Bitcoin Checksum on Bash

Checksum is often used in Bitcoin when generating public key, address. Checksum is a simple method for error-checking data [1].

In Bitcoin blockchain the checksum is generated by running SHA256 function two times in a row.

Important note: need to use sha256 in binary mode for binary data.

 

Bitcoin checksum on Linux Bash: sha256sum

This is an example used on learnmeabitcoin [1] and this bash analogue gives the same result:

echo -n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | xxd -r -p | sha256sum -b | cut -d ' ' -f1 | xxd -r -p | sha256sum -b | cut -d ' ' -f1
05c4de7c1069e9de703efd172e58c1919f48ae03910277a49c9afd7ded58bbeb

1. Here we print a string aaaa.. without new line character at the end: echo -n

2. Next we convert to binary: xxd -r -p

3. Use sha256 in binary mode: sha256sum -b

4. As far as sha256sum prints also *- in the end, needs to cut only first word from its output

5. Convert output to binary again with xxd

6. Use sha256sum again and cut its output leaving only necessary string

The result line is checksum hash. In Bitcoin checksum is the first four bytes (first 8 letters), so lets cut it:

echo -n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | xxd -r -p | sha256sum -b | cut -d ' ' -f1 | xxd -r -p | sha256sum -b | cut -d ' ' -f1 | head -c8
05c4de7c

Data and checksum is: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa05c4de7c

Then you use Base58 and other function for generate address or private and public keys.

 

openssl dgst -sha256 

There is another way to get SHA256 in bash using openssl tool:

echo -n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | xxd -r -p | openssl dgst -sha256 -binary | openssl dgst -sha256 -binary | xxd -p -l4
05c4de7c

 

We have learnt how to use Bash functions `sha256sum` and `openssl dgst -sha256` to get Bitcoin's checksum.

 

Links

1. Checksum https://learnmeabitcoin.com/technical/checksum

Section
Category