在Java中是否有任何方法可以生成一个字符串的MD5哈希?
当前回答
这就是我来这里的目的-一个方便的scala函数,返回MD5哈希字符串:
def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
其他回答
如果你不需要最好的安全性,MD5是完全可以的,如果你正在做一些像检查文件完整性这样的事情,那么安全性就不是一个考虑因素。在这种情况下,您可能希望考虑一些更简单和更快的方法,例如Adler32, Java库也支持它。
另一种实现:Java中的快速MD5实现
String hash = MD5.asHex(MD5.getHash(new File(filename)));
另一个选择是使用Guava哈希方法:
Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();
如果你已经在用番石榴,这很方便(如果你没有,你可能应该用)。
是我做的…似乎还行-我相信有人会指出错误…
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]));
}
}
如果你真的想要返回一个字符串,而不是字节数组,你总是可以这样做:
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;
}
推荐文章
- 泛型类中的静态方法?
- 如何在JPA中持久化类型列表<字符串>的属性?
- 考虑在配置中定义一个'package'类型的bean [Spring-Boot]
- Java注释中的/**和/*
- java8 LocalDate Jackson格式
- Android Studio谷歌JAR文件导致GC开销限制超过错误
- 如何在Intellij生成串行版本UID
- “比较法违反其总合同!”
- 从Java项目生成UML类图
- 正确地从一个<Integer>的列表中移除一个整数
- Java开关语句:需要常量表达式,但它是常量
- Java的assertEquals方法可靠吗?
- 如何在Java中获得系统变量值?
- 比较Java中2个XML文档的最佳方法
- Java SE 8有对或元组吗?