Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Swift compatible AES Encryption and Decryption with PHP and mcrypt
<?php
// Credit should be given to;
// https://gist.github.com/bradbernard/7789c2dd8d17c2d8304b#file-php-encyrption
// https://gist.github.com/krzyzanowskim/043be69ab3ba9fd5ba58#file-encryptaeswithphp
$data = '{"verification_code":"123456"}';
$key = '1234567890123456';
function aesEncrypt($data, $key) {
$data = addPadding($data);
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$cipherText = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$result = base64_encode($iv.$cipherText);
return $result;
}
function aesDecrypt($base64encodedCipherText, $key) {
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$cipherText = base64_decode($base64encodedCipherText);
if (strlen($cipherText) < $ivSize) {
throw new Exception('Missing initialization vector');
}
$iv = substr($cipherText, 0, $ivSize);
$cipherText = substr($cipherText, $ivSize);
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipherText, MCRYPT_MODE_CBC, $iv);
$result = stripPadding(rtrim($result, chr(0x0b)));
return $result;
}
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);
}
$base64encodedCipherText = aesEncrypt($data, $key);
print($base64encodedCipherText);
print("<br />");
$decryptedText = aesDecrypt($base64encodedCipherText, $key);
print($decryptedText);
print("<br />");
$base64encodedCipherText2 = "aAQ7PWP50FtUv37VxItEIVl6kPXdFm/xiA1ROxAuKthmCj4+L4CWix4pyzbq+I/q"; // Encoded and Ciphered string generated by Swift
$decryptedText2 = stripPadding(aesDecrypt($base64encodedCipherText2, $key));
print($decryptedText2);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment