I have an AES encrypted byte array. When I decrypt this array in java application, everything is fine. But in a servlet container, decrypted wrong.
Here ise my byte array
String [] str = new String[] {"41", "23", "67" ,"-124", "-56" ,"-35" ,"89", "-54" ,"-17" ,"-49" ,"-53", "-21" ,"125" ,"4", "98", "-13", "60" ,"-72", "12", "75" ,"-105" ,"-104", "107", "34", "1", "-109", "-19", "-102", "-72", "9" ,"26" ,"-39", "-60", "-15", "0" ,"112", "-5", "-86", "-7", "5" ,"75", "100" ,"94", "-47", "6", "-81", "-22", "82", "97" ,"114", "3", "-24", "-80", "67", "106", "-100" ,"-35", "-83", "54", "-95", "124", "-22", "-100", "-47" };
byte [] inv = new byte[str.length];
int count = 0;
for (String s : str) {
inv[count++] = Byte.valueOf(s);
}
The result of Java Application
Decrypted: 000000.016*kWh|000000.007*kWh|000000.015*kWh|000000.000*kWh
My application code
byte[] keyBytes = "vikoAmrPass12345".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte [] out = cipher.doFinal(inv);
System.out.println("Decrypted: " +new String(out));
My web code which is works on servlet container is definitly same with above one.
But the container decypted result is
'?f ??0??????b]5hJ?F*`U????.8??p@?]?u?~Nb??z?????{3??;?
What is wrong here ?
In my application, I got encrypted byte array as
ServerSocket ss = new ServetSocket(port);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
byte [] sizeBuffer = new byte[5];
in.read(sizeBuffer);
byte [] dataBuffer = new byte[Integer.valueOf(""+new String(sizeBuffer)];
in.read(dataBuffer);
Encrypted data exists on dataBuffer array. And encryption handled in an embedded device.
My configuration
java 1.6
tomcat 7.1
Thanks.
From the code you’ve posted:
That could be the problem. You should never use the platform default encoding if you’re expecting to get the same result in multiple places. Always specify the encoding.
If you’ve done this, it’s also possible that you’ve got problems with how you’re transporting the encrypted data. If you’re ever creating a string from it, you should almost certainly use Base64, e.g. with this library. If you’re using:
Then that will basically be losing information, and could well be the cause of the problem.
EDIT: Okay, so now we know your receiving code is:
Here you have at least three problems:
read, that exact amount of information will be read. There’s a good chance it won’t, particularly for network streams. You should be using the return value ofreadto see how much has actually been read. You either need to loop round until you’ve read all the data required (or run out of data in the stream), or use a higher level API to do the same thing.