Skip to content

Instantly share code, notes, and snippets.

@mllnd
Created March 6, 2019 17:08
Show Gist options
  • Save mllnd/f29bbbd44304e5aae9f9d70c7c54ec1b to your computer and use it in GitHub Desktop.
Save mllnd/f29bbbd44304e5aae9f9d70c7c54ec1b to your computer and use it in GitHub Desktop.
PHP 3DES (Triple DES) Encryption
<?php
$text = 'Super awesome string that goes through encryption';
$secret = 'D05XC051X1KLRWQ8';
$encrypted = encrypt($text, $secret);
echo "Encrypted value: $encrypted\n";
$decrypted = decrypt($encrypted, $secret);
echo "Decrypted value: $decrypted\n";
function encrypt($data, $secret) {
$key = md5(utf8_encode($secret), true);
$key .= substr($key, 0, 8);
$block_size = @mcrypt_get_block_size('tripledes', 'ecb');
$length = strlen($data);
$pad = $block_size - ($length % $block_size);
$data .= str_repeat(chr($pad), $pad);
$encrypted_data = @mcrypt_encrypt('tripledes', $key, $data, 'ecb');
return base64_encode($encrypted_data);
}
function decrypt($data, $secret) {
$key = md5(utf8_encode($secret), true);
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = @mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = @mcrypt_get_block_size('tripledes', 'ecb');
$length = strlen($data);
$pad = ord($data[$length-1]);
return substr($data, 0, strlen($data) - $pad);
}
@musamamasood
Copy link

musamamasood commented Nov 6, 2020

This mcrypt_decrypt has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

@mllnd
Copy link
Author

mllnd commented Nov 6, 2020

This mcrypt_decrypt has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

This snippet was initially added for educational purposes and was never intended to be used in the development of web applications. After all, 3DES is a weak cipher and developers should use more modern and secure ciphers. But thanks for pointing it out that mcrypt has been entirely removed from PHP 7.2. I believe it already had some deprecation warnings when I added the snippet (hence the @ warning suppressors in front of mcrypt method calls) 😉.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment