Kotlin MD5, SHA-1, SHA-256, SHA-384, SHA-512, and PBKDF2 Hashing Example

What does Hashing mean?

A secure password hash is an encrypted sequence of characters obtained after applying certain algorithms and manipulations on utilizer-provided passwords, which are generally very impotent and facile to conjecture.
Please remember that once this password hash is engendered and stored in the database, you can not convert it back to the pristine password.


Using MD5 algorithm

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

MD5 Example:

import java.lang.StringBuilder
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object KnowledgeFactoryMD5 {
@Throws(NoSuchAlgorithmException::class)
@JvmStatic
fun main(args: Array<String>) {
val password = "knowledgefactory.net"
val md = MessageDigest.getInstance("MD5")
val hashInBytes = md.digest(password.
toByteArray(StandardCharsets.UTF_8))
val sb = StringBuilder()
for (b in hashInBytes) {
sb.append(String.format("%02x", b))
}
println(sb.toString())
}
}

Output: 9a98e56d08ee55f824a8e713d5d9b4b0


Using the SHA-1 algorithm

In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that takes an input and engenders a 160-bit (20-byte) hash value kenned 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.

SHA-1 Example:

import java.security.NoSuchAlgorithmException
import java.math.BigInteger
import java.security.MessageDigest

object KnowledgeFactorySHA1 {
fun encryptThisString(input: String): String {
return try {
val md = MessageDigest.getInstance("SHA-1")
val messageDigest = md.digest(input.toByteArray())
val no = BigInteger(1, messageDigest)
var hashtext = no.toString(16)
while (hashtext.length < 32) {
hashtext = "0$hashtext"
}
hashtext
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}

@Throws(NoSuchAlgorithmException::class)
@JvmStatic
fun main(args: Array<String>) {
println("HashCode Generated by SHA-1 for: ")
val s1 = "knowledgefactory.net"
println("$s1 : ${encryptThisString(s1)}"
)
}
}
Output:

HashCode Generated by SHA-1 for: 
knowledgefactory.net : 69c8c1f8846ecee34d12832e3f744df376f01ef4

 

Using the 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 engenders a virtually unique, fine-tuned size 256-bit (32-byte) hash. 

SHA-256 Example:

import java.security.NoSuchAlgorithmException
import java.math.BigInteger
import java.security.MessageDigest

object KnowledgeFactorySHA256 {
fun encryptThisString(input: String): String {
return try {
val md = MessageDigest.getInstance("SHA-256")
val messageDigest = md.digest(input.toByteArray())
val no = BigInteger(1, messageDigest)
var hashtext = no.toString(16)
while (hashtext.length < 32) {
hashtext = "0$hashtext"
}
hashtext
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}

@Throws(NoSuchAlgorithmException::class)
@JvmStatic
fun main(args: Array<String>) {
println("HashCode Generated by SHA-256 for: ")
val s1 = "knowledgefactory.net"
println("$s1 : ${encryptThisString(s1)}"
)
}
}
Output:

HashCode Generated by SHA-256 for: 
knowledgefactory.net : becf1d00ecc97f2168c6c39a661f792841fff797cbe25245ae426ef661877b3f 


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 are withal differences in the initialization process. This function is a component of the U.S Federal Information Processing Standard.

SHA-384 Example:

import java.security.NoSuchAlgorithmException
import java.math.BigInteger
import java.security.MessageDigest

object KnowledgeFactorySHA384 {
fun encryptThisString(input: String): String {
return try {
val md = MessageDigest.getInstance("SHA-384")
val messageDigest = md.digest(input.toByteArray())
val no = BigInteger(1, messageDigest)
var hashtext = no.toString(16)
while (hashtext.length < 32) {
hashtext = "0$hashtext"
}
hashtext
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}

@Throws(NoSuchAlgorithmException::class)
@JvmStatic
fun main(args: Array<String>) {
println("HashCode Generated by SHA-384 for: ")
val s1 = "knowledgefactory.net"
println("$s1 : ${encryptThisString(s1)}")
}
}
Output:

HashCode Generated by SHA-384 for: 
knowledgefactory.net: : fe2e9fc08d1a1e7cf2c90df3fe68ab1a7bf0b7152230e9ceb722cdaadbcae5e13dbbdb5b6be7fd3cc9bc81fa97977c5d


Using the SHA-512 algorithm

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 other algorithmic modifications in comparison with Sha-256.

SHA-512 Example:

import java.security.NoSuchAlgorithmException
import java.math.BigInteger
import java.security.MessageDigest

object KnowledgeFactorySHA512 {
fun encryptString(input: String): String {
return try {
val md = MessageDigest.getInstance("SHA-512")
val messageDigest = md.digest(input.toByteArray())
val no = BigInteger(1, messageDigest)
var hashtext = no.toString(16)
while (hashtext.length < 32) {
hashtext = "0$hashtext"
}
hashtext
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}

@Throws(NoSuchAlgorithmException::class)
@JvmStatic
fun main(args: Array<String>) {
println("HashCode Generated by SHA-512 for: ")
val s1 = "knowledgefactory.net"
println("$s1 : ${encryptString(s1)}")
}
}
Output:

HashCode Generated by SHA-512 for: 
knowledgefactory.net: : 546488471b6187b346fef026aaca5780c671b2b24abd707c31c89abcafbfb861d9cab02992de8ca2af20d047de5aae696be865605d48441323b5878b5c9a751d


Using  PBKDF2WithHmacSHA1 algorithm

In cryptography, PBKDF1 and PBKDF2 (Password-Predicated Key Derivation Function 2) are key derivation functions with a sliding computational cost, used to reduce vulnerabilities to brute force attacks.

PBKDF2WithHmacSHA1 Example:

import java.math.BigInteger
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import java.security.spec.InvalidKeySpecException

object KnowledgeFactoryPBKDF2 {
@Throws(NoSuchAlgorithmException::class,
InvalidKeySpecException::class)
@JvmStatic
fun main(args: Array<String>) {
val originalPassword = "knowledgefactory.net"
val generatedSecuredPasswordHash =
generateStorngPasswordHash(originalPassword)
println(generatedSecuredPasswordHash)
}

@Throws(NoSuchAlgorithmException::class,
InvalidKeySpecException::class)
private fun generateStorngPasswordHash
(password: String): String {
val iterations = 500
val chars = password.toCharArray()
val salt = salt
val spec = PBEKeySpec(chars, salt, iterations, 64 * 8)
val skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val hash = skf.generateSecret(spec).encoded
return """
Total iteration: $iterations
Salt: ${toHex(salt)}
Hash: ${toHex(hash)}
""".trimIndent()
}

@get:Throws(NoSuchAlgorithmException::class)
private val salt: ByteArray
private get() {
val sr: SecureRandom = SecureRandom.
getInstance("SHA1PRNG")
val salt = ByteArray(16)
sr.nextBytes(salt)
return salt
}

@Throws(NoSuchAlgorithmException::class)
private fun toHex(array: ByteArray): String {
val bi = BigInteger(1, array)
val hex = bi.toString(16)
val paddingLength = array.size * 2 - hex.length
return if (paddingLength > 0) {
String.format("%0" + paddingLength + "d", 0) + hex
} else {
hex
}
}
}
Output:

Total iteration: 500
Salt: 7825369b35caf7d0781a39625f025591
Hash: fc04c5682256be716e8c58da4ba4587bb21ae3193b2e92a6b20330a3abb5405ded05c21d3214ccdb4f353151040b4056c47bd23463fdd3d32b85d40d1818c4aa


Popular posts from this blog

Spring boot video streaming example-HTML5

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

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example