3

I am using the Android javax API to encrypt a string which returns a byte array which I again convert into String (purpose is to write to textfile later).

Now using this String, I convert to byte array to decrypt which returns another byte array which I convert again to String.

I could not get this to work. I narrowed down the issue to the string conversion to byte array portion. Because if i use the encrpted byte array to decrypt and then get the String it works.

Not sure what's the issue. I have used the following for the conversion:

String str;
Byte [] theByteArray = str.getBytes("UTF-8");
String val = new String (theByteArray , "UTF-8");

and 

Byte [] theByteArray = str.getBytes();
String val = new String (theByteArray);

What is the best way to convert from byte array to string and vice versa without losing anything?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
aandroidtest
  • 1,493
  • 8
  • 41
  • 68
  • Possible duplicate of [how to convert byte array to string and vice versa](http://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa) – lxknvlk Oct 22 '16 at 12:59

2 Answers2

3

You can use apache library's Hex class. It provides decode and encode functions.

String s = "42Gears Mobility Systems";
byte[] bytes = Hex.decodeHex(s.toCharArray());

String s2 = new String(Hex.encodeHex(bytes));
PC.
  • 6,870
  • 5
  • 36
  • 71
0

If you really need another way to store the byte array to string and vice versa, the best way is to use Base64 encoding so that you don't lose any data. Here is the link where you can download the zip. Extract the zip and include the class file in your project. Then use the following code snippets wherever you need to encode and decode.

//To encode the data and convert into a string

ByteArrayOutputStream bao = new ByteArrayOutputStream();
 bitMap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
  byte [] ba = bao.toByteArray();
  String ba1=Base64.encodeBytes(ba);

//To decode the data into byte array again

try{
            byte[] ba3 = Base64.decode(ba1);

    }catch(Exception e)
            {

            }
Kanth
  • 6,681
  • 3
  • 29
  • 41
  • Hi, I have tried the Base64 but when I am reading a Base64 encoded string from a textfile to decode, it is showing me bad base 64 error. Any idea what's wrong? – aandroidtest Nov 23 '12 at 07:27
  • @aandroidtest You might have gone wrong somewhere. Paste your code and particularly the snippets where you are applying this mechanism and logcat too if possible. Unless that it is difficult to answer.. – Kanth Nov 23 '12 at 11:42