erp
erp

Reputation: 3024

How do I turn a hex string directly into a byte array?

I want to convert a string into hex, then into a byte array. Here is my code so far:

public static void findKey(){

    Cipher cipher;
    SecretKeySpec key;
    byte [] keyBytes;
    byte [] pt;
    byte [] ct;

    String plaintext = "Plaintxt";
    ct = new byte [] {(byte)0x4A, (byte)0xC4, (byte)0x55, (byte)0x3D, (byte)0xB3, (byte)0x37, (byte)0xCA, (byte)0xB3};
    String ptHex = asciiToHex(plaintext);
    System.out.println(ptHex);
    pt = ptHex.getBytes();
    printByteArray(pt);
}

My method to convert to hex works fine, but when I use getBytes, it obviously turns it to 16 bytes which is not what I want. That was just an attempt. Here is the output from just printing my string to make sure it worked and then printing the byte array which is incorrect:

506c61696e747874
[  35  30  36  63  36  31  36  39  36  65  37  34  37  38  37  34  ]
-------------Key  Found-------------

I want to take the 50, the 6c, the 61 etc., and put it into a byte array like I did for ct like 0x50, 0x6c, and so on.

Is this even possible?

Upvotes: 1

Views: 698

Answers (4)

Ankit Singla
Ankit Singla

Reputation: 198

Simple java method for converting hex to byte array:

byte[] byteArray= new BigInteger(hexvalue, 2).toByteArray();

Upvotes: 0

Bohemian
Bohemian

Reputation: 425308

Use this one-liner, which employs the JDK's API:

byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();

Here's a test:

import java.nio.ByteBuffer;

public static void main(String[] args) throws Exception {
    String chars= "506c61696e747874";
    byte[] array = ByteBuffer.allocate(8).putLong(Long.parseLong(chars, 16)).array();
    System.out.println(Arrays.toString(array));
}

Output:

[80, 108, 97, 105, 110, 116, 120, 116]

Of course the output here is in decimal, but the values are correct.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

try

byte[] getBytes(String s) {
    byte[] a = new byte[s.length() / 2];
    for (int i = 0; i < a.length; i++) {
        a[i] = Byte.parseByte(s.substring(i * 2, i * 2 + 2), 16);
    }
    return a;
}

Upvotes: 2

exexzian
exexzian

Reputation: 7890

it might help you

Byte.parseByte(string, 16);

check API

also check this discussion

Upvotes: 2

Related Questions