Last active
November 5, 2018 18:58
-
-
Save echr/cda94664c9538ac2f618b98669f0b1dc to your computer and use it in GitHub Desktop.
PHP AES-128-ECB Encrypt Test
This file contains 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 | |
error_reporting(E_ALL ^ E_DEPRECATED); | |
class PHP_AES_Cipher { | |
static function encrypt($str, $key) { | |
$block = mcrypt_get_block_size('rijndael_128', 'ecb'); | |
$pad = $block - (strlen($str) % $block); | |
$str .= str_repeat(chr($pad), $pad); | |
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB); | |
} | |
static function decrypt($str, $key){ | |
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB); | |
return $str; | |
} | |
static function hex2bin($hexstr) { | |
$n = strlen($hexstr); | |
$sbin = ""; | |
$i = 0; | |
while ($i < $n) { | |
$a = substr($hexstr, $i, 2); | |
$c = pack("H*", $a); | |
if ($i == 0) { | |
$sbin = $c; | |
} else { | |
$sbin.=$c; | |
} | |
$i+=2; | |
} | |
return $sbin; | |
} | |
} | |
//Code to Test | |
$key = 'BDE540BD7E96ECAB33D0216EF003F53C'; | |
$data = "9996575408"; | |
$javaEqualizer = "0B4547B67E1585D6741535763E71B276"; # hasil dari jar JAVA | |
echo "Key: $key <br><br>"; | |
echo "Data: $data <br><br>"; | |
$encrypted = strtoupper(bin2hex(PHP_AES_Cipher::encrypt($data, hex2bin($key)))); | |
echo "Encrypted Payload: $encrypted <br><br>"; | |
echo "Is Encryption equal with java result: " . ($encrypted == $javaEqualizer ? '<b>YES</b>' : '<b>NO</b>') . "<br/><br/>"; | |
$decryptedPayload = PHP_AES_Cipher::decrypt(hex2bin($encrypted), hex2bin($key)); | |
echo "Decrypted Payload: $decryptedPayload <br><br>"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment