Java secure hashing - 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.



Security using the MD5 algorithm


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


package com.knowledgefactory;

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



Security using the SHA-1 algorithm

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


package com.knowledgefactory;



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



Security using SHA-256 algorithm

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


package com.knowledgefactory;



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 : 505c217e8123f856ae88cd06d1753f1562ee44c1f1e91f6d90ccf4ff11b52c880197cf4fb008788fa8bd184c4d7171265328577735d4229015f4be26776fc725



Security using the SHA-384 algorithm

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's 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


package com.knowledgefactory;

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



Security using SHA-512 algorithm

SHA-512 is a function of cryptographic algorithm SHA-2, which is an evolution of famous SHA-1.


SHA-512 is very close to Sha-256 except that it used 1024 bits "blocks", and accept as input a 2^128 bits maximum length string. SHA-512 also has others algorithmic modifications in comparison with Sha-256.


Example:Java-SHA-512 to hash a String


package com.knowledgefactory;

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



Security using PBKDF2WithHmacSHA1 algorithm

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

package com.knowledgefactory;

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


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments