1

I am stuck with casting issue for converting a byte String to byte array.

i.e I have a String "[B@1a758cb". That is Base64 encrypted String of the main String "gunjan". Here for decryption I want to convert that encrypted byte string to byte[].

But String.getByte[] is not working for me. String.getBytes[] gives bytes of the byte String.

How can I do that ?? Do I have to iterate over each character in the byte string and to convert them to byte[] ??

EDITED

I am using Apache Coded 3.1 jar for Base64 conversion. Here is the code from which I am getting this encrypted text..

String in = "gunjan";
byte[] byteStr = in.getBytes();
byte[] base64Encoded = Base64.encodeBase64(byteStr);

Here the value of base64Encoded is [B@1a758cb You can also see the console log in the image..enter image description here

Gunjan Shah
  • 5,088
  • 16
  • 53
  • 72

1 Answers1

6

First of all, you don't have any problem here, since the decoded string value (gunjan) is equal to the original value (gunjan).

You're confused by what is printed for the intermediate byte arrays. As noted in the comments, the strings [@Bxxxx are the result of calling toString() on a byte array. This desn't display the value of the bytes, but the type of the array ([@B) followed by the hashCode of the array object. If you want to display the byte values, use

System.out.println(Arrays.toString(byteArray));

You have a potential bug though: you're using the default encoding to transform strings to bytes and vice-versa. This encoding might not be able to support every character in your String. You should use a specific encoding that supports every character on earth, like UTF8:

byte[] byteStr = string.getBytes("UTF8");
...
String str = new String (byteStr, "UTF8");
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks for the reply. Here I have given the example only to show,how I am encrypting the text. My main problem is that I have encrypted text "[B@1a758cb" that is stored in String variable. How can I convert that to byte[]. String.getByte[] is not working here. – Gunjan Shah Apr 20 '13 at 12:18
  • Also see this post : http://stackoverflow.com/questions/5499924/convert-java-string-to-byte-array/5500020#5500020 this is very similar to my problem.. – Gunjan Shah Apr 20 '13 at 12:19
  • You're not encrypting anything. You're encoding a string to base 64, and then decoding the encoded string, which succeeds since you get the original string back. So what's the problem? Have you read and understood my answer? String.getBytes() transforms a string into a byte array. What is not working? Show us a clear piece of code, tell us what you expect it to do, and what it does instead. – JB Nizet Apr 20 '13 at 12:24
  • sorry.. i am misguiding you. You are right, I have done encoding. By mistake I have used that word "encryption" – Gunjan Shah Apr 20 '13 at 12:27