在使用AES 256加密和解密过程中,有时会发现解密过程中会获取额外的垃圾数据,这是由于加密时使用的PKCS7填充方式与解密时使用的不一致导致的。我们可以通过使用同样的填充方式来解决这个问题,代码示例如下:
使用phpseclib和PKCS7填充方式进行AES 256加密和解密:
include_once 'Crypt/AES.php';
$key = '01234567890123456789012345678901'; // 32 bytes key
$iv = '0123456789012345'; // 16 bytes iv
$plaintext = 'This is test data.';
// Encrypt using phpseclib and PKCS7 padding
$aes = new Crypt_AES(CRYPT_AES_MODE_CBC);
$aes->setKey($key);
$aes->setIV($iv);
$aes->setPadding(CRYPT_AES_PADDING_PKCS7);
$ciphertext = base64_encode($aes->encrypt($plaintext));
// Decrypt using phpseclib and PKCS7 padding
$aes = new Crypt_AES(CRYPT_AES_MODE_CBC);
$aes->setKey($key);
$aes->setIV($iv);
$aes->setPadding(CRYPT_AES_PADDING_PKCS7);
$decrypted = $aes->decrypt(base64_decode($ciphertext));
使用openssl和PKCS7填充方式进行AES 256加密和解密:
$key = '01234567890123456789012345678901'; // 32 bytes key
$iv = '0123456789012345'; // 16 bytes iv
$plaintext = 'This is test data.';
// Encrypt using openssl and PKCS7 padding
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$ciphertext = base64_encode($ciphertext);
// Decrypt using openssl and PKCS7 padding
$decrypted = openssl_decrypt(base64_decode($ciphertext), 'aes-256-cbc', $key, OPENSSL
下一篇:AES256解密在c#中如何实现