在Java中是否有任何方法可以生成一个字符串的MD5哈希?


当前回答

没必要把事情搞得太复杂。 DigestUtils工作得很好,使您在使用md5散列时感到舒适。

DigestUtils.md5Hex(_hash);

or

DigestUtils.md5(_hash);

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

其他回答

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

当使用字符串和加密类时,请确保始终指定您希望字节表示的编码。如果只使用string.getBytes(),它将使用平台默认值。(并非所有平台都使用相同的默认值)

import java.security.*;

..

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

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

如果你有很多数据,看看.update(xxx)方法,它可以被重复调用。然后调用.digest()来获得结果散列。

无论如何,我无意中发现了这一点,因为我想从一个将安装COM组件的程序的自然键合成guid;我希望进行综合,以免管理GUID生命周期。我将使用MD5,然后使用UUID类从中获取一个字符串。(http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439提出了这个问题)。

在任何情况下,java.util.UUID都可以从MD5字节中获得一个漂亮的String。

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

我已经使用php,如下所示

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

你可以参考这个资料来源

我不知道这与阅读这篇文章的人是否相关,但我只是遇到了我想要解决的问题

从给定的URL下载文件和 将其MD5值与已知值进行比较。

我希望只使用JRE类(没有Apache Commons或类似的类)。我在网上快速搜索了一下,并没有看到同时执行这两项任务的示例代码片段,只是分别执行了每项任务。因为这需要读取相同的文件两次,所以我认为有必要编写一些代码来统一这两个任务,在下载文件时实时计算校验和。这是我的结果(如果它不是完美的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)
        );
}

您可能还想看看apache公用编解码器项目的DigestUtils类,它提供了非常方便的方法来创建MD5或SHA摘要。