Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SHA-256 (Secure Hash Algorithm 256-bit)



SHA 256 is a part of the SHA 2 family of algorithms, where SHA stands for Secure Hash Algorithm. Published in 2001, it was a joint effort between the NSA and NIST to introduce a successor to the SHA 1 family, which was slowly losing strength against brute force attacks.

The significance of the 256 in the name stands for the final hash digest value, i.e. irrespective of the size of plaintext/cleartext, the hash value will always be 256 bits.

Characteristics of the SHA-256

The SHA algorithm has several important features, like −

  • Message length − The cleartext should be less than 264 bits. The size has to be in the same range to keep the digest as random as possible.
  • Digest Length − The hash digest should be 256 bits for the SHA 256 method, 512 bits for SHA-512, and so on. Higher digests typically represent considerably more calculations at a cost of speed and space.
  • Irreversible − By design, all hash functions, like SHA 256, are irreversible. You should not get a plaintext if you already have the digest, nor should the digest return its original value if you put it over the hash function again.

Now that you have a good understanding of the technical requirements for SHA, you can go on to the next part and learn about the whole method.

Algorithm

You can divide the whole procedure into five different sections, as shown below −

Padding Bits

It gives some extra bits to the message so that the length is precisely 64 bits less than a multiple of 512. In addition, the first bit must be one, and the remaining bits should be zeros.

Padding Bits

Padding Length

We can now add 64 bits of data to the final plaintext, which makes it a multiple of 512. To determine these 64 bits of characters, apply the modulus to the initial plaintext without padding.

Padding Length

Initialising the Buffers

The default settings for the eight buffers that will be used in the rounds should be set as follows −

Initialising the Buffers

We need to keep 64 different keys in an array, ranging from K[0] to K[63].

Compression Functions

The entire message is divided into numerous blocks of 512 bits each. It runs each block over 64 rounds of operations, with the output of each one being used as the input to the next block.

Since the value of K[i] in all of those iterations is pre-initialized, W[i] is another input that is calculated separately for each block according to the number of iterations being performed at the time.

Output

With each iteration, the block's final output becomes the input for the next block. The entire cycle is carried out until we reach the last 512-bit block, at the point where the output is considered the final hash digest. As the algorithm's name suggests, this digest will be 256 bits in length.

ImImplementation of SHA-256

Now, we will implement SHA-256 using several programming languages to get hands-on practice.

SHA-256 using Python

We will first import the hashlib library install if you have not installed yet using pip. After that we will create a string whch we want to hash. Then we will encode the string to bytes using the UTF-8 encoding as hashlib works with bytes. We will generate a new SHA-256 hash object using hashlib.sha256(). And then we will update the hash object with the bytes of our string using the update() method. At the end we will get the hexadecimal representation of the hash with the help of hexdigest() method and print it.

import hashlib

# generate a string to hash
my_string = "Hello, Tutorialspoint!"

# chaneg the string to bytes 
my_bytes = my_string.encode('utf-8')

# generate a new SHA-256 hash object
hash_object = hashlib.sha256()

# Update the hash object
hash_object.update(my_bytes)

# get the hexadecimal representation
hash_hex = hash_object.hexdigest()

# print the SHA-256 hash
print("SHA-256 hash of", my_string, ":", hash_hex)

Output

SHA-256 hash of Hello, Tutorialspoint! : caba24f8a70cc24277bffcc27aa952723fbf369f315b9657eebf7c7e42b7a1f9

SHA-256 using Java

In this implementation of SHA-256 using Java we will define a class called SHA256Class to generate the hash for given input strings. It uses the MessageDigest class from the java.security package and the BigInteger class to convert byte arrays to hexadecimal strings. So the complete code for SHA-256 using Java is as follows −

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Class {
   public static byte[] calculateSHA256(String input) throws NoSuchAlgorithmException {
      MessageDigest md = MessageDigest.getInstance("SHA-256");
      return md.digest(input.getBytes(StandardCharsets.UTF_8));
   }

   public static String bytesToHexString(byte[] hash) {
      BigInteger number = new BigInteger(1, hash);
      StringBuilder hexString = new StringBuilder(number.toString(16));
      while (hexString.length() < 64) {
         hexString.insert(0, '0');
      }
      return hexString.toString();
   }

   public static void main(String args[]) {
      try {

         String message1 = "Simple SHA-256 Example";
         System.out.println("\n" + message1 + " : " + bytesToHexString(calculateSHA256(message1)));

         String message2 = "Secure Hash Algorithm";
         System.out.println("\n" + message2 + " : " + bytesToHexString(calculateSHA256(message2)));

         String message3 = "Hello, Tutorialspoint!";
         System.out.println("\n" + message3 + " : " + bytesToHexString(calculateSHA256(message3)));
      } catch (NoSuchAlgorithmException e) {
         System.out.println("Exception thrown for incorrect algorithm: " + e);
      }
   }
}

Output

Simple SHA-256 Example : 0e3c2ff641548fd5b1dd2724262cc099d56459ebec2c1bb3c7f71513f65ccb39

Secure Hash Algorithm : 42cf1ce9880d7f211c3d30d3bd376d20b26aaf6a929471108025c8e99b751c89

Hello, Tutorialspoint! : caba24f8a70cc24277bffcc27aa952723fbf369f315b9657eebf7c7e42b7a1f9

How secure is SHA-256?

One of the strongest hashing algorithms available is SHA-256. The US government recommends that its agencies use SHA-256 to secure specific sensitive data. While the details of SHA-256's operation are kept under wraps, we do know that it is constructed using a Merkle-Damgård structure that is derived from a one-way compression function that was itself developed using a particular block cipher's Davies-Meyer structure.

SHA-256 is secure due to three reasons −

  • First of all, using the hash value alone to recreate the original data is very hard. It takes a brute-force attack 2256 tries to produce the first set of data.
  • Second, it is very impossible that two messages will have the identical hash value-a situation known as a collision. There are 2256 potential hash values, which is more than there are atoms in the known universe, therefore there is an extremely low chance that two will be identical.
  • Third, the avalanche effect occurs when a small alteration to the original data changes the hash value so much that it becomes difficult to tell the new hash value is obtained from similar material.

Applications of SHA-256

SHA-256 is the industry standard hashing algorithm for SSL handshake, digital signature verification, protecting passwords, and a variety of other tasks related to security.

Verification of Digital Signatures

An electronic signature known as a digital signature is applied to verify the authenticity and consistency of a communication, like an email messages, a credit card transaction, or a digital document. It is produced by hashing the file and encrypting it with Public Key Infrastructure (PKI).

The integrity of the digital signature is protected during the entire process by the SHA-256 hash method. The web browser of the recipient verifies the hashing algorithm on its end and decrypts the message using the public key. The data is real and unaltered if they match.

SSL Handshake

A key component of web browsing sessions is the SSL handshake, which depends on SHA-256 functionality and compatibility. Before any data transmission begins, communications via SS/TLS always start with the SSL handshake, an asymmetric cryptography that enables the browser to validate the web server, receive the public key, and create a secure connection.

Password Security

User passwords are stored on websites in a hashed form. As previously stated, safe password hashing uses an encryption method to reduce them to a brief string of letters and/or numbers. Hashed passwords are not accessible to cybercriminals when a website is compromised.

Verification of blockchain transactions

When Bitcoin was initially created, the SHA-256 hash algorithm was the first to be used with a cryptocurrency. Blockchains need block headers in order to link or connect one block of transactions to the next in an ordered manner. Without affecting with the header of the new block, the SHA-256 hash ensures that no earlier blocks are altered.

Advertisements