Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

1.18. java.security

1.18.1. 列出 Java 支持的數字摘要算法

		
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		
		
		

1.18.2. 計算檔案的 MD5,SHA 等 HASH 值

		
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();

	}

}