Hashing in Java - MD5 ,SHA-1, SHA-256, SHA-384,SHA-512 and PBKDF2

What does Hashing mean?

A secure password hash is an encrypted sequence of characters obtained after applying certain algorithms and manipulations on user-provided password, which are generally very weak and easy to guess.
Please remember that once this password hash is generated and stored in the database, you can not convert it back to the original password.




MD5 hash in Java

The MD5 message-digest algorithm is a widely used hash function producing a 128-bit hash value. Although MD5 was initially designed to be used as a cryptographic hash function, it has been found to suffer from extensive vulnerabilities. It can still be used as a checksum to verify data integrity, but only against unintentional corruption. It remains suitable for other non-cryptographic purposes, for example for determining the partition for a particular key in a partitioned database.

Example: Java-MD5 to hash a String
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class KnowledgeFactoryMD5 {

public static void main(String[] args) throws NoSuchAlgorithmException {

String password = "www.knowledgefactory.net";

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = md.digest(password.
getBytes(StandardCharsets.UTF_8));

StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
System.out.println(sb.toString());

}
}


Output: 25d1f28032d7f41c2b0337740261bc64



SHA-1 hash in Java

In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that takes an input and produces a 160-bit (20-byte) hash value known as a message digest – typically rendered as a hexadecimal number, 40 digits long. It was designed by the United States National Security Agency and is a U.S. Federal Information Processing Standard.

Example: Java-SHA-1 to hash a String
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class KnowledgeFactorySHA1 {

public static String encryptThisString(String input) {

try {

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}

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

public static void main(String args[]) throws NoSuchAlgorithmException {

System.out.println("HashCode Generated by SHA-1 for: ");
String s1 = "www.knowledgefactory.net";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));

}
}

Output:

HashCode Generated by SHA-1 for: 
www.knowledgefactory.net : 3a6846af08452b2244b4b105ea12cf24761cf8ed



SHA-256 hash in Java

The SHA (Secure Hash Algorithm) is one of a number of cryptographic hash functions. A cryptographic hash is like a signature for a text or a data file. SHA-256 algorithm generates an almost-unique, fixed-size 256-bit (32-byte) hash. Hash is a one-way function – it cannot be decrypted back.

Example: Java-SHA-256 to hash a String
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class KnowledgeFactorySHA256 {

public static String encryptThisString(String input) {

try {

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}

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

public static void main(String args[]) throws NoSuchAlgorithmException {

System.out.println("HashCode Generated by SHA-256 for: ");
String s1 = "www.knowledgefactory.net";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));

}
}

Output:

HashCode Generated by SHA-256 for: 
www.knowledgefactory.net : e7d1a94a4df129131ac8f3de6367ff6b522397924bf504d7506e615fc7e73153



SHA-384 hash in Java

Sha-384 is a function of the cryptographic algorithm Sha-2, the evolution of Sha-1. It's the same encryption as Sha-512, except that the output is truncated at 384 bits. There are also differences in the initialization process. This function is part of the U.S Federal Information Processing Standard. 

Example: Java-SHA-384 to hash a String
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class KnowledgeFactorySHA384 {
public static String encryptThisString(String input) {
try {

MessageDigest md = MessageDigest.getInstance("SHA-384");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}

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

public static void main(String args[]) throws NoSuchAlgorithmException {

System.out.println("HashCode Generated by SHA-384 for: ");
String s1 = "www.knowledgefactory.net";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));

}
}

Output:

HashCode Generated by SHA-384 for: 
www.knowledgefactory.net : 2643e129044af3888ba30d8b781fb1990a487a750a5110e41f505d5fb40097cff88b402342251e2209f6d8e3dec78778




SHA-512 hash in Java

SHA-512 is a function of the cryptographic algorithm SHA-2, which is an evolution of the famous SHA-1.
SHA-512 is very close to Sha-256 except that it used 1024 bits "blocks", and accepts as input a 2^128 bits maximum length string. SHA-512 also has other algorithmic modifications in comparison with Sha-256.

Example: Java - SHA-512 to hash a String
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class KnowledgeFactorySHA512 {
public static String encryptThisString(String input) {
try {

MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}

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

public static void main(String args[]) throws NoSuchAlgorithmException {

System.out.println("HashCode Generated by SHA-512 for: ");
String s1 = "www.knowledgefactory.net";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));

}
}

Output:

HashCode Generated by SHA-512 for: 
www.knowledgefactory.net : 505c217e8123f856ae88cd06d1753f1562ee44c1f1e91f6d90ccf4ff11b52c880197cf4fb008788fa8bd184c4d7171265328577735d4229015f4be26776fc725




PBKDF2WithHmacSHA1 hash in Java

Java has implementation of “PBKDF2” algorithm as “PBKDF2WithHmacSHA1“.
In cryptography, PBKDF1 and PBKDF2 (Password-Based Key Derivation Function 2) are key derivation functions with a sliding computational cost, used to reduce vulnerabilities to brute force attacks.

Example: Java - PBKDF2WithHmacSHA1 to hash a String
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class KnowledgeFactoryPBKDF2 {
public static void main(String[] args) throws NoSuchAlgorithmException
 InvalidKeySpecException {
String originalPassword = "www.knowledgefactory.net";
String generatedSecuredPasswordHash = generateStorngPasswordHash
(originalPassword);
System.out.println(generatedSecuredPasswordHash);
}

private static String generateStorngPasswordHash(String password)
throws NoSuchAlgorithmException, InvalidKeySpecException {
int iterations = 500;
char[] chars = password.toCharArray();
byte[] salt = getSalt();

PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8);
SecretKeyFactory skf = SecretKeyFactory.
getInstance("PBKDF2WithHmacSHA1");
byte[] hash = skf.generateSecret(spec).getEncoded();
return "Total iteration: " + iterations + "\n" + "Salt: "
toHex(salt) + "\n" + "Hash: " + toHex(hash);
}

private static byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
sr.nextBytes(salt);
return salt;
}

private static String toHex(byte[] array) throws NoSuchAlgorithmException {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0) {
return String.format("%0" + paddingLength + "d", 0) + hex;
} else {
return hex;
}
}

}


Output:

Total iteration: 500
Salt: 7b37492c931fe4c00f19a4622a7cda4e
Hash: 4604be8f314c1089db874f35fc6b9ee7f72ec124b92cc7b24aa83f239365b228b3ffa16f55433426c15ff3b09c142d7d7f621a7bc7eb8cf1eb8b913e4aaabdef

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete