知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
package cn.netkiller.security; import java.security.Security; import java.util.Set; public class ListMessageDigest { public static void main(String[] args) { // List of available MessageDigest Algorithms Set<String> messageDigest = Security.getAlgorithms("MessageDigest"); messageDigest.forEach(x -> System.out.println(x)); } }
運行結果
SHA3-512 SHA-384 SHA SHA3-384 SHA-224 SHA-512/256 SHA-256 MD2 SHA-512/224 SHA3-256 SHA-512 MD5 SHA3-224
package cn.netkiller.security; import java.io.FileInputStream; import java.io.IOException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class sha1sum { public sha1sum() { // TODO Auto-generated constructor stub } public static void main(String[] args) throws NoSuchAlgorithmException, IOException { String hex = checksum("/etc/hosts"); System.out.println(hex); } private static String checksum(String filepath) throws IOException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); // SHA, MD2, MD5, SHA-256, SHA-384... // file hashing with DigestInputStream try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) { while (dis.read() != -1) ; // empty loop to clear the data md = dis.getMessageDigest(); } // bytes to hex StringBuilder result = new StringBuilder(); for (byte b : md.digest()) { result.append(String.format("%02x", b)); } return result.toString(); } }