Java create md5 hash

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

Источник

MD5 пример использования в Java

Вам нужно зашифровать пароль либо другие данные, в таком случае можно использовать MD5 шифрование.

MD5 ( Message Digest 5 ) — 128-битный алгоритм хеширования , разработанный профессором Рональдом Л. Ривестом в 1991 году . Предназначен для создания «отпечатков» или дайджестов сообщения произвольной длины и последующей проверки их подлинности.

Для приведения примеров я создал класс MD5Util.java в котором реализую два метода генерации MD5.

Метод #1: Собственная реализация

Ниже приведен пример реализации:

public static String md5Custom(String st) < MessageDigest messageDigest = null; byte[] digest = new byte[0]; try < messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(st.getBytes()); digest = messageDigest.digest(); >catch (NoSuchAlgorithmException e) < // тут можно обработать ошибку // возникает она если в передаваемый алгоритм в getInstance(. ) не существует e.printStackTrace(); >BigInteger bigInt = new BigInteger(1, digest); String md5Hex = bigInt.toString(16); while( md5Hex.length() < 32 )< md5Hex = "0" + md5Hex; >return md5Hex; >

Хеш содержит 128 бит (16 байт) поэтому мы в строке 17 указали 16 байтов, в строке 19 было указанно 32 так как обычно хеш 16 байтов представляется как последовательность из 32 шестнадцатеричных цифр.

Метод #2: Apache Common Codec

Этот метод заключается в использовании готовой реализации MD5.

Для того чтобы использовать реализацию Apache Common Codec нужно подключить его к проекту. Если использовать Maven то нужно подключить к вашему проекту зависимость:

 commons-codec commons-codec 1.9 

И ниже пример использования:

public static String md5Apache(String st)

DigestUtils – это утильный класс позволяющий зашифровать данные в MD5 и другие типы шифрования.

Использование

Вызов методов утильного класса MD5Util.java со строкой devcolibri:

public static void main(String[] args)

Custom MD5: 4fa25efdd84d2e2c9f206980d4ccfff1 Apache MD5: 4fa25efdd84d2e2c9f206980d4ccfff1

ПОХОЖИЕ ПУБЛИКАЦИИ

21 комментариев к статье «MD5 пример использования в Java»

а почему не указал в обратную сторону , т.е. как расшифровать md5 например , если хранить пароли пользователей в базе

Потому что расшифровать md5 возможно, но это очень и очень трудоемкий процесс. Но если хранить пароль в БД и вы хотите сравнить их, то расшифровывать пароль не надо нужно просто второй не зашифрованный зашифровать и сравнить их.

На данный момент расшифровать MD5 уже совершенно не трудоемкий процесс, будет ли туториал по современным методам хеширования?

Хеш-сумму, полученную с помощью любого метода хеширования (не важно, MD5 это, или какой-нибудь SHA1) расшифровать невозможно, и не будет никогда возможно. Начнём с того, что MD5 это не шифрование вообще, а всего лишь хеш-сумма. Хеш можно взять с любого объёма данных. Представьте, у нас есть файл размером 50Гб, мы берём с него хеш-сумму и получаем 32-байтовую строку (в обычном MD5). Получается, что мы сжали данные объёмом в 53687091200 байт всего до 32. Вы сами-то в этом верите?

Дело не в трудоемкости, а в безопасности. Не стоит хранить в бд пароли юзеров, т.к их могут украсть. Храни хеши, и сравнивай хеши….

Александр, есть правильные вопросы, а есть неправильные. Alex задал неправильный вопрос, который говорит, что он не совсем понимает тему, про которую задает вопрос. И вместо того, что бы отвечать на его некомпетентный вопрос, наверно лучше сказать, что он изначально неправильно видит ситуацию.
1) Например то, что md5 служит для именно для одностороннего преобразования, а значит декодирование в принципе не для этого алгоритма….
2) Ну и второе, человек рассуждает о хранении паролей в БД….вместо того, что бы намекнуть о изначально неправильном подходе, Вы подогреваете его неверные рассуждения.
При этом, я всего-лишь хотел поправить его вектор мыслей…. 🙂 Да, вероятно такие вопросы идут из-за не очень продуманного введения к статье. Практики много, теории ноль, что в итоге ведет к непониманию и оторванности решения от постановки задачи.

В статье же не сря метка NOTE стоит 🙂 Это тип заметки, который не подразумевает детальное описание всего. Но вас я понял, учту)

Источник

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

Источник

Читайте также:  Build menu in css
Оцените статью