-2

I am writing a Java program that converts Bitcoin privateKey to WIF format. Unfortunately, I got wrong SHA256 hashes.

My code is based on Basing on this tutorial.

When I hash a value like:

800C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D

I get something like this as result:

e2e4146a36e9c455cf95a4f259f162c353cd419cc3fd0e69ae36d7d1b6cd2c09

instead of:

8147786C4D15106333BF278D71DADAF1079EF2D2440A4DDE37D747DED5403592

This is my piece of code:

public String getSHA(String value){
    String hash = hash = DigestUtils.sha256Hex(value.getBytes());
    System.out.println(hash);
    return hash;
}

I used this library: import org.apache.commons.codec.digest.DigestUtils;

Of course I searched this problem on the web and I found this site.

On that website, there are two textboxes - String hash and Binary Hash. Using a String hash, I got the same incorrect result as in my Java program. But, using a Binary hash, I got a right result.

My question is: What is the difference between Binary and String hashes? How to implement Binary hash in my Java method?

kalehmann
  • 4,821
  • 6
  • 26
  • 36
  • 1
    Probably you are using 800C28... as a String but it should be the byte array 0x80,0x0C,0x28,... https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array – PeterMmm Mar 11 '19 at 22:15

1 Answers1

1

In your case 800C28... is a text representation of byte[] using hex encoding. To convert it back to byte[] you can take a look at this answer, one way would be to do it is:

public static byte[] hexStringToByteArray(String hex) {
  int l = hex.length();
  byte[] data = new byte[l/2];
  for (int i = 0; i < l; i += 2) {
    data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
      + Character.digit(hex.charAt(i+1), 16));
  }
  return data;
}

String.getBytes() will return the character values, e.g. character 8 has a value of 56 as per the ASCII table.

System.out.println(Arrays.toString("8".getBytes())); // 56
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111