用 java.security.MessageDigest 生成 md5,sha1,sha256,sha512 到文本文件
package generate_hash_sum_check_file;
import java.awt.*;
import java.io.*;
import java.security.MessageDigest;
import java.util.*;
public class Main {
public static void main(String...arguments)throws Exception{
FileDialog fileDialog = new FileDialog((Frame)null, "MD5 , SHA1 , SHA256 , SHA512", FileDialog.LOAD);
fileDialog.setVisible(true);
var directory = fileDialog.getDirectory();
var fileName = fileDialog.getFile();
var src = directory + "/" + fileName;
System.out.println(src);
File srcFile = new File(src);
var keyAl = Arrays.asList("md5", "SHA1", "sha256", "Sha512");
var digestBarRltMapping = new LinkedHashMap<String, byte[]>();
var digestUcHexRltMapping = new LinkedHashMap<String, String>();
var digestLcHexRltMapping = new LinkedHashMap<String, String>();
for(String k:keyAl){
var messageDigest = MessageDigest.getInstance(k);
byte[] bf = new byte[12345];
int readLength = 0;
var srcIsm = new FileInputStream(srcFile);
while((readLength = srcIsm.read(bf))>0) {
messageDigest.update(bf, 0, readLength);
}
srcIsm.close();
digestBarRltMapping.put(k, messageDigest.digest());
digestLcHexRltMapping.put(k, hexLowerCaseFromByteArray(digestBarRltMapping.get(k)));
digestUcHexRltMapping.put(k, hexUpperCaseFromByteArray(digestBarRltMapping.get(k)));
};
File hashTxt = new File(directory+"Hash - "+fileName+".txt");
FileOutputStream hashTxtFosm = new FileOutputStream(hashTxt);
hashTxtFosm.write(("文件名: "+fileName+"\n").getBytes());
hashTxtFosm.write((digestLcHexRltMapping.toString()+"\n").getBytes());
hashTxtFosm.write((digestUcHexRltMapping.toString()+"\n").getBytes());
hashTxtFosm.write(("\n\n\n\n").getBytes());
for(var k:keyAl) {
hashTxtFosm.write(("\n\n"+k+":\n").getBytes());
hashTxtFosm.write(("\n"+k+" 的字节数组内容 = "+ Arrays.toString(digestBarRltMapping.get(k)) + "\n").getBytes());
hashTxtFosm.write(("\n"+k+" 的小写十六进制 = "+ (digestLcHexRltMapping.get(k)) + "\n").getBytes());
hashTxtFosm.write(("\n"+k+" 的大写十六进制 = "+ (digestUcHexRltMapping.get(k)) + "\n").getBytes());
hashTxtFosm.write(("\n\n").getBytes());
}
hashTxtFosm.write(("\n\n\n\n").getBytes());
hashTxtFosm.close();
System.out.println(digestBarRltMapping);
System.out.println(digestLcHexRltMapping);
System.out.println(digestUcHexRltMapping);
System.exit(0);
}
public static String hexLowerCaseFromByteArray(byte[] byteArray) {
if(byteArray==null)return null;
String simple = "0123456789abcdef";
StringBuilder sb = new StringBuilder(byteArray.length*2);
for(byte b : byteArray) {
sb.append(simple.charAt(Byte.toUnsignedInt(b)/16)).append(simple.charAt(Byte.toUnsignedInt(b)%16));
}
return sb.toString();
}
public static String hexUpperCaseFromByteArray(byte[] byteArray) {
if(byteArray==null)return null;
String simple = "0123456789ABCDEF";
StringBuilder sb = new StringBuilder(byteArray.length*2);
for(byte b : byteArray) {
sb.append(simple.charAt(Byte.toUnsignedInt(b)/16)).append(simple.charAt(Byte.toUnsignedInt(b)%16));
}
return sb.toString();
}
}
使用 java.security.MessageDigest 生成 MD5、SHA-1、SHA-256 和 SHA-512 哈希值,并将这些哈希值写入文本文件,你可以按照以下步骤进行。以下是一个完整的 Java 程序示例:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashGenerator {
// Method to generate hash of a given input string using a specified algorithm
private static String generateHash(String algorithm, String input) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
// Convert byte array to hex string
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
// Method to write the hashes to a text file
private static void writeHashesToFile(String input, String filePath) {
String md5 = generateHash("MD5", input);
String sha1 = generateHash("SHA-1", input);
String sha256 = generateHash("SHA-256", input);
String sha512 = generateHash("SHA-512", input);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("MD5: " + md5 + "\n");
writer.write("SHA-1: " + sha1 + "\n");
writer.write("SHA-256: " + sha256 + "\n");
writer.write("SHA-512: " + sha512 + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String input = "Hello, World!"; // The input string to hash
String filePath = "hashes.txt"; // The file path to write the hashes
writeHashesToFile(input, filePath);
System.out.println("Hashes have been written to " + filePath);
}
}
说明:
-
生成哈希值:
generateHash方法使用指定的哈希算法(如 MD5、SHA-1、SHA-256、SHA-512)生成输入字符串的哈希值。- 生成的哈希值以十六进制字符串形式返回。
-
写入文件:
writeHashesToFile方法调用generateHash方法生成不同算法的哈希值,并将这些哈希值写入指定的文本文件。- 使用
BufferedWriter和FileWriter类来写入文件。
-
主方法:
main方法定义输入字符串和文件路径,并调用writeHashesToFile方法。- 最后,打印一条消息,表示哈希值已写入文件。
运行程序:
- 将上述代码保存为一个 Java 文件(例如
HashGenerator.java)。 - 使用 Java 编译器编译代码:
javac HashGenerator.java - 运行编译后的 Java 程序:
java HashGenerator
程序运行后,将在当前目录下生成一个名为 hashes.txt 的文件,文件内容包含输入字符串的 MD5、SHA-1、SHA-256 和 SHA-512 哈希值。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class DigestGenerator {
public static void main(String[] args) {
String text = "Hello, World!";
String[] algorithms = {"MD5", "SHA-1", "SHA-256", "SHA-512"};
try (BufferedWriter writer = new BufferedWriter(new FileWriter("digests.txt"))) {
for (String algorithm : algorithms) {
String digest = generateDigest(text, algorithm);
writer.write(algorithm + ": " + digest);
writer.newLine();
}
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
private static String generateDigest(String text, String algorithm) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] encodedhash = digest.digest(text.getBytes());
return bytesToHex(encodedhash);
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if(hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}