Flutter中如何将现有AES/CBC/PKCS7Padding加解密代码转换为AES/CBC/PKCS5Padding实现?
Problem Description
I currently have this AES encryption/decryption implementation in Flutter using the encrypt package, which uses AES/CBC/PKCS7Padding:
static String encKey = 'oasterw4567ncdsagfhswtoslfiessgv'; static final key = encrypt.Key.fromUtf8(encKey); static final iv = encrypt.IV.fromLength(16); static final encrypter = encrypt.Encrypter( encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7')); static encryptAES(text) { final encrypted = encrypter.encrypt(text, iv: iv); print("Encrypted " + encrypted.base64); decryptAES(encrypted.base64); return encrypted.base64; } static decryptAES(encText) { String original = encrypter.decrypt(encrypt.Encrypted.from64(encText), iv: iv); print("Decrypt " + original); }
Now my client requires switching to AES/CBC/PKCS5Padding. How should I modify this code?
Answer
Great question! Let's adjust your code and clarify some key points first:
First, a quick note on PKCS5 vs PKCS7 Padding: PKCS5Padding is technically a subset of PKCS7Padding (it only works with 8-byte block sizes), while AES uses a 16-byte block size. However, most modern encryption libraries (including the encrypt package you're using) handle PKCS5Padding correctly for AES by aligning it with the 16-byte block size.
To switch your implementation to AES/CBC/PKCS5Padding, you only need to make one small change to your code: update the padding parameter in the AES constructor from 'PKCS7' to 'PKCS5'.
Here's the modified full code:
static String encKey = 'oasterw4567ncdsagfhswtoslfiessgv'; static final key = encrypt.Key.fromUtf8(encKey); static final iv = encrypt.IV.fromLength(16); static final encrypter = encrypt.Encrypter( // Changed padding from 'PKCS7' to 'PKCS5' encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS5')); static encryptAES(text) { final encrypted = encrypter.encrypt(text, iv: iv); print("Encrypted " + encrypted.base64); decryptAES(encrypted.base64); return encrypted.base64; } static decryptAES(encText) { String original = encrypter.decrypt(encrypt.Encrypted.from64(encText), iv: iv); print("Decrypt " + original); }
Key Notes to Keep in Mind:
- Key Length: Your current key is 32 bytes (256 bits), which is valid for AES-256. This doesn't need to change for PKCS5Padding.
- IV Requirement: CBC mode requires the IV to be the same size as the AES block size (16 bytes). Your
IV.fromLength(16)is correct and should stay as-is. - Cross-System Validation: If you're communicating with another system that uses PKCS5Padding, make sure to test end-to-end encryption/decryption to confirm compatibility (e.g., encrypt in Flutter, decrypt in the target system and vice versa).
内容的提问来源于stack exchange,提问作者amit.flutter

