package com.tu.Security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * <pre>
 * 消息摘要算法: SHA
 * 
 *  安全散列算法
 * 	固定长度摘要信息
 * 	SHA-1  SHA-2(SHA-224,SHA-256,SHA-384,SHA-512)
 * 
 * 算法:
 * SHA-1    实现方:JDK
 * SHA-224  实现方:BC
 * SHA-256  实现方:JDK
 * SHA-384  实现方:JDK
 * SHA-512  实现方:JDK
 * 
 * </pre>
 * 
 * @author comtu
 */
public class SHA {
	public static void main(String[] args) {
		jdkSHA1("comtu");
		bcSHA1("comtu");
		bcSHA224("comtu");
		jdkSHA224_2("comtu");
		ccSHA1("comtu");
	}

	public static void jdkSHA1(String msg) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA");// SHA1
			md.update(msg.getBytes());
			System.out.println("jdk SHA-1:" + Hex.encodeHexString(md.digest()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public static void bcSHA1(String msg) {
		Digest digest = new SHA1Digest();
		digest.update(msg.getBytes(), 0, msg.getBytes().length);
		byte[] sha1Byte = new byte[digest.getDigestSize()];
		digest.doFinal(sha1Byte, 0);
		System.out.println("bc SHA-1:" + org.bouncycastle.util.encoders.Hex.toHexString(sha1Byte));
	}

	public static void bcSHA224(String msg) {
		Digest digest = new SHA224Digest();
		digest.update(msg.getBytes(), 0, msg.getBytes().length);
		byte[] sha224Byte = new byte[digest.getDigestSize()];
		digest.doFinal(sha224Byte, 0);
		System.out.println("bc SHA-224:" + org.bouncycastle.util.encoders.Hex.toHexString(sha224Byte));
	}

	public static void jdkSHA224_2(String msg) {
		try {
			Security.addProvider(new BouncyCastleProvider());// 设置
			MessageDigest md = MessageDigest.getInstance("SHA224");// SHA224
			md.update(msg.getBytes());
			System.out.println("jdk addProvider ->SHA-224:" + Hex.encodeHexString(md.digest()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public static void ccSHA1(String msg) {
		System.out.println("cc sha1:" + DigestUtils.sha1Hex(msg.getBytes()));
		System.out.println("cc sha512:" + DigestUtils.sha512Hex((msg.getBytes())));
	}

}
