Open In App

SHA-1 Hash

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

SHA-1 or Secure Hash Algorithm 1 is a cryptographic algorithm that takes an input and produces a 160-bit (20-byte) hash value. This hash value is known as a message digest. This message digest is usually then rendered as a hexadecimal number which is 40 digits long. It is a U.S. Federal Information Processing Standard and was designed by the United States National Security Agency. SHA-1 is been considered insecure since 2005. Major tech giants browsers like Microsoft, Google, Apple, and Mozilla have stopped accepting SHA-1 SSL certificates by 2017.

SHA---1-Algorithm-Block-Diagram

SHA-1 Hash


How SHA-1 Works

The block diagram of the SHA-1 (Secure Hash Algorithm 1) algorithm. Here’s a detailed description of each component and process in the diagram:

Components and Process Flow:

  1. Message (M):
    • The original input message that needs to be hashed.
  2. Message Padding:
    • The initial step where the message is padded to ensure its length is congruent to 448 modulo 512. This step prepares the message for processing in 512-bit blocks.
  3. Round Word Computation (WtW_tWt​):
    • After padding, the message is divided into blocks of 512 bits, and each block is further divided into 16 words of 32 bits. These words are then expanded into 80 32-bit words, which are used in the subsequent rounds.
  4. Round Initialize (A, B, C, D, and E):
    • Initialization of five working variables (A, B, C, D, and E) with specific constant values. These variables are used to compute the hash value iteratively.
  5. Round Constants (KtK_tKt​):
    • SHA-1 uses four constant values (K1K_1K1​, K2K_2K2​, K3K_3K3​, K4K_4K4​), each applied in a specific range of rounds:
      • K1K_1K1​ for rounds 0-19
      • K2K_2K2​ for rounds 20-39
      • K3K_3K3​ for rounds 40-59
      • K4K_4K4​ for rounds 60-79
  6. Rounds (0-79):
    • The main computation loop of SHA-1, divided into four stages (each corresponding to one of the constants K1K_1K1​ to K4K_4K4​). In each round, a combination of logical functions and operations is performed on the working variables (A, B, C, D, and E) using the words generated in the previous step.
  7. Final Round Addition:
    • After all 80 rounds, the resulting values of A, B, C, D, and E are added to the original hash values to produce the final hash.
  8. MPX (Multiplexing):
    • Combines the results from the final round addition to form the final message digest.

Summary of Steps:

  • Input (Message M): The process starts with the input message MMM.
  • Message Padding: The message is padded to meet the length requirements.
  • Word Computation: The padded message is divided into blocks and further into words, which are expanded for use in the rounds.
  • Initialization: Initial hash values are set.
  • Round Processing: The main loop performs 80 rounds of computation using the message words and round constants.
  • Final Addition: The results from the rounds are added to the initial hash values.
  • Output (Hash Value): The final message digest is produced.

Cryptographic Hash Functions in Java

To calculate cryptographic hash values in Java, the MessageDigest class is used, which is part of the java.security package. The MessageDigest class provides the following cryptographic hash functions:

  • MD2
  • MD5
  • SHA-1
  • SHA-224
  • SHA-256
  • SHA-384
  • SHA-512

These algorithms are initialized in static method called getInstance(). After selecting the algorithm the message digest value is calculated and the results are returned as a byte array. BigInteger class is used, to convert the resultant byte array into its signum representation. This representation is then converted into a hexadecimal format to get the expected MessageDigest.

Examples:

Input : hello world
Output : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

Input : GeeksForGeeks
Output : addf120b430021c36c232c99ef8d926aea2acd6b

Example 1: Below program shows the implementation of SHA-1 hash in Java. 

Java
// Java program to calculate SHA-1 hash value
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GFG {
    public static String encryptThisString(String input) {
        try {
            // getInstance() method is called with algorithm SHA-1
            MessageDigest md = MessageDigest.getInstance("SHA-1");

            // digest() method is called
            // to calculate message digest of the input string
            // returned as array of byte
            byte[] messageDigest = md.digest(input.getBytes());

            // Convert byte array into signum representation
            BigInteger no = new BigInteger(1, messageDigest);

            // Convert message digest into hex value
            String hashtext = no.toString(16);

            // Add preceding 0s to make it 40 digits long
            while (hashtext.length() < 40) {
                hashtext = "0" + hashtext;
            }

            // return the HashText
            return hashtext;
        }

        // For specifying wrong message digest algorithms
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // Driver code
    public static void main(String args[]) throws NoSuchAlgorithmException {
        System.out.println("HashCode Generated by SHA-1 for:");

        String s1 = "GeeksForGeeks";
        System.out.println("\n" + s1 + " : " + encryptThisString(s1));

        String s2 = "hello world";
        System.out.println("\n" + s2 + " : " + encryptThisString(s2));
    }
}

Output
HashCode Generated by SHA-1 for:

GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b

hello world : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

Example 2: Below program shows the implementation of SHA-1 hash in PHP.

PHP
<?php
    echo "HashCode Generated by SHA-1 for:"; 
    echo ("<br>");
    $myString = "hello world";
    echo $myString." : ";
    echo sha1($myString);
    echo ("<br>");
    $myString2 = "GeeksForGeeks";
    echo $myString2." : ";
    echo sha1($myString2);
?>


Output:

HashCode Generated by SHA-1 for:
hello world : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b

Example 3: Below program shows the implementation of SHA-1 hash in JavaScript. 

HTML
<!DOCTYPE html>
<html>
<head>
    <title>sha1 Hash function</title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/js-sha1/0.6.0/sha1.min.js">
    
    </script>
</head>
<body>
    <h1>GeeksforGeeks</h1>
 
    <h2>JavaScript sha1 Hash function</h2>
   
    <p id="pId"></p>
    <p id="pId2"></p>
 
    <!-- Script to return math property values -->
    <script>       
        var myString = "hello world";
        var text = sha1(myString); 
        document.getElementById("pId").innerHTML = myString + " : " + text;
        var myString2 = "GeeksForGeeks";
        var text2 = sha1(myString2); 
        document.getElementById("pId2").innerHTML = myString2 + " : " + text2;            
    </script>
</body>
</html>

Output:

GeeksforGeeks
JavaScript sha1 Hash function
hello world : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b

Applications:

  • Cryptography: The main application of SHA1 is to protect communications from being intercepted by outside parties. From a given data input, SHA1 generates a fixed-size, singular, and irreversible hash value. The integrity of the data can then be confirmed by comparing this hash value to the original hash value. This makes it possible to confirm that the data was not changed or tampered with in any manner during transmission.
  • Data Integrity: In many industries, such as finance, healthcare, and government, data integrity is a major concern. Data integrity in a system is checked using the SHA1 algorithm. A fingerprint of the original data is created using a hash value produced by the SHA1 algorithm.  If the data changes in any way, the hash value will also change, indicating that the data has been tampered with. 
  • Digital Signatures: Digital signatures are used to confirm the legitimacy of digital documents and messages. The digital document or communication is hashed using the SHA1 technique, and its hash value is subsequently encrypted with the sender’s private key. Using the sender’s public key to decode the message, the recipient can then compare the hash value to the original value.
  • Digital Forensics: In digital forensics, a hash of a file containing digital evidence can be produced using the SHA1 algorithm. To ensure that the evidence hasn’t been altered with during the investigation, utilize this hash value as proof. It gives proof that the file has not been altered if the hash values of the original file and the evidence file match. 
  • Password Storage: SHA1 can be used to save passwords. A hash of the password is generated using SHA1 when a user creates a password. The password itself is then substituted in a database for the hash value. The user’s password is hashed with SHA1 when they attempt to log in, and the resulting hash is compared to a previously generated hash.
  • Software Updates: The integrity of software updates can be guaranteed using SHA1. The SHA1 hash of the update file can be made public on the software vendor’s website when an update is made available. By comparing the hash of the downloaded file with the published hash, users can download the update and ensure its integrity.


Next Article
Article Tags :
Practice Tags :

Similar Reads