Reputation: 3758
I import an XML file as a byte array to the project
RandomAccessFile rnd = new RandomAccessFile(filePath, "r");
byte[] fileData = new byte[(int) rnd.length()];
rnd.read(fileData);
I encrypted the array using java.crypto
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte[] encypted = new byte[cipher.getOutputSize(fileData.length)];
int len = cipher.update(fileData, 0, fileData.length, encypted, 0);
len += cipher.doFinal(encypted, len);
When I decrypt the byte array and print it using
System.out.println(new String(decrypted, "UTF-8"));
I got the XML file but there were some unkown characters at the end (they are only at the end). Is there any way I can remove this?
Thanks in advance
Upvotes: 0
Views: 484
Reputation: 3758
I changed the padding and it worked.
cipher = Cipher.getInstance("DESede/CFB8/NoPadding");
Upvotes: -1
Reputation: 42009
There is a lot of missing code that might be important. One thing that I note is that you are reading the data in without any character encoding specified, then upon decryption your are creating a string using a UTF-8 decoder. That only makes sense if the original XML file was UTF-8 encoded, which is entirely possible. Also, RandomAccessFile.read()
returns an int containing the number of bytes actually read. You're supposed to use that number rather than assuming that the entire array is read in.
Upvotes: 0
Reputation: 36423
see a similar question here, the answer though is what might be very relavent to your situation:
1.If you don't know what padding was used to encrypt, then decrypt with 'no padding' set. That will decrypt everything, including the padding, and won't throw an error because of mismatched padding.
2.When you have decrypted the cyphertext, have a look at the last block of the output and see what padding was used. Different paddings leave different byte patterns, so it is usually easy enough to tell.
3.Set your decryption method to expect the correct type of padding, and it will be automatically removed for you.
and incase this is relavant to you here is a link on padding patterns etc: Padding Wikipedia
This over here is also a very good tutorial for encrypting using DES: http://www.exampledepot.com/egs/javax.crypto/desstring.html and here is for PBE in DES: PBE with HMAC(SHA1) and DES(EDE)
Upvotes: 2