How Can I solve this Error:
Unhandled Exception: Invalid argument(s): Key length not 128/192/256 bits.
in this flutter code:
final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
final encrypt.Key key = encrypt.Key.fromUtf8(
phoneId.length > 32 ? phoneId.substring(0, 32) : phoneId);
final encrypt.IV iv = encrypt.IV.fromLength(16);
final encrypt.Encrypter encrypter = encrypt.Encrypter(encrypt.AES(key));
final String encrypted =
encrypter.encrypt(timestamp + phoneId, iv: iv).base16;
Thank you.
0
This is because the key
is not 32 characters
long. Please step into your code and verify the key is 32 characters
long.
The key that I used is secretkey:hapilyeverafter1234567
it should be a secret securely stored in a config file.
Also, in your code I assume the phoneId
is always longer than 32 characters. then you can use phoneId
instead of the key
that I used.
Essentially key must be 32 chars long
it was not in your case that was the issue.
I have changed your code like below and it works.
String phoneId = "324234234234234";
//final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
//final encrypt.Key key = encrypt.Key.fromUtf8(
// phoneId.length > 32 ? phoneId.substring(0, 32) : phoneId);
//create a 32 chars long key
final key = encrypt.Key.fromUtf8('secretkey:hapilyeverafter1234567'); // 32 chars
final encrypt.IV iv = encrypt.IV.fromLength(16);
final encrypt.Encrypter encrypter = encrypt.Encrypter(encrypt.AES(key));
final encrypted = encrypter.encrypt(phoneId, iv: iv);
print('Encrypted Phone Number: ${encrypted.base64}');
final decrypted = encrypter.decrypt(encrypted, iv: iv);
print('Decrypted Phone Number: $decrypted');