SHA-256

Cryptographic hash and its role in blockchain





Introduction
Hashing is a concept from cryptography and in this article we will explore SHA-256 hash. Our objective is to shine some light on the properties of hashes which make them usable for blockchain. Note that to make things simpler for different levels of audiences , we've oversimplified things where applicable.
What is a Hash ?
In case you've never come across before this term , here's a simple way of looking at it. Think of a Hash as a function which just like all other functions in computer programming takes one ore more inputs and produces an output.
Hash( data ) = Output or Digest; OR
Hash( a ) = b;
Now what makes hashing usable in blockchain are the properties of the output produced by hash functions. We're about to discuss this properties in next section.
Properties of Hash
Following are the properties of Hash functions.
  1. Irreversible
    Hash functions are Irreversible which means that given the output of the function , you've no way to perdict the input. It means they only flow in one direction viz from input to output.
  2. Uniqueness
    The output of the hash function is unique for unique data. What this means is that no 2 data inputs can have same hash.
  3. Fixed Length
    Whether you calculate the hash of a small string or a few gigabytes of file , you always get a fixed length string.
So these 3 properties of a hash function i.e. Irreversible, Uniqueness and Fixed length are what makes it suitable for use in blockchain.
SHA-256
SHA or Simple Hashing Algorithms is a family of hash functions. Following is nodejs code to calculate SHA-256.
                        
var crypto = require('crypto');
var hash1 = crypto.createHash('sha256');
var hash2 = crypto.createHash('sha256');
data1 = hash1.update('nodejsera', 'utf-8');
data2 = hash2.update('I am a longer string but my hash will also be of the same length as above.', 'utf-8');
hash1 = data1.digest('hex');
hash2 = data2.digest('hex');
console.log(hash1);
console.log(hash2);                                
                        
                    
The output of the above program is as shown below:
                        
'664ad54634c10149e324ffd83bd7b90badbffffcc5738c602b3e27cb7617737f'
'ae27cdbc130d842c2d1129609837b33a3ba2d68473916d076683b0a248ffe422'
                        
                    
As we can see , both the hashes are of fixed length.
Summary
In this tutorial , we learned about basic concepts which makes a hash usable in blockchain.