简体   繁体   English

使用 java 解密 C# 中的 AES 加密文件

[英]Decrypting AES encrypted file in C# with java

I have the following problem.我有以下问题。 I use this code to encrypt a sample text in C#, and want to decrypt it in java.我使用代码加密 C# 中的示例文本,并希望在 java 中对其进行解密。 I use the following java code.我使用以下 java 代码。

byte[] IV = { 65, 1, 2, 23, 4, 5, 6, 7, 32, 21, 10, 11, 12, 13, 84, 45 };
byte[] KEY = { 0, 42, 2, 54, 4, 45, 6, 7, 65, 9, 54, 11, 12, 13, 60, 15 };
byte baData[] = new byte[1024];
int iRead = 0;

SecretKeySpec key = new SecretKeySpec(KEY, "AES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV));

File file = new File("/sdcard", "SAMPLE.txt");

FileInputStream in = new FileInputStream(file);
iRead = in.read(baData, 0, baData.length);

String strResult = new String(cipher.doFinal(baData, 0, baData.length));

I obviously use the same IV and KEY values above as in the C# sample.我显然使用了与 C# 示例中相同的 IV 和 KEY 值。 The above java code runs on an android device, and the encrypted binary file is the SAMPLE.txt on it's sdcard.上面的 java 代码在 android 设备上运行,加密的二进制文件是它的 sdcard 上的 SAMPLE.txt。 The problem is I don't get the correct data after decrypting it.问题是解密后我没有得到正确的数据。 Can anyone tell me what I'm doing wrong?谁能告诉我我做错了什么?

Thanks.谢谢。

There are a few problems here:这里有几个问题:

  • What encoding are you using to convert the text data into binary before encrypting it?在加密之前,您使用什么编码将文本数据转换为二进制? Your current use of the string constructor will use the platform default encoding - almost never a good idea您当前对字符串构造函数的使用将使用平台默认编码 - 几乎不是一个好主意
  • You're assuming that a single call to read() will read everything - you're not actually using the value of iRead later假设read()的一次调用将读取所有内容-您实际上并没有稍后使用iRead的值
  • You're assuming that all the data will fit in a 1024-byte buffer假设所有数据都适合 1024 字节的缓冲区

It's hard to know which of those is causing the problem.很难知道是哪一个导致了问题。

I would strongly suggest that you use a CipherInputStream to wrap your FileInputStream , and then wrap an InputStreamReader around that, using the appropriate encoding.我强烈建议您使用CipherInputStream来包装FileInputStream ,然后使用适当的编码将InputStreamReader包装在其周围。 You could then use something like Guava's CharStreams.toString() method to read everything from the InputStreamReader into a string.然后,您可以使用 Guava 的CharStreams.toString()方法将InputStreamReader中的所有内容读入字符串。

EDIT: As noted in comments, while all of these are potential problems, there's also the matter of the code currently creating the Cipher in encryption mode rather than decryption mode.编辑:正如评论中所指出的,虽然所有这些都是潜在的问题,但目前在加密模式而不是解密模式下创建Cipher的代码也有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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