Java MessageDigest ??????????????????????,?????? MessageDigest ???????? MD5 ???:
- ??,????????:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.nio.charset.StandardCharsets; import java.util.Arrays;
- ??????,?????????????,?????? MD5 ???:
public static String calculateMD5(String filePath) { try { // ???? MessageDigest ??,????? MD5 MessageDigest md = MessageDigest.getInstance("MD5"); // ?? FileInputStream ?????? FileInputStream fis = new FileInputStream(new File(filePath)); byte[] buffer = new byte[1024]; int bytesRead; // ??????????? MessageDigest ?? while ((bytesRead = fis.read(buffer)) != -1) { md.update(buffer, 0, bytesRead); } // ?? FileInputStream fis.close(); // ?? MD5 ???????? byte[] mdBytes = md.digest(); // ??????????????? StringBuilder sb = new StringBuilder(); for (byte b : mdBytes) { sb.append(String.format("x", b)); } return sb.toString(); } catch (IOException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
- ???????
calculateMD5
??,??????,?????:
public static void main(String[] args) { String filePath = "path/to/your/file.txt"; String md5Hash = calculateMD5(filePath); System.out.println("MD5 hash of the file: " + md5Hash); }
??????????????,?????????????? MD5 ????????????????????????,???? SHA-256 ?? "MD5"?