-
-
Save bobgodwinx/91c75ef3d18d2dcc28202f9dcb1f766d to your computer and use it in GitHub Desktop.
How to encrypt data with padding usign AES cipher, complatible with CryptoSwift defaults.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Marcin Krzyżanwski | |
// Code for https://github.com/krzyzanowskim/CryptoSwift/issues/20 | |
// PHP | |
///Please refer to issue: https://github.com/krzyzanowskim/CryptoSwift/issues/20 | |
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