Skip to content

Instantly share code, notes, and snippets.

@poszlo
Forked from krzyzanowskim/EncryptAESWithPHP
Created April 20, 2016 12:38
Show Gist options
  • Save poszlo/3dc1d3e116c54658c623e6fce4161169 to your computer and use it in GitHub Desktop.
Save poszlo/3dc1d3e116c54658c623e6fce4161169 to your computer and use it in GitHub Desktop.
How to encrypt data with padding usign AES cipher, complatible with CryptoSwift defaults.
// Marcin Krzyżanwski
// Code for https://github.com/krzyzanowskim/CryptoSwift/issues/20
// PHP
function encrypt($plaintext, $key, $iv) {
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
return base64_encode($ciphertext);
}
function decrypt($ciphertext_base64, $key, $iv) {
$ciphertext = base64_decode($ciphertext_base64);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
return $plaintext;
}
function addPadding($value)
{
$pad = 16 - (strlen($value) % 16);
return $value.str_repeat(chr($pad), $pad);
}
function stripPadding($value)
{
$pad = ord($value[($len = strlen($value)) - 1]);
return paddingIsValid($pad, $value) ? substr($value, 0, $len - $pad) : $value;
}
function paddingIsValid($pad, $value)
{
$beforePad = strlen($value) - $pad;
return substr($value, $beforePad) == str_repeat(substr($value, -1), $pad);
}
// Generate IV
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
// Encrypt
$ciphertext_base64 = encrypt(addPadding("data"), "abcdefghijklmnop", $iv);
print $ciphertext_base64."\n";
// Decrypt
$plaintext = stripPadding(decrypt($ciphertext_base64, "abcdefghijklmnop", $iv));
print $plaintext."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment