1

I'm trying to encrypt a message that is in hex and it requires it to be stored into a byteArray. I got it working when i hard code the byte array but I can't get it to work when passed as an string. The hardcoded byteArray looks like

byte secretKeyBytes[] = new byte[] {(byte) 0x80, (byte)0x00, (byte)0x00,(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01};

So i want the user to pass a string like "0x80 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01"

I want to know how to save this string as a byte[] array like above. I have tried to use the .getBytes method but that does not work on the string Can it some how be parsed?

I tried using the method posted on Convert a string representation of a hex dump to a byte array using Java? by @pfranza

        public static  byte[] fromHexString(String s) {
        String v[] = s.split(" "); 
        System.out.println(v.length);
        byte arr [] = new byte[v.length];
        int i = 0;
        for(String val: v) {

            arr[i++] =  Integer.decode("0x" + val).byteValue();
        }
        return arr;

I added a print statement to see the size of the array and it prints out 16 which is right. But i think it is not storing the values correctly in the byte array. When i enter 0x80 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01

I get java.lang.NumberFormatException: For input string: "0x80"

Community
  • 1
  • 1
  • 1
    http://stackoverflow.com/questions/12495619/initialise-and-return-a-byte-array-in-java check this link ,some time it help to you. – uma Oct 24 '15 at 01:12
  • 2
    An idea for parsing: Use the String indexOf method to find the "0x", the substring method to get the next two characters and the Integer class's parseInt method radix=16 with a cast to get the value into a byte. – NormR Oct 24 '15 at 01:26
  • 2
    Possible duplicate of http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java – President James K. Polk Oct 24 '15 at 01:29

0 Answers0