In Android I have a text string that I read (its bytes) in this way:
String b = "7af18klmo02";
byte[] b=udid.getBytes("UTF-8");
After this, I encrypt the string using a Public Key in this way:
c = Cipher.getInstance("RSA/ECB/NoPadding");
c.init(Cipher.ENCRYPT_MODE, pubKeyNew);
encodeFile = c.doFinal(b);
After this, I try to print out the "encryption result" on the console in this way:
String criptato = null;
try {
criptato = new String(encodeFile, "UTF8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ENCRYPTED STRING: "+criptato);
System.out.println("LENGTH: "+criptato.length());
What I obtain is:
ENCRYPTED STRING: (unreproducible characters)
LENGTH: 244
There are a lot of unreadable characters in the output console. I did not intend to change them, and I think there is some particular encoding I should use to avoid this.
But when I send the encrypted string using a NDEF message throught NFC I obtain a different "string" on Java side that I'm not able to understand:
\x12\t\xc7NL\xb9\xee\xb3\xae\xe4\xa5\xe5\x88\x93\xd6\\=S\xff\xa0'\xf1\xd0\x87\x8bF\xb0\x0cT!\xd6\xca0\x8b\xe5\x13\xfd\x85\xc3=Z,u1\x14}d\x0b5\xe7\x0bBY\xe7$\xee\xc0Z\x150;r\xfa\xce\x93\x90\x0b\xdas\xe6o\xe8\x954._\x93\xa4\xc2\x06\xe3\x84\xf5\xdbw\x91\xd4'%\xf71\xf3B\x9eA=f\r\xaeu\xe5m\x1en\xdaw\x12\xad+\xfe\xb2\x91;\xbe\t\x1dTd\xf5m\t2\xafl<v\xf0\x06\x98)2]\xbeV\x86\xa7\xe7\xe6\xc3\x1f*b\x8c&\xd8ho\x18\x8a;\x8f\x8cW\xb6\x88A\xc9`^\xc2>\xfcQ\x07\x86\xb3\x82\x16\x8b\xed?\xae\xb0\x9bT<\x84y4/\xef\xf9j\xf2\xff\x17\x8d\xfddQN\x84\x97\xf2z\x88RJtw\xe2F5\xcd=l`\x89\xeaN\x86a\xde\xa4\xdb\xb1\x15x\xe4\xf0.\x06\x03\x16|\xfee\xbf\x8a\x81_\x86\xbc\x83\xd9 \xbc;\x16V.]\xb4\xf9\t>?{\xcdF\xa8\x82\x08\xe0\\L
LENGTH: 700
I am running under Ubuntu 13.04
Is this ISO 8859-15 encoding or what?
Why final length is 700 instead of original 244?
How can I convert these characters in UTF-8 so that i can decrypt them to obtain my original string?
Any help is much appreciated.
This is broken code:
criptato = new String(encodeFile, "UTF8");
The contents of encodeFile
is not UTF-8-encoded text. It's not text in any encoding - it's arbitrary binary data. Don't convert the byte[]
into a String
using the String
constructor like this when you have arbitrary binary data.
Instead, convert it to hex or base64. Those are both explicitly designed to encode arbitrary binary data in ASCII text so that it can later be decoded to the original binary data.
See more on this question at Stackoverflow