如何生成MD5散列?

时间:2022-10-28 17:33:54

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

在Java中是否有生成字符串MD5散列的方法?

32 个解决方案

#1


521  

java.security.MessageDigest is your friend. Call getInstance("MD5") to get an MD5 message digest you can use.

java.security。MessageDigest是你的朋友。调用getInstance(“MD5”)来获得您可以使用的MD5消息摘要。

#2


631  

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

MessageDigest类可以为您提供MD5摘要的一个实例。

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)

在使用字符串和加密类时,一定要始终指定要在其中进行字节表示的编码。如果您只是使用string.getBytes(),它将使用平台默认值。(并非所有平台都使用相同的缺省值)

import java.security.*;

..

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

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

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

如果您有大量的数据,请查看可多次调用的.update(byte[])方法。然后调用.digest()获取结果散列。

#3


243  

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.

您可能还需要查看apache commons codec项目的摘要类,它提供了创建MD5或SHA摘要的非常方便的方法。

#4


240  

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;
}

#5


145  

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

在下面的网站上,我不相信它,但它是一个有效的解决方案!对我来说,很多其他的代码都不能正常工作,最后我在散列中漏掉了0。这个看起来和PHP是一样的。资料来源:http://m2tec.be/blog/2010/02/03/java - md5 -十六进制- 0093年

#6


81  

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.

其中Hex为:org.apache.commons.codec.binary.Hex来自Apache Commons项目。

#7


74  

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

我只是commons-codec下载。jar并得到了像md5这样的完美php。这是手册。

Just import it to your project and use

只需将其导入到项目中并使用。

String Url = "your_url";

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

and there you have it.

就是这样。

#8


51  

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()));

#9


32  

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

在从MD5散列中获取字符串表示时,找到了这个更干净的解决方案。

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.

代码是从这里提取的。

#10


30  

Another option is to use the Guava Hashing methods:

另一种选择是使用Guava Hashing方法:

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).

如果你已经使用了Guava(如果你不使用Guava的话,你很可能应该使用)。

#11


28  

Another implementation:

另一个实现:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

#12


27  

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

我有一个类(散列),以格式:md5或sha1, php函数(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

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

#13


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;
}

#14


17  

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

不需要太复杂。在使用md5散列时,消化系统工作良好,使您感到舒适。

DigestUtils.md5Hex(_hash);

or

DigestUtils.md5(_hash);

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

您可以使用任何其他加密方法,如sha或md。

#15


16  

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.

但是请注意,除非您绝对必须使用MD5(例如,在您的互操作性上*使用MD5),否则一个更好的选择是SHA1,因为MD5有长期使用的弱点。

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.

我应该补充说,SHA1也有理论漏洞,但没有那么严重。哈希的当前状态是,有许多候选的替换散列函数,但还没有一个取代SHA1的标准最佳实践。因此,根据您的需要,您最好将您的散列算法配置为可配置的,以便将来可以替换它。

#16


14  

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

你可以试试。查看详细信息和下载代码:http://www.luyue.org/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();
}
}

#17


13  

There is a DigestUtils class in Spring also:

春天还有一个消化课:

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

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.

这个类包含执行任务的md5DigestAsHex()方法。

#18


9  

Another implementation: Fast MD5 Implementation in Java

另一个实现:Java中快速MD5实现。

String hash = MD5.asHex(MD5.getHash(new File(filename)));

#19


8  

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
  • 从给定的URL下载一个文件。
  • compare its MD5 to a known value.
  • 将其MD5与已知值进行比较。

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):

我想只使用JRE类(没有Apache Commons或类似的)。一个快速的web搜索并没有显示我的示例代码片段同时进行,只有每个任务单独完成。因为这需要两次读取相同的文件,所以我认为编写一些代码来统一这两个任务是值得的,在下载文件的同时计算出校验和。这是我的结果(不好意思,如果它不是完美的Java,但是我想您已经知道了):

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)
        );
}

#20


6  

Take a look at the following link, the Example gets an MD5 Hash of a supplied image: MD5 Hash of an Image

看一下下面的链接,示例得到了一个提供的图像的MD5散列:图像的MD5散列。

#21


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://*.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 raises this issue).

对于它的价值,我无意中发现了这一点,因为我想从一个自然的密钥中合成一个用于安装COM组件的程序的GUIDs;我想要syhze,以避免管理GUID生命周期。我将使用MD5,然后使用UUID类来获取一个字符串。(http://*.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439提出这个问题)。

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

在任何情况下,java.util。UUID可以从MD5字节得到一个漂亮的字符串。

return UUID.nameUUIDFromBytes(md5Bytes).toString();

#22


5  

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.

如果您不需要最好的安全性,那么MD5非常好,如果您正在做一些类似于检查文件完整性的事情,那么安全性就不是一个考虑因素。在这种情况下,您可能希望考虑一些更简单、更快的东西,比如Adler32,它也由Java库支持。

#23


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 "";
    }
}

#24


3  

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)

从mysql的md5函数或php的md5函数中可以得到确切的md5,这是我所使用的(您可以根据您的需要更改)

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;            
    }

}

#25


3  

Unlike PHP where you can do an md5 encryption 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 an function which return the md5 hash text. Here is how I implemented it , First create a function named md5encryption inside your main class as given below .

与PHP不同的是,您可以通过调用md5函数($text)来对文本进行md5加密,在java中,这是非常复杂的。我通常通过调用返回md5散列文本的函数来实现它。下面是我实现它的方法,首先在您的主类中创建一个名为md5encryption的函数,如下所示。

public static String md5encryption(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 when ever you needed as given below.

现在,当你需要的时候调用这个函数,如下所示。

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

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

这里您可以看到,hashtext添加了一个0,以使它与PHP中的md5加密相匹配。

#26


3  

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)

#27


2  

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

这就是我来这里的目的——一个方便的scala函数,返回MD5散列的字符串:

def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}

#28


2  

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();

#29


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

关于这一点,有一篇关于Codingkit的文章。查阅:http://codingkit.com/a/JAVA/2013/1020/2216.html

#30


-2  

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!");
    }
}

#1


521  

java.security.MessageDigest is your friend. Call getInstance("MD5") to get an MD5 message digest you can use.

java.security。MessageDigest是你的朋友。调用getInstance(“MD5”)来获得您可以使用的MD5消息摘要。

#2


631  

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

MessageDigest类可以为您提供MD5摘要的一个实例。

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)

在使用字符串和加密类时,一定要始终指定要在其中进行字节表示的编码。如果您只是使用string.getBytes(),它将使用平台默认值。(并非所有平台都使用相同的缺省值)

import java.security.*;

..

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

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

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

如果您有大量的数据,请查看可多次调用的.update(byte[])方法。然后调用.digest()获取结果散列。

#3


243  

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.

您可能还需要查看apache commons codec项目的摘要类,它提供了创建MD5或SHA摘要的非常方便的方法。

#4


240  

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;
}

#5


145  

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

在下面的网站上,我不相信它,但它是一个有效的解决方案!对我来说,很多其他的代码都不能正常工作,最后我在散列中漏掉了0。这个看起来和PHP是一样的。资料来源:http://m2tec.be/blog/2010/02/03/java - md5 -十六进制- 0093年

#6


81  

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.

其中Hex为:org.apache.commons.codec.binary.Hex来自Apache Commons项目。

#7


74  

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

我只是commons-codec下载。jar并得到了像md5这样的完美php。这是手册。

Just import it to your project and use

只需将其导入到项目中并使用。

String Url = "your_url";

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

and there you have it.

就是这样。

#8


51  

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()));

#9


32  

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

在从MD5散列中获取字符串表示时,找到了这个更干净的解决方案。

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.

代码是从这里提取的。

#10


30  

Another option is to use the Guava Hashing methods:

另一种选择是使用Guava Hashing方法:

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).

如果你已经使用了Guava(如果你不使用Guava的话,你很可能应该使用)。

#11


28  

Another implementation:

另一个实现:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

#12


27  

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

我有一个类(散列),以格式:md5或sha1, php函数(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

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

#13


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;
}

#14


17  

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

不需要太复杂。在使用md5散列时,消化系统工作良好,使您感到舒适。

DigestUtils.md5Hex(_hash);

or

DigestUtils.md5(_hash);

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

您可以使用任何其他加密方法,如sha或md。

#15


16  

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.

但是请注意,除非您绝对必须使用MD5(例如,在您的互操作性上*使用MD5),否则一个更好的选择是SHA1,因为MD5有长期使用的弱点。

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.

我应该补充说,SHA1也有理论漏洞,但没有那么严重。哈希的当前状态是,有许多候选的替换散列函数,但还没有一个取代SHA1的标准最佳实践。因此,根据您的需要,您最好将您的散列算法配置为可配置的,以便将来可以替换它。

#16


14  

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

你可以试试。查看详细信息和下载代码:http://www.luyue.org/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();
}
}

#17


13  

There is a DigestUtils class in Spring also:

春天还有一个消化课:

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

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.

这个类包含执行任务的md5DigestAsHex()方法。

#18


9  

Another implementation: Fast MD5 Implementation in Java

另一个实现:Java中快速MD5实现。

String hash = MD5.asHex(MD5.getHash(new File(filename)));

#19


8  

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
  • 从给定的URL下载一个文件。
  • compare its MD5 to a known value.
  • 将其MD5与已知值进行比较。

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):

我想只使用JRE类(没有Apache Commons或类似的)。一个快速的web搜索并没有显示我的示例代码片段同时进行,只有每个任务单独完成。因为这需要两次读取相同的文件,所以我认为编写一些代码来统一这两个任务是值得的,在下载文件的同时计算出校验和。这是我的结果(不好意思,如果它不是完美的Java,但是我想您已经知道了):

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)
        );
}

#20


6  

Take a look at the following link, the Example gets an MD5 Hash of a supplied image: MD5 Hash of an Image

看一下下面的链接,示例得到了一个提供的图像的MD5散列:图像的MD5散列。

#21


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://*.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 raises this issue).

对于它的价值,我无意中发现了这一点,因为我想从一个自然的密钥中合成一个用于安装COM组件的程序的GUIDs;我想要syhze,以避免管理GUID生命周期。我将使用MD5,然后使用UUID类来获取一个字符串。(http://*.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439提出这个问题)。

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

在任何情况下,java.util。UUID可以从MD5字节得到一个漂亮的字符串。

return UUID.nameUUIDFromBytes(md5Bytes).toString();

#22


5  

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.

如果您不需要最好的安全性,那么MD5非常好,如果您正在做一些类似于检查文件完整性的事情,那么安全性就不是一个考虑因素。在这种情况下,您可能希望考虑一些更简单、更快的东西,比如Adler32,它也由Java库支持。

#23


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 "";
    }
}

#24


3  

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)

从mysql的md5函数或php的md5函数中可以得到确切的md5,这是我所使用的(您可以根据您的需要更改)

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;            
    }

}

#25


3  

Unlike PHP where you can do an md5 encryption 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 an function which return the md5 hash text. Here is how I implemented it , First create a function named md5encryption inside your main class as given below .

与PHP不同的是,您可以通过调用md5函数($text)来对文本进行md5加密,在java中,这是非常复杂的。我通常通过调用返回md5散列文本的函数来实现它。下面是我实现它的方法,首先在您的主类中创建一个名为md5encryption的函数,如下所示。

public static String md5encryption(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 when ever you needed as given below.

现在,当你需要的时候调用这个函数,如下所示。

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

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

这里您可以看到,hashtext添加了一个0,以使它与PHP中的md5加密相匹配。

#26


3  

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)

#27


2  

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

这就是我来这里的目的——一个方便的scala函数,返回MD5散列的字符串:

def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}

#28


2  

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();

#29


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

关于这一点,有一篇关于Codingkit的文章。查阅:http://codingkit.com/a/JAVA/2013/1020/2216.html

#30


-2  

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!");
    }
}