解密由.NET的RijndaelManaged使用Java加密的字节

时间:2011-05-21 22:46:56

标签: c# java .net aes rijndaelmanaged

我正在尝试解密使用RijndaelManaged of .NET / C#加密的东西,使用Java解密。

C#程序不是我的;我无法将其更改为更具互操作性。但我知道它是如何加密的:

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);

我不知道如何在Java端解密这个问题。我找到的最接近有用的是this blog post,但它对实际细节很清楚,我无法实现解密器。

编辑:我是个白痴,现在已经开始工作了。

UnicodeEncoding是UTF-16LE,而我使用的是UTF-8。在插入密码时切换到正确的编码已修复程序。

我还需要获得BouncyCastle并执行Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

finaledit:这是用Java解密来自.NET的默认 RijndaelManaged流的代码,假设它是使用原始密码作为密钥创建的:

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)

请记住:如果您控制C#端,请不要使用未获得的密码作为密钥!

1 个答案:

答案 0 :(得分:3)

可以使用标准AES解密。 Rijndel只是AES的超集,它在特定选项上更加宽松。有关详细信息,请参阅Rijndael support in Java

从链接问题中给出的答案:

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);