Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert byte[] to String

 
Tay Thotheolh
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20999
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I would look into the encoding.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic