Flutter如何实现AES-128-CBC加密与解密
在Flutter中如何正确实现AES-128-CBC模式的加密与解密?我尝试使用encrypt包,但解密时总是报错,不知道是不是IV或填充方式的问题。希望能提供一个完整的示例代码,包括密钥和IV的处理步骤。
        
          2 回复
        
      
      
        使用encrypt包。加密时,通过AES类创建加密器,使用CBC模式,配合PKCS7填充。需提供16字节密钥和IV。解密同理,调用decrypt方法即可。
更多关于Flutter如何实现AES-128-CBC加密与解密的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现AES-128-CBC加密与解密,可以使用encrypt包。以下是完整实现步骤:
- 添加依赖
在pubspec.yaml中添加:
dependencies:
  encrypt: ^5.0.1
- 加密实现
import 'package:encrypt/encrypt.dart';
String encryptAES128CBC(String plaintext, String key, String iv) {
  final encrypter = Encrypter(AES(
    Key.fromUtf8(key),
    mode: AESMode.cbc,
  ));
  final encrypted = encrypter.encrypt(plaintext, iv: IV.fromUtf8(iv));
  return encrypted.base64;
}
- 解密实现
String decryptAES128CBC(String ciphertext, String key, String iv) {
  final encrypter = Encrypter(AES(
    Key.fromUtf8(key),
    mode: AESMode.cbc,
  ));
  final decrypted = encrypter.decrypt64(ciphertext, iv: IV.fromUtf8(iv));
  return decrypted;
}
- 使用示例
void main() {
  final key = '1234567890123456'; // 16字符长度
  final iv = 'abcdefghijklmnop';  // 16字符长度
  final plaintext = 'Hello World';
  
  // 加密
  final encrypted = encryptAES128CBC(plaintext, key, iv);
  print('加密结果: $encrypted');
  
  // 解密
  final decrypted = decryptAES128CBC(encrypted, key, iv);
  print('解密结果: $decrypted');
}
重要说明:
- 密钥(key)必须为16字节(128位)
- 初始向量(iv)必须为16字节
- 确保密钥和IV安全存储,不要硬编码在代码中
- 此示例使用UTF8编码,如需其他编码请调整fromUtf8方法
实际使用时建议将密钥和IV通过安全方式存储,如Flutter Secure Storage。
 
        
       
             
             
            

