Java SHAハッシュの例
Javaでは、MessageDigestクラスを使用してSHA hashingを実行できます。 この記事では、SHA-256アルゴリズムを使用して文字列をハッシュし、ファイルのチェックサムを生成する方法を示します。
1. メッセージダイジェスト
1.1 Hash a string.
PasswordSha256.java
package com.example.hashing;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PasswordSha256 {
public static void main(String[] args) throws NoSuchAlgorithmException {
String password = "123456";
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));
// bytes to hex
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
System.out.println(sb.toString());
}
}
出力
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
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("SHA-256");
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();
}
}
出力
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
2. Apache Commons Codec
または、このApache Commons Codecsライブラリをハッシュ用に試してください。
pom.xml
commons-codec commons-codec 1.11
2.1 Hash a String.
PasswordSha256.java
package com.example.hashing;
import org.apache.commons.codec.digest.DigestUtils;
public class PasswordSha256 {
public static void main(String[] args) {
String password = "123456";
String result = DigestUtils.sha256Hex(password);
System.out.println(result);
}
}
出力
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
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.sha256Hex(new FileInputStream("d:\\server.log"));
System.out.println(result);
}
}
出力
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92