在Java中是否有任何方法可以生成一个字符串的MD5哈希?
当前回答
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));
}
}
Codingkit上有一篇关于这个的文章。查看:http://codingkit.com/a/JAVA/2013/1020/2216.html
其他回答
另一个选择是使用Guava哈希方法:
Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();
如果你已经在用番石榴,这很方便(如果你没有,你可能应该用)。
没必要把事情搞得太复杂。 DigestUtils工作得很好,使您在使用md5散列时感到舒适。
DigestUtils.md5Hex(_hash);
or
DigestUtils.md5(_hash);
您可以使用任何其他加密方法,如sha或md。
使用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();
}
我不知道这与阅读这篇文章的人是否相关,但我只是遇到了我想要解决的问题
从给定的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)
);
}
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()来获得结果散列。
推荐文章
- 如何使一个Java通用方法静态?
- for-each循环和迭代器,哪个更有效?
- 泛型类中的静态方法?
- 如何在JPA中持久化类型列表<字符串>的属性?
- 考虑在配置中定义一个'package'类型的bean [Spring-Boot]
- Java注释中的/**和/*
- java8 LocalDate Jackson格式
- Android Studio谷歌JAR文件导致GC开销限制超过错误
- 如何在Intellij生成串行版本UID
- “比较法违反其总合同!”
- 从Java项目生成UML类图
- 正确地从一个<Integer>的列表中移除一个整数
- Java开关语句:需要常量表达式,但它是常量
- Java的assertEquals方法可靠吗?
- 如何在Java中获得系统变量值?