Base64算法,消息摘要算法-Base64,MD5,SHA,MAC加密

2/10/2017来源:ASP.NET技巧人气:549

参考慕课的加密视频上面的代码:http://www.imooc.com/learn/285

学习security应用与算法如下:

         *   1.Base64算法
	 *   2.消息摘要算法
	 *   3.对称加密算法
	 *   4.非对称加密算法
	 *   5.数字签名算法
	 *   6.数字证书
	 *   7.安全协议

1.创建一个maven项目,可以参考一下百度:http://jingyan.baidu.com/article/ea24bc39b1a8c7da63b33159.html

2.pom.xml文件进行如下配置:

<PRoject xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.samlai</groupId>
	<artifactId>security</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>security</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk16</artifactId>
			<version>1.45</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
		<!-- 不知道为什么引入jdk的base64Decoder,所以要添加jdk中jre的rt.jar,进行pom引入本地文件 -->
		<dependency>
			<groupId>com.samlai</groupId>
			<artifactId>my-tools</artifactId>
			<version>2.5.0</version>
			<type>jar</type>
			<scope>system</scope>
			<systemPath>${basedir}/lib/rt.jar</systemPath>
		</dependency>
	</dependencies>
</project>

4.直接在project写对应的Base64的class类:

package com.samlai.security;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
//Base64算法
//应用:证书,密钥,email
public class Base64Study {

	/**
	 * 加密应用:
	 * 	 1.Base64算法
	 *   2.消息摘要算法
	 *   3.对称加密算法
	 *   4.非对称加密算法
	 *   5.数字签名算法
	 *   6.数字证书
	 *   7.安全协议
	 * 
	 * 3种方式进行加密解密处理:
	 *  	1.原生的JDK方式
	 *  	2.Bouncy Castle
	 *  		-两种支持方案:A.配置 2.调用
	 *      3.Commons Codec
	 *      	-Apache
	 *      	-Base64,二进制,十六进制,字符集编码
	 *      	-Url编码/解码
	 */
	
	private static String STR="one type of security:Base64";
	
	public static void main(String[] args) {
		//JDK方式实现
		jdkDoBase64();
		//CC实现的方式
		commonsCodecBase64();
		//BC实现的方式
		bouncyCastleBase64();
	}
	
	
	//JDK方式实现
	public static void jdkDoBase64(){
		try {
			BASE64Encoder encoder=new BASE64Encoder();
			String encode=encoder.encode(STR.getBytes());
			System.out.println("jdk encode:  "+encode);
			BASE64Decoder decoder=new BASE64Decoder();
			System.out.println("jdk decode:  "+new String(decoder.decodeBuffer(encode)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//Commons Codec方式实现
	public static void commonsCodecBase64(){
		byte[] encodeBytes=Base64.encodeBase64(STR.getBytes());
		System.out.println("cc encode:  "+new String(encodeBytes));
		byte[] decodeBytes=Base64.decodeBase64(encodeBytes);
		System.out.println("cc decode:  "+new String(decodeBytes));
	}
	
	//Bouncy Castle方式实现
	public static void bouncyCastleBase64(){
		byte[] encodeBytes=org.bouncycastle.util.encoders.Base64.encode(STR.getBytes());
		System.out.println("bc encode: "+new String(encodeBytes));
		byte[] decodeBytes=org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
		System.out.println("bc decode: "+new String(decodeBytes));
	}
	
	
	
	
	
}


运行的结果是:

jdk encode:  b25lIHR5cGUgb2Ygc2VjdXJpdHk6QmFzZTY0
jdk decode:  one type of security:Base64
cc encode:  b25lIHR5cGUgb2Ygc2VjdXJpdHk6QmFzZTY0
cc decode:  one type of security:Base64
bc encode: b25lIHR5cGUgb2Ygc2VjdXJpdHk6QmFzZTY0
bc decode: one type of security:Base64

5.新建消息摘要算法-MD,以Jdk,bc,cc方式来进行实现

package com.samlai.security;

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

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD2Digest;
import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.crypto.digests.md5Digest;

//消息摘要算法
public class MessageDigestStudy {
	/**
	 * MD(Message Digest) 
	 * 		MD家族(128位摘要信息) -MD2,MD4 
	 * 	类型: 
	 * 		算法     长度         实现方
	 * 		MD2-128位-JDK
	 * 		MD4-128位-Boundcy Castle 
	 * 		MD5-128位-JDK
	 * 
	 * SHA(Secure Hash Algorithm) MAC(Message Authentication Code) 验证数据的完整性
	 * 数字签名核心算法
	 */
	private static String STR = "one type of security:MD-X";

	public static void main(String[] args) {
		jdkMd5();
		jdkMd2();
		bcMd4();
		bcMd2();
		bcMd5();
		ccMd5();
		ccMd2();
	}

	// jdkMd5
	public static void jdkMd5() {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md.digest(STR.getBytes());
			// 借助cc的算法来进行md5的加密出对应的字符串
			System.out.println("JDK MD5: " + Hex.encodeHexString(md5Bytes));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	// jdkMd2
	public static void jdkMd2() {
		try {
			MessageDigest md = MessageDigest.getInstance("MD2");
			byte[] md5Bytes = md.digest(STR.getBytes());
			// 借助cc的算法来进行md2的加密出对应的字符串
			System.out.println("JDK MD2: " + Hex.encodeHexString(md5Bytes));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	// bcMd4
	public static void bcMd4() {
		Digest digest = new MD4Digest();
		digest.update(STR.getBytes(), 0, STR.getBytes().length);
		byte[] md4Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md4Bytes, 0);
		System.out.println("bc Md4: " + Hex.encodeHexString(md4Bytes));
	}

	// bcMd2
	public static void bcMd2() {
		Digest digest = new MD2Digest();
		digest.update(STR.getBytes(), 0, STR.getBytes().length);
		byte[] md4Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md4Bytes, 0);
		System.out.println("bc Md2: " + Hex.encodeHexString(md4Bytes));
	}

	// bcMd5
	public static void bcMd5() {
		Digest digest = new MD5Digest();
		digest.update(STR.getBytes(), 0, STR.getBytes().length);
		byte[] md4Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md4Bytes, 0);
		System.out.println("bc Md5: " + Hex.encodeHexString(md4Bytes));
	}

	// ccMD5
	public static void ccMd5() {
		System.out.println("CC MD5: " + DigestUtils.md5Hex(STR.getBytes()));
	}

	// ccMD2
	public static void ccMd2() {
		System.out.println("CC MD2: " + DigestUtils.md2Hex(STR.getBytes()));
	}

}


运行的结果如下:

JDK MD5: 124a5c93d2b8d49e96f3e62aa758af78
JDK MD2: 5f35106ba9b40d343bd33ee777e15bda
bc Md4: 2182747909e25a336d8928bd4c5b7f31
bc Md2: 5f35106ba9b40d343bd33ee777e15bda
bc Md5: 124a5c93d2b8d49e96f3e62aa758af78
CC MD5: 124a5c93d2b8d49e96f3e62aa758af78
CC MD2: 5f35106ba9b40d343bd33ee777e15bda

6.新建消息摘要算法-SHA,以Jdk,bc,cc方式来进行实现:

package com.samlai.security;

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

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;

public class SHAMessageDigestStudy {
	/**
	 * 消息摘要算法--SHA
	 * 	  安全散列算法
	 * 	SHA-1,SHA-2(SHA-224,SHA-256,SHA-384,SHA-512)
	 * 	算法       	摘要长度         实现方
	 * 	SHA-1   160     JDK
	 *  SHA-224 224     Bouncy Castle
	 *  SHA-256 256     JDK
	 *  SHA-384 384     JDK
	 *  SHA-512 512     JDK
	 */
	private static String STR = "one type of security:SH-X";
	
	public static void main(String[] args) {
		jdkSHA1();
		bcSHA1();
		bcSHA224();
		ccSHA1();
	}
	
	//Jdk的SHA1算法
	public static void jdkSHA1() {
		try {
			MessageDigest md=MessageDigest.getInstance("SHA");
			md.update(STR.getBytes());
			System.out.println("jdk sha-1:"+Hex.encodeHexString(md.digest()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	
	//bc的SHA1算法
	public static void bcSHA1() {
		 Digest digest=new SHA1Digest();
		 digest.update(STR.getBytes(),0,STR.getBytes().length);
		 byte[] sha1Bytes=new byte[digest.getDigestSize()];
		 digest.doFinal(sha1Bytes, 0);
		 System.out.println("bc SHA-1:  "+Hex.encodeHexString(sha1Bytes));
	}
	
	
	//bc的SHA224算法
	public static void bcSHA224() {
		Digest digest=new SHA224Digest();
		digest.update(STR.getBytes(),0,STR.getBytes().length);
		byte[] sha1Bytes=new byte[digest.getDigestSize()];
		digest.doFinal(sha1Bytes, 0);
		System.out.println("bc SHA-224:  "+Hex.encodeHexString(sha1Bytes));
	}
	
	//cc的SHA1算法
	public static void ccSHA1(){
		System.out.println("cc SHA1 1: "+DigestUtils.sha1Hex(STR.getBytes()));
		System.out.println("cc SHA1 2: "+DigestUtils.sha1Hex(STR));
	}
	
	

}

运行的结果如下:

jdk sha-1:6f1f5458f87160e40de37b632c9f202521c38069
bc SHA-1:  6f1f5458f87160e40de37b632c9f202521c38069
bc SHA-224:  8809029976d18ef9564042591b9e02401d7fec17cece03f43b6e886a
cc SHA1 1: 6f1f5458f87160e40de37b632c9f202521c38069
cc SHA1 2: 6f1f5458f87160e40de37b632c9f202521c38069

7.新建消息摘要算法-MAC,以Jdk,bc实现:

package com.samlai.security;

import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.omg.IOP.Encoding;


//消息摘要算法-MAC
public class MACMessageDigest {
	/**
	 * MAC:Message Authentication Code
	 *     含有密钥的散列函数算法
	 *     融合MD,SHA
	 *     	 -MD系列:HMACMD2,HmacMd4,HmacMd5
	 *       -SHA系列:HmacSHA1,HmacSHA224,HmacSHA256,HmacSHA384,HmacSHA512
	 *       应用如:SecureCRT
	 */
	private static String STR = "one type of security:MAC";
	public static void main(String[] args) {
		jdkHmacMd5();
		bcHmacMd5();
	}
	
	//jdk hmac
	public static void jdkHmacMd5(){
		try {
			//初始化KeyGenerator
			KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacMD5");
			//产生密钥
			SecretKey secretKey=keyGenerator.generateKey();
			//获取密钥
//			byte[] key=secretKey.getEncoded();
			byte[] key=Hex.decodeHex(new char[]{'a','a','a','a','a','a','a','a'});
			
			//还原密钥
			SecretKey restoreSecretKey=new SecretKeySpec(key, "HmacMD5");
			//实例化MAC
			Mac mac=Mac.getInstance(restoreSecretKey.getAlgorithm());
			//初始化Mac
			mac.init(restoreSecretKey);
			//执行摘要
			byte[] hmacMD5Bytes=mac.doFinal(STR.getBytes());
			System.out.println("jdk HmacMD5:"+Hex.encodeHexString(hmacMD5Bytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//bc hmac
	public static void bcHmacMd5(){
		HMac hMac=new HMac(new MD5Digest());
		hMac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaa")));
		hMac.update(STR.getBytes(),0,STR.getBytes().length);
		//执行摘要
		byte[] hmacMD5bytes=new byte[hMac.getMacSize()];
		hMac.doFinal(hmacMD5bytes, 0);
		System.out.println("bc HmacMD5:"+Hex.encodeHexString(hmacMD5bytes));
	}
	
	
}