1090

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

azbarcea
  • 3,323
  • 1
  • 20
  • 25
Akshay
  • 11,803
  • 5
  • 29
  • 26

34 Answers34

728

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.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
koregan
  • 10,054
  • 4
  • 23
  • 36
  • “LATIN1” != “ASCII” (or “US-ASCII”). ASCII is a 7-bit character set, Latin1 is an 8-bit character set. They are not the same. – Bombe Jan 07 '09 at 07:57
  • 9
    (see http://www.joelonsoftware.com/articles/Unicode.html for much better rationale and explanation) – Piskvor left the building Jan 07 '09 at 19:57
  • 18
    [This topic](http://stackoverflow.com/questions/332079/in-java-how-do-i-convert-a-byte-array-to-a-string-of-hex-digits-while-keeping-l) is also useful if you need to convert the resulting bytes to hex string. – weekens May 22 '12 at 07:25
  • and what about if I want the pure string ? – albanx Nov 04 '15 at 23:09
  • @albanx : there is no such thing as a "pure string", unless you meant the serialized contents of the Java object itself. Please refer to the previously posted link to Joel On Software. – Daniel Kamil Kozar Feb 20 '16 at 23:29
  • @DanielKamilKozar I needed the hex string to save in db. dac2009 has posted the solution for this – albanx Feb 20 '16 at 23:41
  • This was very easy and simple I would recommend this for all of the visitors – Humphrey Nov 03 '17 at 12:49
  • 2
    Then how do u convert this thedigest to a string so that we can insert it in mysql ? – Humphrey Nov 08 '17 at 08:39
  • 7
    Better yet, where possible use `yourString.getBytes(StandardCharsets.UTF_8)`. This prevents handling an `UnsupportedEncodingException`. – Hummeling Engineering BV Mar 07 '19 at 10:28
645

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.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Bombe
  • 81,643
  • 20
  • 123
  • 127
  • 157
    One thing that's not mentioned here, and caught me by surprise. The MessageDigest classes are NOT thread safe. If they're going to be used by different threads, just create a new one, instead of trying to reuse them. – mjuarez Mar 07 '13 at 06:34
  • 43
    It uses multiple methods to mutate its internal state. How can the lack of thread safety be surprising at all? – Bombe Apr 25 '13 at 07:57
  • 102
    @Bombe: why should we expect to *have* to know about MessageDigest's internal state? – Dan Barowy Jul 01 '14 at 14:10
  • 32
    @DanBarowy well, you *are* mutating it (i.e. calling methods that do not return values but cause other methods to return different values) so until proven otherwise you should always assume that it’s not thread-safe to do so. – Bombe Jul 09 '14 at 18:17
  • 4
    @Traubenfuchs `MessageDigest` allows you to input the data in chunks. That wouldn't be possible with a static method. Although you can argue they should have added one anyway for convenience when you can pass all the data at once. – user253751 Aug 16 '15 at 12:39
  • Makes sense. I guess you wouldn't always want to move around byte arrays with multiple Gigabytes! Still, just let it take a stream. – ASA Aug 17 '15 at 09:42
  • @Traubenfuchs and what would it do with the bytes that it read from that stream, throw them away? – kbolino May 28 '16 at 03:00
  • I believe back when I wrote this I thought about an "finalized" & "ready for consumption" InputStream that would be fully drained by the static method. Any necessary state would be saved in the method body. – ASA May 28 '16 at 09:05
  • 1
    This does not answer the question, it's just a couple of links. https://stackoverflow.com/help/how-to-answer – Fran Marzoa Feb 20 '18 at 20:13
276

If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
  hashtext = "0"+hashtext;
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
user49913
  • 3,018
  • 1
  • 17
  • 8
  • 12
    @BalusC: Not true, the BigInteger.toString method will return the full number in the base specified. 0x0606 will be printed as 606, just trailing zeros are omitted, – Spidey Aug 29 '10 at 22:29
  • 11
    Minor nitpick: m.reset() isn't necessary right after calling getInstance. More minor: 'your text here' requires double-quotes. – David Leppik Apr 19 '11 at 15:28
  • From Java 11 on, you can use `hashtext = "0".repeat(32 - hashtext.length()) + hashtext` instead of the `while`, so the editors won't give you a warning that you're doing string concatenation inside a loop. – tom May 14 '19 at 13:29
  • Instead of m.update(plaintext.getBytes()); I would recommend specifying the encoding. such as m.update(plaintext.getBytes("UTF-8")); getBytes() does not guarantee the encoding and may vary from system to system which may result in different MD5 results between systems for the same String. – user1819780 Mar 27 '20 at 05:35
264

You might also want to look at the DigestUtils class of the apache commons codec project, which provides very convenient methods to create MD5 or SHA digests.

lutzh
  • 4,917
  • 1
  • 18
  • 21
  • 2
    In particular, the methods which return "safe" encoded representations of the byte data in string form. – Rob Jan 07 '09 at 19:21
  • 4
    However there is no easy way to get the DigestUtils class into your project without adding a ton of libs, or porting the class "per hand" which requires at least two more classes. – iuiz Jul 23 '11 at 20:52
  • Can't find it in maven repos either. Grrrr. – sparkyspider Oct 04 '11 at 16:05
  • 5
    Should be in the central Maven repositories, unless I'm going crazy: groupId=commons-codec artifactId=commons-codec version=1.5 – Nick Spacek Oct 12 '11 at 17:10
174

Found this:

public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
       }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}

on the site below, I take no credit for it, but its a solution that works! For me lots of other code didnt work properly, I ended up missing 0s in the hash. This one seems to be the same as PHP has. source: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093

dac2009
  • 3,521
  • 1
  • 22
  • 22
  • 15
    You should specify the encoding to be used in `getBytes()`, otherwise your code will get different results on different platforms/user settings. – Paŭlo Ebermann Jul 03 '11 at 21:57
  • @PaŭloEbermann does MessageDigest.getInstance("MD5"); not enough? I tried to add "MD5" in getBytes() but it returned an error – Blaze Tama Feb 19 '14 at 05:29
  • 2
    @BlazeTama "MD5" is not an encoding, it is a message digest algorithm (and not one which should be used in new applications). An encoding is an algorithm pair which transforms bytes to strings and strings to bytes. An example would be "UTF-8", "US-ASCII", "ISO-8859-1", "UTF-16BE", and similar. Use the same encoding as every other party which calculates a hash of this string, otherwise you'll get different results. – Paŭlo Ebermann Feb 21 '14 at 19:48
  • 6
    For an example of the character set... (use UTF-8, that is the best and most compatible in my opinion)... `byte[] array = md.digest(md5.getBytes(Charset.forName("UTF-8")));` – Richard Nov 25 '14 at 01:56
  • Since its not my solution, and I didnt test all scenarios myself, I will leave it unchanged, although I think specifiying encoding etc is probably a good idea. – dac2009 Jul 08 '19 at 10:45
98

I've found this to be the most clear and concise way to do it:

MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
rednoah
  • 1,053
  • 14
  • 41
  • 3
    Great. It doesn't fall into the trap of cutting leading zeros. – Markus Pscheidt Jun 10 '16 at 07:29
  • 2
    Beware this won't work for Android if you're using API level < 19, but you just need to change the second line with md5.update(string.getBytes("UTF-8")); This will add yet another checked exception to handle, though... – Fran Marzoa Feb 20 '18 at 20:27
97

Here is how I use it:

final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));

where Hex is: org.apache.commons.codec.binary.Hex from the Apache Commons project.

bluish
  • 26,356
  • 27
  • 122
  • 180
adranale
  • 2,835
  • 1
  • 21
  • 39
  • 16
    If you use Apache Commons Codec anyway you can use: http://commons.apache.org/codec/api-release/org/apache/commons/codec/digest/DigestUtils.html#md5Hex(java.lang.String) – squiddle Oct 25 '10 at 15:10
  • 15
    I would replace last line with this: `String result = Hex.encodeHexString(resultByte);` – bluish May 24 '11 at 09:35
87

I just downloaded commons-codec.jar and got perfect php like md5. Here is manual.

Just import it to your project and use

String Url = "your_url";

System.out.println( DigestUtils.md5Hex( Url ) );

and there you have it.

Eugene
  • 4,352
  • 8
  • 55
  • 79
  • 1
    This is the method that provides the same return value as the MySQL function md5(str). A lot of the other answers did return other values. – rwitzel Mar 18 '15 at 14:54
  • 1
    This doesn't work right on Android because Android bundles commons-codec 1.2, for which you need this workaround: http://stackoverflow.com/a/9284092/2413303 – EpicPandaForce Mar 19 '15 at 10:22
  • Worked perfectly for Gravatar's email MD5 hash!, Thank you – Logesh S Aug 29 '21 at 12:35
36

No need to make it too complicated.
DigestUtils works fine and makes you comfortable while working with md5 hashes.

DigestUtils.md5Hex(_hash);

or

DigestUtils.md5(_hash);

Either you can use any other encryption methods such as sha or md.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
fth
  • 2,478
  • 2
  • 30
  • 44
35

Found this solution which is much cleaner in terms of getting a String representation back from an MD5 hash.

import java.security.*;
import java.math.*;

public class MD5 {
    public static void main(String args[]) throws Exception{
        String s="This is a test";
        MessageDigest m=MessageDigest.getInstance("MD5");
        m.update(s.getBytes(),0,s.length());
        System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
    }
}

The code was extracted from here.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
Heshan Perera
  • 4,592
  • 8
  • 44
  • 57
  • 2
    Why has this answer -1 while the other, shorter and less descriptive answer has +146? – Nilzor Feb 12 '13 at 12:17
  • 4
    Nice using BigInteger to get a hex value +1 – Dave.B Mar 14 '13 at 17:42
  • 5
    I just found out that in some cases this only generates 31 characters long MD5 sum, not 32 as it should be – kovica Mar 29 '13 at 14:09
  • 3
    @kovica this is because, the starting zeros get truncated if I remember right.. `String.format("%032x", new BigInteger(1, hash));` This should solve this. 'hash' is the byte[] of the hash. – Heshan Perera Apr 01 '13 at 05:10
  • This answer has bug with charset type! – Gelldur Apr 13 '15 at 10:24
  • @HeshanPerera How come you mentioned in your answer "getting a String representation back from an MD5 hash"!!? But your code shows logic to convert String to Md5 hash. If I am not wrong MD5 hash is a one way algorithm and it can't be converted back to original String. – supernova Sep 17 '15 at 15:39
  • 1
    This seems far superior. You don't even have to capture as many exceptions either. – JGFMK Jan 02 '20 at 22:30
35

Another implementation:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
stacker
  • 68,052
  • 28
  • 140
  • 210
  • 2
    Only one-liner I've seen that doesn't use an external library. – holmis83 Feb 07 '17 at 09:33
  • Unless I'm mistaken this returns always in uppercase which will not align with md5's made without using hex. Not even really sure it is a true md5 – walshie4 Jun 29 '17 at 02:00
32

Another option is to use the Guava Hashing methods:

Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();

Handy if you are already using Guava (which if you're not, you probably should be).

andrewrjones
  • 1,801
  • 21
  • 25
29

I have a Class (Hash) to convert plain text in hash in formats: md5 or sha1, simillar that php functions (md5, sha1):

public class Hash {
    /**
     * 
     * @param txt, text in plain format
     * @param hashType MD5 OR SHA1
     * @return hash in hashType 
     */
    public static String getHash(String txt, String hashType) {
        try {
                    java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
                    byte[] array = md.digest(txt.getBytes());
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < array.length; ++i) {
                        sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
                 }
                    return sb.toString();
            } catch (java.security.NoSuchAlgorithmException e) {
                //error action
            }
            return null;
    }

    public static String md5(String txt) {
        return Hash.getHash(txt, "MD5");
    }

    public static String sha1(String txt) {
        return Hash.getHash(txt, "SHA1");
    }
}

Testing with JUnit and PHP

PHP Script:

<?php

echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";

Output PHP script:

MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0

Using example and Testing with JUnit:

    public class HashTest {

    @Test
    public void test() {
        String txt = "Hello World";
        assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
        assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
    }

}

Code in GitHub

https://github.com/fitorec/java-hashes

fitorec
  • 1,022
  • 12
  • 10
22

My not very revealing answer:

private String md5(String s) {
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes(), 0, s.length());
        BigInteger i = new BigInteger(1,m.digest());
        return String.format("%1$032x", i);         
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}
marioosh
  • 27,328
  • 49
  • 143
  • 192
18

There is a DigestUtils class in Spring also:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/DigestUtils.html

This class contains the method md5DigestAsHex() that does the job.

Austin Henley
  • 4,625
  • 13
  • 45
  • 80
Raul Luna
  • 1,945
  • 1
  • 17
  • 26
  • BTW: The performance of this is much better then using BigInteger to create the hex string representation. – James Apr 17 '18 at 09:37
18

You can try following. See details and download codes here: http://jkssweetlife.com/java-hashgenerator-md5-sha-1/

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Example {

public static void main(String[] args) throws Exception {

    final String inputString = "Hello MD5";

    System.out.println("MD5 hex for '" + inputString + "' :");
    System.out.println(getMD5Hex(inputString));
}

public static String getMD5Hex(final String inputString) throws NoSuchAlgorithmException {

    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(inputString.getBytes());

    byte[] digest = md.digest();

    return convertByteToHex(digest);
}

private static String convertByteToHex(byte[] byteData) {

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    return sb.toString();
}
}
ylu
  • 867
  • 8
  • 5
15

Bombe's answer is correct, however note that unless you absolutely must use MD5 (e.g. forced on you for interoperability), a better choice is SHA1 as MD5 has weaknesses for long term use.

I should add that SHA1 also has theoretical vulnerabilities, but not as severe. The current state of the art in hashing is that there are a number of candidate replacement hash functions but none have yet emerged as the standard best practice to replace SHA1. So, depending on your needs you would be well advised to make your hash algorithm configurable so it can be replaced in future.

frankodwyer
  • 13,948
  • 9
  • 50
  • 70
  • Could you point me to some resources, where i can read about relative merits and weaknesses of each? – Akshay Jan 06 '09 at 10:19
  • Probably the best you can do at the moment is use SHA1 and be ready to replace it in future. You could use newer functions but they have not yet been subject to great amounts of research. You could track online security resources to find out when this changes - for example Bruce Schneier's blog. – frankodwyer Jan 06 '09 at 10:49
  • 8
    SHA1 is overkill unless you want a cryptographically secure hash, i.e. you don't want the hash to help in reconstructing the original message, nor do you want a clever attacker to create another message which matches the hash. If the original isn't a secret and the hash isn't being used for security, MD5 is fast and easy. For example, Google Web Toolkit uses MD5 hashes in JavaScript URLs (e.g. foo.js?hash=12345). – David Leppik Apr 19 '11 at 15:14
13

Another implementation: Fast MD5 Implementation in Java

String hash = MD5.asHex(MD5.getHash(new File(filename)));
Lukasz R.
  • 2,265
  • 1
  • 24
  • 22
11

I do not know if this is relevant for anyone reading this, but I just had the problem that I wanted to

  • download a file from a given URL and
  • compare its MD5 to a known value.

I wanted to do it with JRE classes only (no Apache Commons or similar). A quick web search did not show me sample code snippets doing both at the same time, only each task separately. Because this requires to read the same file twice, I figured it might be worth the while to write some code which unifies both tasks, calculating the checksum on the fly while downloading the file. This is my result (sorry if it is not perfect Java, but I guess you get the idea anyway):

import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.DigestOutputStream;        // new
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

void downloadFile(String fromURL, String toFile, BigInteger md5)
    throws IOException, NoSuchAlgorithmException
{
    ReadableByteChannel in = Channels.newChannel(new URL(fromURL).openStream());
    MessageDigest md5Digest = MessageDigest.getInstance("MD5");
    WritableByteChannel out = Channels.newChannel(
        //new FileOutputStream(toFile));  // old
        new DigestOutputStream(new FileOutputStream(toFile), md5Digest));  // new
    ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);  // 1 MB

    while (in.read(buffer) != -1) {
        buffer.flip();
        //md5Digest.update(buffer.asReadOnlyBuffer());  // old
        out.write(buffer);
        buffer.clear();
    }

    BigInteger md5Actual = new BigInteger(1, md5Digest.digest()); 
    if (! md5Actual.equals(md5))
        throw new RuntimeException(
            "MD5 mismatch for file " + toFile +
            ": expected " + md5.toString(16) +
            ", got " + md5Actual.toString(16)
        );
}
kriegaex
  • 63,017
  • 15
  • 111
  • 202
  • 1
    Oh BTW, before anyone except for myself notices how bad my JRE knowledge really is: I just discovered [DigestInputStream](http://docs.oracle.com/javase/7/docs/api/java/security/DigestInputStream.html) and [DigestOutputStream](http://docs.oracle.com/javase/7/docs/api/java/security/DigestOutputStream.html). I am going to edit my original solution to reflect what I have just learned. – kriegaex Jun 26 '12 at 08:45
9
import java.security.*;
import javax.xml.bind.*;

byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytesOfDigest = md.digest(bytesOfMessage);
String digest = DatatypeConverter.printHexBinary(bytesOfDigest).toLowerCase();
Giancarlo Romeo
  • 663
  • 1
  • 9
  • 24
8

Unlike PHP where you can do an MD5 hashing of your text by just calling md5 function ie md5($text), in Java it was made little bit complicated. I usually implemented it by calling a function which returns the md5 hash text. Here is how I implemented it, First create a function named md5hashing inside your main class as given below.

public static String md5hashing(String text)
    {   String hashtext = null;
        try 
        {
            String plaintext = text;
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.reset();
            m.update(plaintext.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1,digest);
            hashtext = bigInt.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while(hashtext.length() < 32 ){
              hashtext = "0"+hashtext;   
            }
        } catch (Exception e1) 
        {
            // TODO: handle exception
            JOptionPane.showMessageDialog(null,e1.getClass().getName() + ": " + e1.getMessage());   
        }
        return hashtext;     
    }

Now call the function whenever you needed as given below.

String text = textFieldName.getText();
String pass = md5hashing(text);

Here you can see that hashtext is appended with a zero to make it match with md5 hashing in PHP.

Geordy James
  • 2,358
  • 3
  • 25
  • 34
6

For what it's worth, I stumbled upon this because I want to synthesize GUIDs from a natural key for a program that will install COM components; I want to syhthesize so as not to manage GUID lifecycle. I'll use MD5 and then use the UUID class to get a string out of it. (http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 raises this issue).

In any case, java.util.UUID can get you a nice String from the MD5 bytes.

return UUID.nameUUIDFromBytes(md5Bytes).toString();
Mihai Danila
  • 2,229
  • 1
  • 23
  • 28
  • actually it accepts not only MD5 bytes array (size == 16). You can pass byte array of any length. It will be converted to MD5 bytes array by means of MD5 `MessageDigest` (see [nameUUIDFromBytes() source code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/UUID.java#UUID.nameUUIDFromBytes%28byte%5B%5D%29)) – Ilya Serbis Oct 20 '17 at 22:18
6

MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

5

this one gives the exact md5 as you get from mysql's md5 function or php's md5 functions etc. This is the one I use (you can change according to your needs)

public static String md5( String input ) {
    try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(input.getBytes( "UTF-8" ));
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            sb.append( String.format( "%02x", array[i]));
        }
        return sb.toString();
    } catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
        return null;            
    }

}
Aurangzeb
  • 1,537
  • 13
  • 9
5
import java.security.MessageDigest

val digest = MessageDigest.getInstance("MD5")

//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString

//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString

//Output
println(md5hash1 + " should be the same as " + md5hash2)
HimalayanCoder
  • 9,630
  • 6
  • 59
  • 60
5

You can generate MD5 hash for a given text by making use of the methods in the MessageDigest class in the java.security package. Below is the complete code snippet,

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;

public class MD5HashGenerator 
{

   public static void main(String args[]) throws NoSuchAlgorithmException
   {
       String stringToHash = "MyJavaCode"; 
       MessageDigest messageDigest = MessageDigest.getInstance("MD5");
       messageDigest.update(stringToHash.getBytes());
       byte[] digiest = messageDigest.digest();
       String hashedOutput = DatatypeConverter.printHexBinary(digiest);
       System.out.println(hashedOutput);
   }
}

The output from the MD5 function is a 128 bit hash represented by 32 hexadecimal numbers.

In case, if you are using a database like MySQL, you can do this in a more simpler way as well. The query Select MD5(“text here”) will return the MD5 hash of the text in the bracket.

Ali
  • 2,702
  • 3
  • 32
  • 54
Prasanna L M
  • 301
  • 3
  • 6
4

try this:

public static String getHashMD5(String string) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
        return bi.toString(16);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(MD5Utils.class
                .getName()).log(Level.SEVERE, null, ex);

        return "";
    }
}
2

This is what I came here for- a handy scala function that returns string of MD5 hash:

def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
Priyank Desai
  • 3,693
  • 1
  • 27
  • 17
0
 import java.math.BigInteger;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;

/**
* MD5 encryption
*
* @author Hongten
*
*/
public class MD5 {

 public static void main(String[] args) {
     System.out.println(MD5.getMD5("123456"));
 }

 /**
  * Use md5 encoded code value
  *
  * @param sInput
  * clearly
  * @ return md5 encrypted password
  */
 public static String getMD5(String sInput) {

     String algorithm = "";
     if (sInput == null) {
         return "null";
     }
     try {
         algorithm = System.getProperty("MD5.algorithm", "MD5");
     } catch (SecurityException se) {
     }
     MessageDigest md = null;
     try {
         md = MessageDigest.getInstance(algorithm);
     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }
     byte buffer[] = sInput.getBytes();

     for (int count = 0; count < sInput.length(); count++) {
         md.update(buffer, 0, count);
     }
     byte bDigest[] = md.digest();
     BigInteger bi = new BigInteger(bDigest);
     return (bi.toString(16));
 }
}

There is an article on Codingkit about that. Check out: http://codingkit.com/a/JAVA/2013/1020/2216.html

dcaswell
  • 3,137
  • 2
  • 26
  • 25
shouyu
  • 11
  • 2
0

You could try using Caesar.

First option:

byte[] hash =
    new Hash(
        new ImmutableMessageDigest(
            MessageDigest.getInstance("MD5")
        ),
        new PlainText("String to hash...")
    ).asArray();

Second option:

byte[] hash =
    new ImmutableMessageDigest(
        MessageDigest.getInstance("MD5")
    ).update(
        new PlainText("String to hash...")
    ).digest();
Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
-1
private String hashuj(String dane) throws ServletException{
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] bufor = dane.getBytes();
        m.update(bufor,0,bufor.length);
        BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
        return String.format("%1$032X", hash);

    } catch (NoSuchAlgorithmException nsae) {
        throw new ServletException("Algorytm szyfrowania nie jest obsługiwany!");
    }
}
Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
Radek
  • 11
  • Welcome to _StackOverflow_, you might want to read [how to post an answer](http://stackoverflow.com/help/how-to-answer) before doing so. Give a bit of context explaining why you posted that code and what does it do. Also consider taking the time to format your answer to be easily understood by readers. – Nacho Apr 11 '16 at 17:37
-1

Simple function using java.security.MessageDigest library

public String stringMD5Hash(String text) throws NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    byte[] bytes = messageDigest.digest(text.getBytes());
    StringJoiner stringJoiner = new StringJoiner("");
    for (byte b : bytes) {
        stringJoiner.add(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
    }
    return stringJoiner.toString();
}

and for files use this function

public static String FileMD5Hash(File file) throws NoSuchAlgorithmException, IOException {
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    byte[] bytes = messageDigest.digest(getFileBytes(file));
    StringJoiner stringJoiner = new StringJoiner("");
    for (byte b : bytes) {
        stringJoiner.add(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
    }
    return stringJoiner.toString();
}

public static byte[] getFileBytes(File file) throws IOException{
    InputStream inputStream = new FileInputStream(file);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] bytes = new byte[1024];
    int bytesRead;
    while ((bytesRead = inputStream.read(bytes)) != -1) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    return byteArrayOutputStream.toByteArray();
}
TheShoqanebi
  • 112
  • 4
-4

I did this... Seems to work ok - I'm sure somebody will point out mistakes though...

public final class MD5 {
public enum SaltOption {
    BEFORE, AFTER, BOTH, NONE;
}
private static final String ALG = "MD5";
//For conversion to 2-char hex
private static final char[] digits = {
    '0' , '1' , '2' , '3' , '4' , '5' ,
    '6' , '7' , '8' , '9' , 'a' , 'b' ,
    'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};

private SaltOption opt;

/**
 * Added the SaltOption constructor since everybody
 * has their own standards when it comes to salting
 * hashes.
 * 
 * This gives the developer the option...
 * 
 * @param option The salt option to use, BEFORE, AFTER, BOTH or NONE.
 */
public MD5(final SaltOption option) {
    //TODO: Add Char Encoding options too... I was too lazy!
    this.opt = option;
}

/**
 * 
 * Returns the salted MD5 checksum of the text passed in as an argument.
 * 
 * If the salt is an empty byte array - no salt is applied.
 * 
 * @param txt The text to run through the MD5 algorithm.
 * @param salt The salt value in bytes.
 * @return The salted MD5 checksum as a <code>byte[]</code>
 * @throws NoSuchAlgorithmException
 */
private byte[] createChecksum(final String txt, final byte[] salt) throws NoSuchAlgorithmException {
    final MessageDigest complete = MessageDigest.getInstance(ALG);
    if(opt.equals(SaltOption.BEFORE) || opt.equals(SaltOption.BOTH)) {
        complete.update(salt);
    }
    complete.update(txt.getBytes());
    if(opt.equals(SaltOption.AFTER) || opt.equals(SaltOption.BOTH)) {
        complete.update(salt);
    }
    return complete.digest();
}

/**
 * 
 * Returns the salted MD5 checksum of the file passed in as an argument.
 * 
 * If the salt is an empty byte array - no salt is applied.
 * 
 * @param fle The file to run through the MD5 algorithm.
 * @param salt The salt value in bytes.
 * @return The salted MD5 checksum as a <code>byte[]</code>
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
private byte[] createChecksum(final File fle, final byte[] salt)
        throws IOException, NoSuchAlgorithmException {
    final byte[] buffer = new byte[1024];
    final MessageDigest complete = MessageDigest.getInstance(ALG);
            if(opt.equals(SaltOption.BEFORE) || opt.equals(SaltOption.BOTH)) {
            complete.update(salt);
        }
    int numRead;
    InputStream fis = null;
    try {
        fis = new FileInputStream(fle);
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
    } finally {
    if (fis != null) {
            fis.close();
        }
    }
            if(opt.equals(SaltOption.AFTER) || opt.equals(SaltOption.BOTH)) {
            complete.update(salt);
        }
    return complete.digest();
}

/**
 * 
 * Efficiently converts a byte array to its 2 char per byte hex equivalent.
 * 
 * This was adapted from JDK code in the Integer class, I just didn't like
 * having to use substrings once I got the result...
 *
 * @param b The byte array to convert
 * @return The converted String, 2 chars per byte...
 */
private String convertToHex(final byte[] b) {
    int x;
    int charPos;
    int radix;
    int mask;
    final char[] buf = new char[32];
    final char[] tmp = new char[3];
    final StringBuilder md5 = new StringBuilder();
    for (int i = 0; i < b.length; i++) {
        x = (b[i] & 0xFF) | 0x100;
        charPos = 32;
        radix = 1 << 4;
        mask = radix - 1;
        do {
            buf[--charPos] = digits[x & mask];
            x >>>= 4;
        } while (x != 0);
        System.arraycopy(buf, charPos, tmp, 0, (32 - charPos));
        md5.append(Arrays.copyOfRange(tmp, 1, 3));
    }
    return md5.toString();
}

/**
 * 
 * Returns the salted MD5 checksum of the file passed in as an argument.
 * 
 * @param fle The file you want want to run through the MD5 algorithm.
 * @param salt The salt value in bytes
 * @return The salted MD5 checksum as a 2 char per byte HEX <code>String</code>
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public String getMD5Checksum(final File fle, final byte[] salt)
        throws NoSuchAlgorithmException, IOException {
    return convertToHex(createChecksum(fle, salt));
}

/**
 * 
 * Returns the MD5 checksum of the file passed in as an argument.
 * 
 * @param fle The file you want want to run through the MD5 algorithm.
 * @return The MD5 checksum as a 2 char per byte HEX <code>String</code>
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public String getMD5Checksum(final File fle)
        throws NoSuchAlgorithmException, IOException {
    return convertToHex(createChecksum(fle, new byte[0]));
}

/**
 * 
 * Returns the salted MD5 checksum of the text passed in as an argument.
 * 
 * @param txt The text you want want to run through the MD5 algorithm.
 * @param salt The salt value in bytes.
 * @return The salted MD5 checksum as a 2 char per byte HEX <code>String</code>
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public String getMD5Checksum(final String txt, final byte[] salt)
        throws NoSuchAlgorithmException {
    return convertToHex(createChecksum(txt, salt));
}

/**
 * 
 * Returns the MD5 checksum of the text passed in as an argument.
 * 
 * @param txt The text you want want to run through the MD5 algorithm.
 * @return The MD5 checksum as a 2 char per byte HEX <code>String</code>
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public String getMD5Checksum(final String txt)
        throws NoSuchAlgorithmException {

    return convertToHex(createChecksum(txt, new byte[0]));
}
}
Umesh Aawte
  • 4,590
  • 7
  • 41
  • 51
-7

I have made this using php as follows

<?php
$goodtext = "Not found";
// If there is no parameter, this code is all skipped
if ( isset($_GET['md5']) ) {
    $time_pre = microtime(true);
    $md5 = $_GET['md5'];
    // This is our alphabet
    $txt = "0123456789";
    $show = 15;
    // Outer loop go go through the alphabet for the
    // first position in our "possible" pre-hash
    // text
    for($i=0; $i<strlen($txt); $i++ ) {
        $ch1 = $txt[$i];   // The first of two characters
        // Our inner loop Note the use of new variables
        // $j and $ch2 
        for($j=0; $j<strlen($txt); $j++ ) {
            $ch2 = $txt[$j];  // Our second character
            for($k=0; $k<strlen($txt); $k++ ) {
                $ch3 = $txt[$k];
                for($l=0; $l<strlen($txt); $l++){
                    $ch4 = $txt[$l];
                    // Concatenate the two characters together to 
                    // form the "possible" pre-hash text
                    $try = $ch1.$ch2.$ch3.$ch4;
                    // Run the hash and then check to see if we match
                    $check = hash('md5', $try);
                    if ( $check == $md5 ) {
                        $goodtext = $try;
                        break;   // Exit the inner loop
                    }
                    // Debug output until $show hits 0
                    if ( $show > 0 ) {
                        print "$check $try\n";
                        $show = $show - 1;
                    }
                    if($goodtext == $try){
                        break;
                    }
                }
                if($goodtext == $try){
                    break;
                }
            }
            if($goodtext == $try) {
                break;  
            }
        }
        if($goodtext == $try){
            break;
        }
    }
    // Compute ellapsed time
    $time_post = microtime(true);
    print "Ellapsed time: ";
    print $time_post-$time_pre;
    print "\n";
}
?>

you may refer this - source

Anupam Haldkar
  • 985
  • 13
  • 15