SHA-256 is a hashing algorithm created by the National Security Agency (NSA) that can convert a text of any length into a string of 256 bits. SHA is short for Secure Hashing Algorithm, where hashing is a one-way function that takes an input and generates an output.
The input cannot be deduced from the output, where an output is also known as a cryptographic hash. To reverse a 256 bit hash, you’d have to create a random data set, convert them into hash and compare the two hashes, which at the most would need to be calculated 2^256 times, which would take an unimaginable amount of time with current computing power.
SHA-256 is used in two ways in Bitcoin:
- Mining, and
- Bitcoin addresses.
Mining
The Proof of Work algorithm used by Bitcoin is based on SHA-256. For miners to create candidate blocks to be added to the end of Bitcoin’s blockchain, there are six parameters of the block header that must be entered by the miner; version, previous block hash, Merkle root, timestamp, target and nonce.
To produce the previous block hash, a miner must use the SHA-256 algorithm twice, where the double hashing prevents ‘length-extension’ attacks. The Merkle root is also produced using the SHA-256 and is entered into the block header of the block the miner is creating.
Miners then try repeatedly to find a nonce value, which changes frequently, that is below the target. The majority of a miner’s resources and effort is directed to finding a nonce value that is valid. The block header is hashed with SHA-256 until this nonce value is found. If the hashed block header is above the target, then the miner must try again with a new nonce value. The first miner to find the nonce value that is below the target will successfully produce a new block for the Bitcoin blockchain.
Bitcoin Addresses
The SHA-256 algorithm is also used in the creation of Bitcoin addresses. A private key is a random number and elliptic curve cryptography is used to obtain a public key. This public key is then hashed using the SHA-256 algorithm and then the RIPEMD169 algorithm to create a bitcoin address.
The SHA-256 algorithm shortens the public key, which is 256 bits long, creating a bitcoin address which is just 160 bits long.
A private key can also be created by starting with a string of random words, known as a seed. The seed is then put through SHA-256 to generate a 256 bit value and the public key is then created the same way as described above.