Forked from tlarevo/swift-compatible-php-aes-encryption-using-mcrypt.php
Created
April 30, 2018 15:48
-
-
Save bobgodwinx/09fd85603cde6e3b72a9ab2d06a4530a to your computer and use it in GitHub Desktop.
Swift compatible AES Encryption and Decryption with PHP and mcrypt
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
<?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