话不多说,代码如下
package com.syl.test_key; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap; /**
* Created by 孙义朗 on 2017/11/24 0024.
*/
@Slf4j
public class KeyUtil {
public static final String KEY_ALGORTHM = "RSA";//
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
public static final String PUBLIC_KEY = "RSAPublicKey";//公钥
public static final String PRIVATE_KEY = "RSAPrivateKey";//私钥 //map对象中存放公私钥(初始化,生成一对公钥和私钥) 1
public static Map<String, Object> initKey() throws Exception {
//获得对象 KeyPairGenerator 参数 RSA 1024个字节
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORTHM);
keyPairGen.initialize(1024);
//通过对象 KeyPairGenerator 获取对象KeyPair
KeyPair keyPair = keyPairGen.generateKeyPair(); //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//公私钥对象存入map中
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
} /**
* 获得公钥 2
*/
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
//获得map中的公钥对象 转为key对象
Key key = (Key) keyMap.get(PUBLIC_KEY);
//编码返回字符串 2.1
return encryptBASE64(key.getEncoded());
} //编码返回字符串 2.1(3.1)
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
} /**
* 获得私钥 3
*/
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
//获得map中的私钥对象 转为key对象
Key key = (Key) keyMap.get(PRIVATE_KEY);
//编码返回字符串 3.1
return encryptBASE64(key.getEncoded());
} /**
* 根据私钥,生成数字签名 4
*/
public static String getSign(TreeMap<String, Object> map, String privateKey) {
try {
log.info("****** privateKey : " + privateKey); //获取待签名的字符串 4.1
String result = getValue(map);
log.info("****** 参与签名的字符串为:[" + result + "]");
//信息加密,生成数字签名 4.2
return KeyUtil.sign(result.getBytes("utf-8"), privateKey);
} catch (Exception e) {
log.info("****** 签名异常", e);
return "";
}
} //获取待签名的字符串 4.1(5.1)
public static String getValue(TreeMap<String, Object> map) throws Exception {
log.info("****** 加签字符串:[" + map.toString() + "]");
map.remove("sign");// 移除上送上来的sign字段
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
sb.append(entry.getValue() == null ? "" : entry.getValue());
}
String result = sb.toString(); return result;
} //用私钥对需要加密的信息加密 4.2
public static String sign(byte[] data, String privateKey) throws Exception {
//解密私钥
byte[] keyBytes = Base64.decodeBase64(privateKey);
//构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
//指定加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
//取私钥匙对象
PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateKey2);
signature.update(data); return Base64.encodeBase64String(signature.sign());
} /**
* 用公钥,校验签名 5
*/
public static boolean vertifySign(TreeMap<String, Object> map, String sign, String publicKey) {
try {
log.info("****** publicKey : " + publicKey); //获取待校验的字符串 5.1
String result = getValue(map);
log.info("****** 参与验签的字符串为:[" + result + "]");
//校验数字签名 5.2
return KeyUtil.verify(result.getBytes("utf-8"), publicKey, sign);
} catch (UnsupportedEncodingException e) {
log.error("****** 校验签名异常", e);
return false;
} catch (Exception e) {
log.error("****** 校验签名异常", e);
return false;
}
} //校验数字签名(校验签名使用) 5.2
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
//解密公钥
byte[] keyBytes = Base64.decodeBase64(publicKey);
//构造X509EncodedKeySpec对象
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
//指定加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
//取公钥匙对象
PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicKey2);
signature.update(data);
//验证签名是否正常
return signature.verify(Base64.decodeBase64(sign));
} //解码返回byte
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
} }
KeyUtil
测试类
package com.syl.test_key; import java.util.Map;
import java.util.TreeMap; /**
* Created by 孙义朗 on 2017/11/24 0024.
*/
public class TestKey {
public static void main(String[] args) throws Exception {
//新建一个需要加签的信息
TreeMap<String, Object> treeMap = new TreeMap();
treeMap.put("name", "syl");
treeMap.put("age", 18); //map对象中存放公私钥
Map<String, Object> keyMap = KeyUtil.initKey(); //获得公钥和私钥
String publicKey = KeyUtil.getPublicKey(keyMap);
String privateKey = KeyUtil.getPrivateKey(keyMap); //获取签名
String sign = KeyUtil.getSign(treeMap, privateKey); //验证签名
boolean flag = KeyUtil.vertifySign(treeMap, sign, publicKey);
if (flag) {
System.out.println("验证成功!");
} else {
System.err.println("验证失败");
}
}
}
TestKey
控制台输出