• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

Secure Hash Algorithm(SHA-1) in Java

October 1, 2023 //  by Talha Malik

Before moving to the Secure Hash Algorithm in Java, we need to understand what is a hashing algorithm and how the hashing algorithm works in Java. The hashing algorithm accepts the data as input and creates a hash value of a specific(fixed) length. The hash algorithms are designed in such a manner that retrieving the original value from the hashed value is not possible. 

This blog post will specifically demonstrate the use of a secure hash algorithm (SHA-1) in Java.

What is a Secure Hash Algorithm(SHA-1)?

The Secure Hash Algorithm, generally referred to as SHA, is a cryptographic hash function that works in such a way that it takes the input and returns the output in “hash Text”. It takes 20 bytes long input and returns the hash value of 40 digits in hexadecimal form. There are various types of Secure Hashing Algorithms in Java which are SHA-1, SHA-2, SHA-512, SHA-256, SHA-384, and SHA-224SHA-384.

Step 1: Import the Packages and Declare the Class

The first step involves importing the java.security package and math.BigInteger package of Java. The class is declared as “SecureHashAlgorithm” and a method named “stringencryption” is declared that accepts a single parameter/string “input”.

import java.math.BigInteger;
import java.security.*;
public class SecureHashAlgorithm {
public static String stringencryption(String input)
{

Step 2: try Block

The MessageDigest declared as ”msg” calculates the value of the cryptographic hash function. The getInstance() method is used to initiate a static method in Java. The SHA-1 hash of the given string is stored in a byte array “messageDigest”.

try {
MessageDigest msg= MessageDigest.getInstance("SHA-1");
//the getBytes() method returns an array of bytes.
byte[] messageDigest = msg.digest(input.getBytes());

Step 3: Convert the Byte Array and messageDigest

The byte array is converted to the sign form using the BigInteger value and the sign form of the messageDigest is converted to the hexadecimal value. Zeros are added to make it a 32-bit value.

BigInteger num = new BigInteger(1, messageDigest);
String hashtxt = num.toString(16);
      while (hashtxt.length() < 32) {
hashtxt = "0" + hashtxt;
}
return hashtxt;
}

Step 4: Exception in Catch Block

The exception occurs if the cryptographic algorithm that is requested is not available.

catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

Step 5: The Main Method of Java

In the code below, the main method is declared along with the strings” Java Programming” and “Python Programming” on which the Secure Hash Algorithm 1 is to be applied.

public static void main(String args[]) throws NoSuchAlgorithmException
{
System.out.println("The HashCode that is generated by SHA-1(Secure Hash Algorithm-1) for: ");
String str1 = "Java Programming";
System.out.println("\n" + str1 + " : " + stringencryption(str1));

String str2 = "Python Programming";
System.out.println("\n" + str2 + " : " + stringencryption(str2));
}
}

Step 6: Review the Code

All the code snippets are combined, and the code is reviewed and executed to understand the working of the Secure Hash Algorithm (SHA-1) in Java.

//Import the required packages for SHA-1
import java.math.BigInteger;
import java.security.*;
//Declare a class for Secure Hash Algorithm
public class SecureHashAlgorithm {
public static String stringencryption(String input)
{
    //The try block
try {
// the MessageDigest method to output a fixed length Hash value.
//The getInstance() method is used to return a signature object
MessageDigest msg= MessageDigest.getInstance("SHA-1");
//the getBytes() method returns an array of bytes.
byte[] messageDigest = msg.digest(input.getBytes());
//array conversion
BigInteger num = new BigInteger(1, messageDigest);

//converting message digest to a hexadecimal value
String hashtxt = num.toString(16);
            //Additional zeros to make it a 32-bit value
while (hashtxt.length() < 32) {
hashtxt = "0" + hashtxt;
}
// retrieves the Hash Text
return hashtxt;
}
// Exception for unavailability of cryptographic algorithm requested
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
//The Main method of Java with exception
public static void main(String args[]) throws NoSuchAlgorithmException
{

System.out.println("The HashCode that is generated by SHA-1(Secure Hash Algorithm-1) for: ");

String str1 = "Java Programming";
System.out.println("\n" + str1 + " : " + stringencryption(str1));

String str2 = "Python Programming";
System.out.println("\n" + str2 + " : " + stringencryption(str2));
}
}

Output

The Hshcode generated by the SHA-1 is described below.

Conclusion

The Secure Hash Algorithm(SHA-1) in Java uses an input value and returns a hashed value output of 40 bytes long in hexadecimal format. SHA-1 is an irreversible algorithm since the value as output can not be changed. In this article, we have demonstrated in detail the implementation of Secure Hash Algorithms in Java.

Category: Java

Previous Post: « Java main() Method
Next Post: Implementation of random() Method of Math Class in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Use Math.min() Method in Java?

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact