| Author |
Convert byte[] to String
|
Tay Thotheolh
Ranch Hand
Joined: Aug 07, 2008
Posts: 84
|
|
|
Hi. How do I convert byte[] to String like 'AEUKHJBJKBJJKBKJBKBB...' ? I am trying to encrypt a file and it returns a byte[]. I want to write the encrypted content to a file to store it so I thought it would be best to write to some String like the above mentioned. How do I do so ?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
Tay Thotheolh wrote:Hi. How do I convert byte[] to String like 'AEUKHJBJKBJJKBKJBKBB...' ? I am trying to encrypt a file and it returns a byte[]. I want to write the encrypted content to a file to store it so I thought it would be best to write to some String like the above mentioned. How do I do so ?
It depends on the type of file. There is a constructor that takes a byte array, but keep in mind that the result of an encryption should be binary data. So, you'll have a string that is binary data -- which doesn't work very well if you write it to a text file. And... if you are going to write to a binary file, it may be best to write the byte array directly.
Anyway, if it is a text file, then you need to encode the string... convert the binary data to a readable string. Base64 encoding is probably the most common encoding standard. And there should be Java libs for that.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Pat Farrell
Rancher
Joined: Aug 11, 2007
Posts: 4442
|
|
Tay Thotheolh wrote:I want to write the encrypted content to a file to store it
Be very careful. Nearly all encryption/decryption algorithms are defined only on arrays of unsigned octets (roughly byte[])
These are not directly transferable to Java Strings without care or something like MIME-encoding. Just getting the bytes out of the String is not enough, as String are all Unicode, which convert to two or even three characters when you properly handle international encodings.
|
 |
Tay Thotheolh
Ranch Hand
Joined: Aug 07, 2008
Posts: 84
|
|
Thanks. I would look into the encoding.
|
 |
 |
|
|
subject: Convert byte[] to String
|
|
|