简体   繁体   中英

symmetric encryption in c# resembles JAVA

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:

  • Set aesProvider.Mode = CipherMode.ECB before calling CreateEncryptor .
  • Pass 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.
    • You will need to pass this data to the decryption routine, which should then use "AES/CBC/PKCS5Padding", and set the IV however one does that in Java.
    • One common method of transport is to simply prepend the data to the ciphertext, then just pick off the first 16 bytes at decryption time.
    • DO NOT use a fixed value for an IV, because it's then almost the same as ECB.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM