I just want to enter string and on press decrypt it.
this is my app, but I can't decrypt the string cause _cipher.text
type 'String'. it's type should be '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;
});
},
I don't want to use final crypted = encrypter.encrypt(_cipher.text, iv: iv);
cause it comes encrypted.
CodePudding user response:
You can't just directly decrypt the string. You need to pass in the encrypted one into decrypt otherwise it would give block size error in most of the cases.
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);
}
If you have manually set the cipher as base16
or base64
string, you can do this :
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);
}
Edit: If you are taking the cipher input from user you need to validate that using the encrypter if it's a base16
or base64
only then you can continue to decrypt using Encrypted.fromBase64(cipher)
or Encrypted.fromBase16(cipher)