我只想输入字符串并按下解密它。这是我的应用程序,但我无法解密字符串导致_cipher.text
类型'字符串'。它的类型应该是'Encrypted'
onPressed: () {
setState(() {
final k = Key.fromUtf8('1234567891011123');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(k));
final decrypted = encrypter.decrypt(_cipher.text, iv: iv);
_plain.text = decrypted;
});
},
我不想使用final crypted = encrypter.encrypt(_cipher.text, iv: iv);
,因为它是加密的。
不能直接解密字符串。您需要将加密后的数据传入解密,否则在大多数情况下会给出块大小错误。
import 'package:encrypt/encrypt.dart';
void main() {
final cipher = 'Lorem ipsum dolor sit amet';
final k = Key.fromUtf8('1234567891011123');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(k));
final encrypted = encrypter.encrypt(cipher, iv: iv);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
print(encrypted.base64);
print(decrypted);
}
如果您手动将密码设置为base16
或base64
字符串,您可以这样做:
import 'package:encrypt/encrypt.dart';
void main() {
final cipher = 'Xg4+gtUDU0Hd9uMUWU7IJtjxvocKzIOJwumyzbY5n40=';
final k = Key.fromUtf8('1234567891011123');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(k));
final decrypted = encrypter.decrypt(Encrypted.fromBase64(cipher), iv: iv);
print(decrypted);
}
编辑:如果您正在从用户获取密码输入,您需要使用加密器验证,如果它是base16
或base64
,那么您可以继续使用Encrypted.fromBase64(cipher)
或Encrypted.fromBase16(cipher)
进行解密