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 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改