Java SHA-1 Hashing String
In this Java tutorial, we learn how to use the SHA-1 hashing algorithm to hash a String value in Java programming language.
How to use SHA-1 algorithm to hash String in Java
At this first step we create a new Java class named SHAUtils.
In this utility class, implement a new static method named sha1(String inputText) to use the SHA-1 algorithm to hash an input String into byte array, and then convert the byte array to hex String as the Java code below.
SHAUtils.java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAUtils {
/**
* This method use SHA-1 algorithm to hash a String.
* @param inputText input text
* @return hashed text
*/
public static String sha1(String inputText) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
messageDigest.update(inputText.getBytes());
byte[] hashedData = messageDigest.digest();
// convert byte array to hex String
BigInteger bigInteger = new BigInteger(1, hashedData);
String hashedText = bigInteger.toString(16);
return hashedText;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}
In the following example Java code, we learn how to use the above SHAUtils.sha1() method to hash a String using SHA-1 algorithm in Java program.
SHA1Example.java
public class SHA1Example {
public static void main(String... args) {
String inputText = "Simple Solution";
// Hash a String using SHA-a algorithm
String hashedText = SHAUtils.sha1(inputText);
System.out.println("Input text: " + inputText);
System.out.println("SHA-1 hashed text: " + hashedText);
}
}
Input text: Simple Solution
SHA-1 hashed text: 23921d0724f0388c797b1383c39a6eaea5c134e6
Happy Coding 😊
Related Articles
Java AES 256 Encryption and Decryption
Java AES Advanced Encryption Standard Encryption and Decryption