MCrypt實現AES加解密
<?php
define( "KEY", "16位" );
define( "IV", "16位" );
function aes_encode( $sourcestr ) {
return base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_128, KEY, $sourcestr, MCRYPT_MODE_CBC, IV ) );
}
function aes_decode( $crypttext ) {
return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, KEY, base64_decode( $crypttext ), MCRYPT_MODE_CBC, IV );
}
$source = '{"token": "asdf"}';
echo aes_encode($source);
echo PHP_EOL;
$source ='mWjO06XV8BwMAJG1uKX+N8ITdkuHyPxRFepTYZNNeQU=';
echo aes_decode($source);
複製程式碼
OpenSSL實現AES加解密
<?php
define( "KEY", "16位" );
define( "IV", "16位" );
function aes_encode( $sourcestr ) {
$padded_data = $sourcestr . str_repeat(chr(0), 16 - (strlen($sourcestr) % 16));
return base64_encode(openssl_encrypt($padded_data, 'aes-128-cbc', KEY, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, IV));
}
function aes_decode( $crypttext ) {
return trim(openssl_decrypt(base64_decode($crypttext), "aes-128-cbc", KEY, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, IV));
}
$source = '{"token": "asdf"}';
var_dump(aes_encode($source));
$tmp = 'mWjO06XV8BwMAJG1uKX+N8ITdkuHyPxRFepTYZNNeQU=';
var_dump(aes_decode($tmp));
複製程式碼
特殊說明: KEY的長度不同會影響到
OpenSSL
中aes-x-cbc
是選擇128,192還是256。
KEY的長度 | aes-x-cbc |
---|---|
16 | aes-128-cbc |
24 | aes-192-cbc |
32 | aes-256-cbc |