What is md5 hash in java

Java File Checksum – MD5 and SHA-256 Hash Examples

A checksum hash is an encrypted sequence of characters obtained after applying specific algorithms and manipulations on user-provided content. In this Java hashing tutorial, we will learn to generate the checksum hash for the files.

1. Why Generate a File’s Checksum?

Any serious file provider provides a mechanism to have a checksum on their downloadable files. A checksum is a form of mechanism to ensure that the file we downloaded is correctly downloaded.

Checksum acts like a proof of the validity of a file so if a file gets corrupted this checksum will change and thus let us know that this file is not the same file or the file has been compromised between the transfer for any reason.

We can also create the file’s checksum to detect any possible change in the file by third parties e.g. license files. We provide licenses to clients which they may upload to their servers. We can cross-verify the file’s checksum to verify that the license file has not been modified after creation.

To create checksum for a file, we will need to read the file’s content, and then generate the hash for it using one of the following methods. Note that both approaches support all types of algorithms so we can use the same code for other algorithms such as HmacMd5, SHA, SHA-512 etc.

Читайте также:  Python telegram bot перенос строки

2. Generate File Checksum with MessageDigest

MessageDigest class provides applications with the functionality of a message digest algorithm, such as MD5 or SHA-256. Its getInstance() method returns a MessageDigest object that implements the specified digest algorithm.

Example 1: Generate MD5 Hash for a File in Java

Path filePath = Path.of("c:/temp/testOut.txt"); byte[] data = Files.readAllBytes(Paths.get(filePath)); byte[] hash = MessageDigest.getInstance("MD5").digest(data); String checksum = new BigInteger(1, hash).toString(16);

Example 2: Generate SHA-256 Hash for a File in Java

Path filePath = Path.of("c:/temp/testOut.txt"); byte[] data = Files.readAllBytes(Paths.get(filePath)); byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); String checksum = new BigInteger(1, hash).toString(16);

3. Generate File Checksum with Guava

In Google Guava, ByteSource.hash() method hashes the contents with the specified hash function as method argument.

Start with adding the latest version of Guava to the project’s classpath.

 com.google.guava guava 31.1-jre  

Now we can use the hash() function as follows.

Example 1: Generate MD5 Hash for a File in Java

File file = new File("c:/temp/test.txt"); ByteSource byteSource = com.google.common.io.Files.asByteSource(file); HashCode hc = byteSource.hash(Hashing.md5()); String checksum = hc.toString();

Example 2: Generate SHA-256 Hash for a File in Java

File file = new File("c:/temp/test.txt"); ByteSource byteSource = com.google.common.io.Files.asByteSource(file); HashCode hc = byteSource.hash(Hashing.sha256()); String checksum = hc.toString();

Drop me a comment if something needs more explanation.

Источник

Knowledge Factory

Learn Java, Spring Boot, Quarkus, Kotlin, Go, Python, Angular, Vue.js, React.js, React Native, PHP, .Net and even more with CRUD example.

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

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

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.

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.

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.

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.

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.

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

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.

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

Источник

Оцените статью