开发者

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. I use the following java code.

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");
ci开发者_如何转开发pher.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. The above java code runs on an android device, and the encrypted binary file is the SAMPLE.txt on it's sdcard. 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
  • You're assuming that all the data will fit in a 1024-byte buffer

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. You could then use something like Guava's CharStreams.toString() method to read everything from the InputStreamReader into a string.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜