Md5 class in java

Java MD5 example

MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value, specified in RFC 1321, MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994). MD5 has been employed in a wide variety of security applications, and is also worldwide used to check the integrity of files.

MD5 is a perfect solution for security thinking. The Java developers usually may take over or code MD5 encryption, the MD5 encryption is complicated, for self-coding it’s hard to implement. Java standard edition has MD5 support built in. in package java.security , class MessageDigest supports functionality of a message digest algorithm, such as MD5 or SHA.

1. Example to Hash a String with MD5 algorithm

This is a Java MD5 example, it passes into a string and returns the MD5 encryption value, we used the method getBytes() that converts a plain text to byte array, the digest is then updated from the bytes from the byte array and a hash computation is conducted upon them(using MessageDigest ).

import java.io.FileInputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 < public static String getMD5(String input) < try < MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(input.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String hashtext = number.toString(16); // Now we need to zero pad it if you actually want the full 32 chars. 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(getMD5("Javarmi.com")); >>

Java MD5 example Output:

2. Another way Hashing String with MD5 algorithm

This is another Java MD5 encryption example, it accepts string and returns MD5 encryption value.

import java.io.FileInputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 < public static String getMD5(String input) < byte[] source; try < //Get byte according by specified coding. source = input.getBytes("UTF-8"); >catch (UnsupportedEncodingException e) < source = input.getBytes(); >String result = null; char hexDigits[] = ; try < MessageDigest md = MessageDigest.getInstance("MD5"); md.update(source); //The result should be one 128 integer byte temp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) < byte byte0 = temp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; > result = new String(str); > catch (Exception e) < e.printStackTrace(); >return result; > public static void main(String[] args) throws NoSuchAlgorithmException < System.out.println(getMD5("Javarmi.com")); >>

Java MD5 example Output

Читайте также:  Unicode string to bytes python

3. File checksum using Java MD5

MD5 algorithm is also widely used for file checksum to ensure that files were not modified by attacker, an example is below that uses Java MD5 hashing algorithm to generate a checksum for file “c:\\apache\\cxf.jar”. you can check whether the printed value matches the original MD5 value which was released by Jar Publisher.

public static void main(String[] args) throws Exception < MessageDigest md = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar"); byte[] dataBytes = new byte[1024]; int nread = 0; while ((nread = fis.read(dataBytes)) != -1) < md.update(dataBytes, 0, nread); >; byte[] mdbytes = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) < sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); >System.out.println("Digest(in hex format):: " + sb.toString()); >

Источник

Java MD5 Hash using Apache Commons Codec

In this Java tutorial we learn how to calculate MD5 digest in Java application using the DigestUtils class of Apache Commons Codec library.

Table of contents

Add Apache Commons Codec Dependency to Java project

To use Apache Commons Codec library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'commons-codec', name: 'commons-codec', version: '1.15'

To use the Apache Commons Codec library in the Maven build project, add the following dependency into the pom.xml file.

  commons-codec commons-codec 1.15 

To have more information about the Apache Commons Codec Java library you can visit the project home page at commons.apache.org/proper/commons-codec/

Convert String to MD5 Hash in Java

The Apache Commons Codec library provides method DigestUtils.md5Hex() can be used to calculate the MD5 digest and return value as a 32 characters hex string.

String md5Value = DigestUtils.md5Hex(inputData);

In the following Java program, we show how to use DigestUtils.md5Hex() method to hash an input String to MD5 hash as a hex string.

import org.apache.commons.codec.digest.DigestUtils; public class Md5Example1  public static void main(String. args)  String inputData = "Simple Solution"; String md5Value = DigestUtils.md5Hex(inputData); System.out.println("Input String:" + inputData); System.out.println("MD5:" + md5Value); > >
Input String:Simple Solution MD5:6cd04c53878b462e5d7d400a11ac19cf

Generate File MD5 Checksum String in Java

Apache Commons Codec library provides the DigestUtils.md5Hex() method to generate MD5 hash for an InputStream as below.

String md5Value = DigestUtils.md5Hex(inputStream);

For example, we have a document file at D:\SimpleSolution\Document.doc

The following Java program to show you how to use the DigestUtils.md5Hex() to generate MD5 checksum hash for a given file and return MD5 hash value as a hex string.

import org.apache.commons.codec.digest.DigestUtils; import java.io.FileInputStream; import java.io.IOException; public class Md5Example2  public static void main(String. args) throws IOException  String filePath = "D:\\SimpleSolution\\Document.docx"; String md5Value = DigestUtils.md5Hex(new FileInputStream(filePath)); System.out.println("MD5:" + md5Value); > >
MD5:b3143672f91aea6ceceae116a852d4d6

Generate MD5 Hash as Bytes Array

The Apache Commons Codec library also provides DigestUtils.md5() method to calculate MD5 digest and return value as a 16 element byte[] array.

byte[] md5Value = DigestUtils.md5(inputData);

The following Java example program to show you how to use the DigestUtils.md5() method to hash a String to a MD5 hash value as byte[] array.

import org.apache.commons.codec.digest.DigestUtils; import java.util.Arrays; public class Md5Example3  public static void main(String. args)  String inputData = "Simple Solution"; byte[] md5Value = DigestUtils.md5(inputData); System.out.println("Input String:" + inputData); System.out.println("MD5 as bytes:" + Arrays.toString(md5Value)); > >
Input String:Simple Solution MD5 as bytes:[108, -48, 76, 83, -121, -117, 70, 46, 93, 125, 64, 10, 17, -84, 25, -49]

Get Instance of java.security.MessageDigest for MD5 message digest algorithm

Using Apache Commons Codec we can use the DigestUtils.getMd5Digest() method to return instance of MD5 java.security.MessageDigest and use it to calculate MD5 digest as following Java program.

import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public class Md5Example4  public static void main(String. args)  String inputData = "Simple Solution"; MessageDigest md5MessageDigest = DigestUtils.getMd5Digest(); byte[] hashedBytes = md5MessageDigest.digest(inputData.getBytes(StandardCharsets.UTF_8)); String md5Value = Hex.encodeHexString(hashedBytes); System.out.println("Input String:" + inputData); System.out.println("MD5:" + md5Value); > >
Input String:Simple Solution MD5:6cd04c53878b462e5d7d400a11ac19cf

Источник

Generate MD5 Hash in Java

Generate MD5 Hash in Java

  1. MD5 Hashing Algorithm in Java
  2. Use MD5 Hash in Java
  3. Use MD5 Hash on Large Data in Java
  4. Conclusion

In this article, we will understand the MD5 algorithm to generate the hash of data and how we can produce the MD5 hash of data in Java.

MD5 Hashing Algorithm in Java

The MD5 hashing algorithm is a cryptographic hashing algorithm, and it is largely used as a checksum of the data files. We can use this algorithm to generate a 128-bit cryptographic hash of our data.

The MD5 hashing algorithm is widely used because it is much faster than the modern secure hashing algorithms.

Use MD5 Hash in Java

Java is widely used for file transfer and server-side programming; it is not surprising to find a library to generate MD5 hash. Java provides us a MessageDigest class, a child class of the MessageDigestSpi found in Java’s ‘security’ package.

To generate the MD5 hash in Java,

Import the MessageDisgest class from the Java security package.
Convert our data into a stream of bytes before getting the message digest.
Then, invoke the getInstance() method to create an instance of the MD5 hashing algorithm.
public static MessageDigest getInstance(String algorithm)  throws NoSuchAlgorithmException 
We will invoke the digest() method by passing the data we want to get the MD5 hash.
public byte[] digest(byte[] input) 
Store the message digest as a stream of bytes into a byte array.
Lastly, convert the message digest from bytes to string.

Let us understand the above approach using a working code in Java.

import java.util.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;  public class md5Test   public static void main(String [] args)    String str;  Scanner scan = new Scanner(System.in);  str = scan.nextLine();  System.out.println("Your input: "+str);   byte[] msg = str.getBytes();   byte [] hash = null;  try    MessageDigest md = MessageDigest.getInstance("MD5");  hash = md.digest(msg);  >  catch (NoSuchAlgorithmException e)   e.printStackTrace();  >  StringBuilder strBuilder = new StringBuilder();  for(byte b:hash)    strBuilder.append(String.format("%02x", b));  >  String strHash = strBuilder.toString();  System.out.println("The MD5 hash: "+strHash);  > > 
Hello, Peter Your input: Hello, Peter The MD5 hash: 945062a2fee23e0901b37fcb5cd952c9  Java is so awesome. Your input: Java is so awesome. The MD5 hash: 601835019da217140c2755c919ee18c2 

Use MD5 Hash on Large Data in Java

If you have large data or read the data in chunks, then use the update() method.

public void update(byte[] input) 

Each time you read a chunk of data, you should call the update() method by passing the current chunk. After all the data is read, use the following polymorphic form of the digest() method.

public byte[] digest() //It means you will pass no parameter to the `digest()` method. 

For demonstration, you can see the following example.

import java.util.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;  public class md5Test   public static void main(String [] args)    String str;  Scanner scan = new Scanner(System.in);  System.out.println("Enter message:");  str = scan.nextLine();  System.out.println("Your input: "+str);   byte [] hash = null;   MessageDigest md = null;   try    md = MessageDigest.getInstance("MD5");  >  catch (NoSuchAlgorithmException e)   e.printStackTrace();  >   md.update(str.getBytes());   System.out.println("Enter message:");  str = scan.nextLine();   md.update(str.getBytes());  hash = md.digest();   StringBuilder strBuilder = new StringBuilder();  for(byte b:hash)    strBuilder.append(String.format("%02x", b));  >  String strHash = strBuilder.toString();  System.out.println("The MD5 hash: "+strHash);  > > 
Enter message: Hello Java Your input: Hello Java Enter message: I'm Peter The MD5 hash: 9008f99fa602a036ce0c7a6784b240b1 

Conclusion

One of the fundamental security measures that we should ensure while sharing the data is to ensure data integrity. Therefore, we need a hashing algorithm that produces a checksum of the data shared with the receiver to ensure integrity.

We have understood the method to generate the MD5 checksum using the MessageDigest class and its methods. It’s best to be cautious when reading data in chunks so that you don’t end up with incorrect results.

Copyright © 2023. All right reserved

Источник

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