Java MD5ハッシュの例
この記事では、MD5 algorithmを使用して文字列をハッシュし、ファイルのチェックサムを生成する方法を示します。
1. メッセージダイジェスト
1.1 MD5 to Hash a string.
PasswordMD5.java
package com.example.hashing;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PasswordMD5 {
public static void main(String[] args) throws NoSuchAlgorithmException {
String password = "123456";
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
System.out.println(sb.toString());
}
}
出力
e10adc3949ba59abbe56e057f20f883e
1.2 File checksum.
d:\server.log
123456
FileCheckSum.java
package com.example.hashing;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileCheckSum {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashInBytes = checksum("d:\\server.log", md);
System.out.println(bytesToHex(hashInBytes));
}
private static byte[] checksum(String filepath, MessageDigest md) throws IOException {
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
return md.digest();
}
private static String bytesToHex(byte[] hashInBytes) {
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
出力
e10adc3949ba59abbe56e057f20f883e
2. Apache Commons Codec
または、このApache Commons Codecsライブラリをハッシュ用に試してください。
pom.xml
commons-codec commons-codec 1.11
2.1 Hash a String.
PasswordMD5.java
package com.example.hashing;
import org.apache.commons.codec.digest.DigestUtils;
public class PasswordMD5 {
public static void main(String[] args) {
String password = "123456";
String result = DigestUtils.md5Hex(password);
System.out.println(result);
}
}
出力
e10adc3949ba59abbe56e057f20f883e
2.2 File checksum.
FileCheckSum.java
package com.example.hashing;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileInputStream;
import java.io.IOException;
public class FileCheckSum {
public static void main(String[] args) throws IOException {
String result = DigestUtils.md5Hex(new FileInputStream("d:\\server.log"));
System.out.println(result);
}
}
出力
e10adc3949ba59abbe56e057f20f883e