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


当前回答

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

其他回答

你需要java.security. messagdigest。

调用MessageDigest. getinstance ("MD5")来获取您可以使用的MessageDigest的MD5实例。

计算哈希的方法是:

以字节[]的形式提供整个输入,并使用md.digest(字节)在一次操作中计算哈希。 通过调用md.update(bytes)每次向MessageDigest提供一个字节[]块。当您完成添加输入字节时,计算与的散列 md.digest()。

md.digest()返回的字节[]是MD5散列。

你可以试着跟着走。查看详细信息和下载代码: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();
}
}

另一个选择是使用Guava哈希方法:

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

如果你已经在用番石榴,这很方便(如果你没有,你可能应该用)。

使用java.security.MessageDigest库的简单函数

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

对于文件使用这个函数

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

不像PHP,你可以通过调用MD5函数ie MD5 ($text)来对文本进行MD5哈希,在Java中它有点复杂。我通常通过调用一个返回md5哈希文本的函数来实现它。 首先在你的主类中创建一个名为md5hashing的函数,如下所示。

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

现在,在需要时调用该函数,如下所示。

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

在这里,您可以看到hashtext被附加了一个0,以使其与PHP中的md5散列匹配。