1

I have a question concerning Java and sha-256.

I try to do these steps discribed here to create a WIF key: https://en.bitcoin.it/wiki/Wallet_import_format

  1. step:

String string = "0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D";

  1. step (ad 80 in front):

string = "80" + string;

  1. perform sha-256:
    • here is my mistake. I can perform sha-256 on step 2 but the result is wrong. The reason seems to be perform the hash on a String and not on binary. I get:

e2e4146a36e9c455cf95a4f259f162c353cd419cc3fd0e69ae36d7d1b6cd2c09

But I should get:

8147786C4D15106333BF278D71DADAF1079EF2D2440A4DDE37D747DED5403592

I dont get how to convert it to binary. Can someone help me?

Its the same problem as here (Correct way to convert a 256-bit private key to WIF?) but I dont understand the answer. I also cant reply to the thread because I dont have enough reputation.

Thank you :)

1 Answer 1

2

You should convert hex representation of bytes to byte array (not String to byte array). Then make hash. Then convert the byte array back to hex representation of bytes in String.

The whole solution will look like:

import java.security.*;

class HashExample {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        String string = "0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D";
        string = "80" + string;
        byte[] data = hexStringToByteArray(string);
        byte[] digest = MessageDigest.getInstance("SHA-256").digest(hexStringToByteArray(string));
        String result = bytesToHex(digest);
        System.out.println(result);
        //prints: 8147786c4d15106333bf278d71dadaf1079ef2d2440a4dde37d747ded5403592
    }

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

    private static String bytesToHex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        return result.toString();
    }
}

Of course this is just example. In production code I recommend to use one of the available libraries which can perform this task.

1
  • hexStringToByteArray can be done much simpler: byte[] bytes = new BigInteger(privateKeyHex, 16).toByteArray();
    – eztam
    Commented Nov 11, 2021 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.