Results 1 to 2 of 2
Thread: String to byte conversion
- 02-02-2012, 07:41 PM #1
Member
- Join Date
- Jan 2012
- Posts
- 5
- Rep Power
- 0
String to byte conversion
Hi,
I'm using the following code to encrypt a String (inText) whose output is a byte array named cipherText;
The cipherText is printed in a textbox as follows:Java Code:byte[] cipherText; cipherText=cipher.doFinal(inText.getBytes());
Everything works fine until here. However, in the decryption section, I need to get the contents of the textbox as a byte array again. For this purpose, I use the following code:Java Code:encText.setText(new String(cipherText));
When I try to do the encryption it gives a 'bad size' error. I found out that the lenghts of the two byte arrays cipherText and cText aren't equal:Java Code:byte[] cText; cText=encText.getText().toString().getBytes();
The 'result' textbox always prints 'false' meaning that the two byte arrays cipherText and cText aren't equal. However I convert cipherText to a String to print in a textbox and then read the contents of that textbox, convert to String back and then to Byte Aray again. Obviously some data is lost during these conversions. What would you recommend to solve this problem?Java Code:decText.setText(Integer.toString(cText.length)); encText.setText(Integer.toString(cipherText.length)); boolean res=Arrays.equals(cText, cipherText); result.setText(Boolean.toString(res));
Thanks...Last edited by YellowSun; 02-02-2012 at 07:45 PM.
- 02-02-2012, 08:19 PM #2
Re: String to byte conversion
Print them both out to see what the difference is. The Arrays toString() method can format arrays.I found out that the lenghts of the two byte arrays cipherText and cText aren't equal:
If you have non-text values you will need to write a loop and use the Integer.toHexString() method to show the contents of the bytes
If the bytes can contain non-text characters the conversion to String is not symmetric. Several different byte patterns will generate the same character: a '?'
The String class has a constructor that will take a Charset with better encoding/decoding characteristics. To find which one works, fill a byte array with values from 0 to 255, convert to String and then back to an array and compare the input array with the output array to see if all the bytes make it without loss.
Similar Threads
-
Byte[] to string and string to byte[] - for database
By kronox in forum New To JavaReplies: 2Last Post: 11-21-2011, 12:08 AM -
String to Hex Conversion
By mocha in forum New To JavaReplies: 0Last Post: 03-17-2010, 08:45 AM -
image to byte code file conversion
By nupurashi in forum Java TipReplies: 0Last Post: 01-28-2009, 10:25 AM -
String Conversion....
By hotice1027 in forum New To JavaReplies: 8Last Post: 11-28-2008, 10:52 PM -
string conversion??
By j2vdk in forum New To JavaReplies: 13Last Post: 09-19-2008, 03:35 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks