Reputation: 125
I have to change java code for decrypt to flutter code. I use library "encrypt" for flutter. my flutter code show
Key length not 128/192/256 bits.
my java spring boot code.
public static String decryptAES256(String str, String secretKey) throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
String AES = "AES";
String AES_PADDING = "AES/CBC/PKCS5Padding";
byte[] keyData = java.util.Base64.getDecoder().decode(secretKey);
String iv = secretKey.substring(0, 16);
SecretKey secureKey = new SecretKeySpec(keyData, AES);
Cipher c = Cipher.getInstance(AES_PADDING);
c.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)));
byte[] byteStr = Base64.getDecoder().decode(str.getBytes());
return new String(c.doFinal(byteStr), StandardCharsets.UTF_8);
}
my flutter code.
final encData = codefModel.data!.encData!;
final key = en.Key.fromUtf8(decryptKey);
final b64key = en.Key.fromUtf8(base64Url.encode(key.bytes));
final iv = en.IV.fromLength(16);
final encrypter = en.Encrypter(en.AES(b64key, mode: en.AESMode.cbc));
logger.d(encrypter.decrypt64(encData, iv: iv));
Upvotes: 0
Views: 327
Reputation: 49276
From the Java code it can be deduced that the AES key secretKey
and the ciphertext str
are Base64 encoded. The first 16 bytes of the Base64 encoded key (not of the raw key!) are used as IV.
In the Dart code the key is incorrectly converted and a wrong IV is used. A possible fix is (together with sample data):
const decryptKey = "MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDE=";
const encData = "lo0dOoJrHNRuefPXgkEa6jtDUhV5CguF9MHWTJ4Y8eGP8zHaKJEQIuOTZxstyk3X";
final key = en.Key.fromBase64(decryptKey);
final iv = en.IV(Uint8List.fromList(utf8.encode(decryptKey).sublist(0, 16)));
final encrypter = en.Encrypter(en.AES(key, mode: en.AESMode.cbc));
final decrypted = encrypter.decrypt64(encData, iv: iv); // The quick brown fox jumps over the lazy dog
As test, key and ciphertext can be used in the Java code that returns the same plaintext for them.
Be aware that deriving the IV from the key is generally insecure, since encryptions with the same key automatically lead to the reuse of key/IV pairs. Instead, a random IV should be used for each encryption.
Upvotes: 1