在Java中是否有任何方法可以生成一个字符串的MD5哈希?
当前回答
你需要java.security. messagdigest。
调用MessageDigest. getinstance ("MD5")来获取您可以使用的MessageDigest的MD5实例。
计算哈希的方法是:
以字节[]的形式提供整个输入,并使用md.digest(字节)在一次操作中计算哈希。 通过调用md.update(bytes)每次向MessageDigest提供一个字节[]块。当您完成添加输入字节时,计算与的散列 md.digest()。
md.digest()返回的字节[]是MD5散列。
其他回答
另一个实现:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
发现了这个:
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;
}
在下面的网站上,我没有功劳,但这是一个有效的解决方案! 对我来说,很多其他的代码都没有正常工作,我最终在哈希中丢失了0。 这一点似乎与PHP相同。 资料来源:http://m2tec.be/blog/2010/02/03/java - md5 -十六进制- 0093年
您可能还想看看apache公用编解码器项目的DigestUtils类,它提供了非常方便的方法来创建MD5或SHA摘要。
使用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();
}
是我做的…似乎还行-我相信有人会指出错误…
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]));
}
}
推荐文章
- 到底是什么导致了堆栈溢出错误?
- 为什么Android工作室说“等待调试器”如果我不调试?
- Java:路径vs文件
- ExecutorService,如何等待所有任务完成
- Maven依赖Servlet 3.0 API?
- 如何在IntelliJ IDEA中添加目录到应用程序运行概要文件中的类路径?
- getter和setter是糟糕的设计吗?相互矛盾的建议
- Android room persistent: AppDatabase_Impl不存在
- Java的String[]在Kotlin中等价于什么?
- Intellij IDEA上的System.out.println()快捷方式
- 使用Spring RestTemplate获取JSON对象列表
- Spring JPA选择特定的列
- URLEncoder不能翻译空格字符
- Java中的super()
- 如何转换JSON字符串映射<字符串,字符串>与杰克逊JSON