DemoMain.java 2.4 KB
Newer Older
梦里藍天's avatar
创建  
梦里藍天 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
package com.security;

import java.io.IOException;

import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;
/**
 * 
 * @ClassName: DemoMain 
 * @Description: TODO(国密SM2签名验签/SM3报文摘要) 
 * @date 2019年5月10日
 */
public class DemoMain {
	
	public static void main(String[] arg) {
		String msg = "这是需要发送的数据字符串可以是json也可以是xml";//原始数据
		//1.摘要
		byte[] md = new byte[32];
		SM3Digest sm = new SM3Digest();
		sm.update(msg.getBytes(), 0, msg.getBytes().length);
		sm.doFinal(md, 0);
		String s = new String(Hex.encode(md));
		System.out.println("第一步:SM3摘要:"+s.toUpperCase());
		//2.摘要签名
		// 国密规范测试私钥
		String prik = "128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263";
		String prikS = new String(Base64.encode(Util.hexToByte(prik)));
		System.out.println("prikS: " + prikS);
		System.out.println("");
		// 国密规范测试用户ID
		String userId = "ALICE123@YAHOO.COM";
		System.out.println("ID: " + Util.getHexString(userId.getBytes()));
		System.out.println("");
		System.out.println("签名: ");
		byte[] sign = null; //摘要签名
		try {
			sign = SM2Utils.sign(userId.getBytes(), Base64.decode(prikS.getBytes()), Util.hexToByte(s));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("第二步:摘要签名(sign): " + Util.getHexString(sign));
		System.out.println("");
		
		//此处组装(摘要签名(sign) + 原始数据 也就是 String msg) 接收方收到数据后进行验签sign,成功则msg为合法信息
		
		//4.接收方验签
		//国密规范测试公钥
		String pubk = "040AE4C7798AA0F119471BEE11825BE46202BB79E2A5844495E97C04FF4DF2548A7C0240F88F1CD4E16352A73C17B7F16F07353E53A176D684A9FE0C6BB798E857";
		String pubkS = new String(Base64.encode(Util.hexToByte(pubk)));
		System.out.println("pubkS: " + pubkS);
		System.out.println("");
		
		System.out.println("验签 ");
		boolean vs = false; //验签结果
		try {
			vs = SM2Utils.verifySign(userId.getBytes(), Base64.decode(pubkS.getBytes()), Util.hexToByte(s), sign);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("最后:验签结果: " + vs);
		System.out.println("完");
	}
}