Decrypting bytes encrypted by .NET's RijndaelM

2019-03-16 22:14发布

问题:

I am trying to decrypt something, which was encrypted using RijndaelManaged of .NET/C#, using Java to decrypt.

The C# program is not mine; I cannot change it to be more interoperable. But I know how it is encrypting:

byte[] bytes = new UnicodeEncoding().GetBytes(password); // edit: built-in is 8chars
FileStream fileStream = new FileStream(outputFile, FileMode.Create);
RijndaelManaged rijndaelManaged = new RijndaelManaged();
CryptoStream cryptoStream = new CryptoStream((Stream) fileStream,
    rijndaelManaged.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);

I do not know how to decrypt this on the Java end. The closest thing to useful I have found is this blog post, but it is light on actual details and I could not implement a decrypter.

Edit: I'm an idiot and now have it working.

UnicodeEncoding is UTF-16LE, while I was using UTF-8. Switching to the proper encoding when plugging the password in has fixed the program.

I also needed to get BouncyCastle and do Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

finaledit: Here's the code to decrypt a default RijndaelManaged stream from .NET in Java, assuming it was created using a raw password as the key:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String password = "kallisti"; // only 8, 12, or 16 chars will work as a key
byte[] key = password.getBytes(Charset.forName("UTF-16LE"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
    new IvParameterSpec(key));
return cipher; // then use CipherInputStream(InputStream, Cipher)

And remember: if you control the C# end, don't use an underived password as your key!

回答1:

It's possible using the standard AES decryption. Rijndel is just a superset of AES which is more lax with particular options. See Rijndael support in Java for more details.

From the answer given in the linked question:

byte[] sessionKey = null; //Where you get this from is beyond the scope of this post
byte[] iv = null ; //Ditto
byte[] plaintext = null; //Whatever you want to encrypt/decrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//You can use ENCRYPT_MODE or DECRYPT_MODE
cipher.calling init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(plaintext);