Search code examples
phpcryptographydecodeencode

php obfuscation encrypt/decrypt


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 :)


Solution

  • 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) );