duankao4489 2010-11-10 12:36
浏览 85
已采纳

php obfuscation加密/解密

Is there a way to encode/decode a string using a secret key. I will use base64 to give you an example what im looking for.

<?php 

$secret = 'abc123'; 
$string = 'Hello World';
$en = base64_encode($string,$secret);//encoded output returns here

echo base64_decode($en,$secret);//output: "Hello World"

?>

so basically im asking to use a key/salt, to encode a text and then decode it back only using that same secret key. otherwise there should be a wrong output :)

  • 写回答

4条回答 默认 最新

  • donglang8008 2010-11-10 12:54
    关注

    You probably want to use the mcrypt extension for PHP.

    The following might be a bit overkill depending on what you want to do, but the security is pretty much guaranteed if you keep your keys safe, as AES has yet to be broken :)

    function enc_aes($str, $key, $iv) {
        $aes = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        if (!$aes) die("<b>mcrypt_module_open failed!</b>");
        (mcrypt_generic_init($aes, $key, $iv) != -1) or die("<b>mcrypt_generic_init failed!</b>");
    
        // PHP will pad query with \0 to multiple of block size
        $ret = mcrypt_generic($aes, $str);
        mcrypt_generic_deinit($aes);
        return $ret;
    }
    
    function dec_aes($str, $key, $iv) {
        $aes = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        if (!$aes) die("<b>mcrypt_module_open failed!</b>");
        (mcrypt_generic_init($aes, $key, $iv) != -1) or die("<b>mcrypt_generic_init failed!    </b>");
    
        // PHP will pad query with \0 to multiple of block size
        $ret = mdecrypt_generic($aes, $str);
        mcrypt_generic_deinit($aes);
        return $ret;
    }
    
    // Specifying key & IV as hex. Obviously doing so in the source is rather unsafe...
    
    // For example. Key is 128-bits
    $key = pack("H*", "0123456789ABCDEFFEDBCA9876543210");
    
    // For example. Initialization Vector is 64-bits
    $iv = pack("H*", "0123456789ABCDEF");
    $encrypted_string = enc_aes("decrypted string", $key, $iv);
    
    // Should output "decrypted string" :]
    print( dec_aes($encrypted_string, $key, $iv) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来