Skip to content

Instantly share code, notes, and snippets.

@orrisroot
Last active March 27, 2017 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orrisroot/c446b5f5455a9134be97d8309d507297 to your computer and use it in GitHub Desktop.
Save orrisroot/c446b5f5455a9134be97d8309d507297 to your computer and use it in GitHub Desktop.
<?php
$text = 'hkHlLFwvwYoo1IcY';
//$text = 'hkHlLFwvwYoo1I';
//$text = 'hkHlLFwv';
$key = md5('SAMPLE SALT');
$em = encrypt_m($text, $key);
$eo = encrypt_o($text, $key);
echo 'encrypt_m()'.PHP_EOL;
var_dump($em, bin2hex($em));
echo 'encrypt_o()'.PHP_EOL;
var_dump($eo, bin2hex($eo));
$dmm = decrypt_m($em, $key);
$dmo = decrypt_o($em, $key);
$dom = decrypt_m($eo, $key);
$doo = decrypt_o($eo, $key);
echo 'encrypt_m() -> decrpyt_m()'.PHP_EOL;
var_dump($dmm, bin2hex($dmm));
echo 'encrypt_m() -> decrpyt_o()'.PHP_EOL;
var_dump($dmo, bin2hex($dmo));
echo 'encrypt_o() -> decrpyt_m()'.PHP_EOL;
var_dump($dom, bin2hex($dom));
echo 'encrypt_o() -> decrpyt_o()'.PHP_EOL;
var_dump($doo, bin2hex($doo));
function remove_padding($plain_text)
{
// remove zero padding for mcrypt encrypted text
$plain_text = rtrim($plain_text, "\0");
// remove pkcs#7 padding for openssl encrypted text if padding string found
$pad_ch = substr($plain_text, -1);
$pad_len = ord($pad_ch);
$pad_text = str_repeat($pad_ch, $pad_len);
if (substr_compare($plain_text, $pad_text, -$pad_len) == 0) {
$plain_text = substr($plain_text, 0, strlen($plain_text) - $pad_len);
}
return $plain_text;
}
function encrypt_o($plain_text, $key)
{
$crypt_text = openssl_encrypt($plain_text, 'DES-ECB', substr($key, 0, 8));
return $crypt_text;
}
function decrypt_o($crypt_text, $key)
{
$plain_text = openssl_decrypt($crypt_text, 'DES-ECB', substr($key, 0, 8), OPENSSL_ZERO_PADDING);
$plain_text = remove_padding($plain_text);
return $plain_text;
}
function encrypt_m($plain_text, $key)
{
$td = mcrypt_module_open('des', '', 'ecb', '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
if (mcrypt_generic_init($td, $key, 'iv_dummy') < 0) {
return $plain_text;
}
$crypt_text = base64_encode(mcrypt_generic($td, $plain_text));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $crypt_text;
}
function decrypt_m($crypt_text, $key)
{
$td = mcrypt_module_open('des', '', 'ecb', '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
if (mcrypt_generic_init($td, $key, 'iv_dummy') < 0) {
return $text;
}
$plain_text = mdecrypt_generic($td, base64_decode($crypt_text));
$plain_text = remove_padding($plain_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $plain_text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment