private static byte[] encryptData(ByteArrayOutputStream data, byte[] symmetricKey) throws EncryptionException {
try {
SecretKey secKey = new SecretKeySpec(symmetricKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secKey);
return cipher.doFinal(data.toByteArray());
} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException |
InvalidKeyException |
BadPaddingException e) {
throw new EncryptionException(e);
}
}
I have a situation where I need to encrypt data using .NET and decrypt the same data using JAVA. Essentially, I need to rewrite the above encryption method in .NET.
public byte[] Encrypt(byte[] key, byte[] plainText)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
using (ICryptoTransform encryptor = aesProvider.CreateEncryptor(key, magicIV))
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(plainText, 0, plainText.Length);
}
byte[] cipherText = ms.ToArray();
return cipherText;
}
}
}
}
The above code I used somewhere mandates IV which JAVA is not asking for. What is the IV used in JAVA code?
I tried many links which didn't work. Symmetric Encryption between .NET and Java
Please help
If your current Java decryption code also does not ask for an IV (and your decryption returns the same data you encrypted) then Cipher.getInstance("AES")
is returning an object using the ECB block mode.
.NET symmetric algorithms default to the CBC block mode, which requires an IV.
You have a couple of options:
aesProvider.Mode = CipherMode.ECB
before calling CreateEncryptor
.
aesProvider.IV
to the IV parameter of CreateEncryptor
. The IV property will make a cryptographically random value on the first read if it's not set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.