Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate an MD5 hash in Java?

Is there any method to generate MD5 hash of a string in Java?

like image 372
Akshay Avatar asked Jan 06 '09 09:01

Akshay


People also ask

What is MD5 algorithm in Java?

MD5 is a widely used cryptographic hash function, which produces a hash of 128 bit. In this article, we will see different approaches to create MD5 hashes using various Java libraries.

How do you make a string hash in Java?

Java String hashCode() Method The hashCode() method returns the hash code of a string. where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.


2 Answers

The MessageDigest class can provide you with an instance of the MD5 digest.

When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default. (Not all platforms use the same defaults)

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] theMD5digest = md.digest(bytesOfMessage);

If you have a lot of data take a look at the .update(xxx) methods which can be called repeatedly. Then call .digest() to obtain the resulting hash.

like image 111
koregan Avatar answered Oct 19 '22 19:10

koregan


You need java.security.MessageDigest.

Call MessageDigest.getInstance("MD5") to get a MD5 instance of MessageDigest you can use.

The compute the hash by doing one of:

  • Feed the entire input as a byte[] and calculate the hash in one operation with md.digest(bytes).
  • Feed the MessageDigest one byte[] chunk at a time by calling md.update(bytes). When you're done adding input bytes, calculate the hash with md.digest().

The byte[] returned by md.digest() is the MD5 hash.

like image 641
Bombe Avatar answered Oct 19 '22 20:10

Bombe