Java MessageDigest????????MD5?SHA???????????,????????:
-
????:????????????????,??????????,????????????1MB??,?????????????
-
?????:????????,??????????????,????
BufferedInputStream
?????,???????FileInputStream
? -
?????:???????????,????
MessageDigest.update()
??????????????????????????????????? -
??????:????????????,????
MessageDigest.digest()
????????????,??????????
??????????????:
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashLargeData { public static void main(String[] args) throws NoSuchAlgorithmException, IOException { String algorithm = "MD5"; // ? "SHA-1", "SHA-256" ? int bufferSize = 1024 * 1024; // 1MB ????? File file = new File("large_data.txt"); MessageDigest messageDigest = MessageDigest.getInstance(algorithm); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { messageDigest.update(buffer, 0, bytesRead); } } byte[] hashBytes = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : hashBytes) { sb.append(String.format("x", b)); } System.out.println("???: " + sb.toString()); } }
?????,???????1MB?????????,?????????????????????,????????MD5??????????????????????