1.RSA工具代码
代码语言:javascript复制package com.unwulian.common.sign;
/*
--------------------------------------------**********--------------------------------------------
该算法于1977年由美国麻省理工学院MIT(Massachusetts Institute of Technology)的Ronal Rivest,Adi Shamir和Len Adleman三位年轻教授提出,并以三人的姓氏Rivest,Shamir和Adlernan命名为RSA算法,是一个支持变长密钥的公共密钥算法,需要加密的文件快的长度也是可变的!
所谓RSA加密算法,是世界上第一个非对称加密算法,也是数论的第一个实际应用。它的算法如下:
1.找两个非常大的质数p和q(通常p和q都有155十进制位或都有512十进制位)并计算n=pq,k=(p-1)(q-1)。
2.将明文编码成整数M,保证M不小于0但是小于n。
3.任取一个整数e,保证e和k互质,而且e不小于0但是小于k。加密钥匙(称作公钥)是(e, n)。
4.找到一个整数d,使得ed除以k的余数是1(只要e和n满足上面条件,d肯定存在)。解密钥匙(称作密钥)是(d, n)。
加密过程: 加密后的编码C等于M的e次方除以n所得的余数。
解密过程: 解密后的编码N等于C的d次方除以n所得的余数。
只要e、d和n满足上面给定的条件。M等于N。
--------------------------------------------**********--------------------------------------------
*/
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import com.github.structlog4j.ILogger;
import com.github.structlog4j.SLoggerFactory;
public class RSA {
private static final ILogger log = SLoggerFactory.getLogger(RSA.class);
/** 指定key的大小 */
private static int KEYSIZE = 2048;
/**
* 生成密钥对
*/
public static Map<String, String> generateKeyPair() throws Exception {
/** RSA算法要求有一个可信任的随机数源 */
SecureRandom sr = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
kpg.initialize(KEYSIZE, sr);
/** 生成密匙对 */
KeyPair kp = kpg.generateKeyPair();
/** 得到公钥 */
Key publicKey = kp.getPublic();
byte[] publicKeyBytes = publicKey.getEncoded();
String pub = new String(Base64Sign.encodeBase64(publicKeyBytes),
ConfigureEncryptAndDecrypt.CHAR_ENCODING);
/** 得到私钥 */
Key privateKey = kp.getPrivate();
byte[] privateKeyBytes = privateKey.getEncoded();
String pri = new String(Base64Sign.encodeBase64(privateKeyBytes),
ConfigureEncryptAndDecrypt.CHAR_ENCODING);
Map<String, String> map = new HashMap<String, String>();
map.put("publicKey", pub);
map.put("privateKey", pri);
RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
BigInteger bint = rsp.getModulus();
byte[] b = bint.toByteArray();
byte[] deBase64Value = Base64Sign.encodeBase64(b);
String retValue = new String(deBase64Value);
map.put("modulus", retValue);
return map;
}
/**
* 加密方法 source: 源数据
*/
public static String encrypt(String source, String publicKey)
throws Exception {
Key key = getPublicKey(publicKey);
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] b = source.getBytes();
/** 执行加密操作 */
byte[] b1 = cipher.doFinal(b);
return new String(Base64Sign.encodeBase64(b1),
ConfigureEncryptAndDecrypt.CHAR_ENCODING);
}
/**
* 解密算法 cryptograph:密文
*/
public static String decrypt(String cryptograph, String privateKey)
throws Exception {
Key key = getPrivateKey(privateKey);
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] b1 = Base64Sign.decodeBase64(cryptograph.getBytes());
/** 执行解密操作 */
byte[] b = cipher.doFinal(b1);
return new String(b);
}
/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
Base64Sign.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 得到私钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
Base64Sign.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static String sign(String content, String privateKey) {
String charset = ConfigureEncryptAndDecrypt.CHAR_ENCODING;
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
Base64Sign.decodeBase64(privateKey.getBytes()));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return new String(Base64Sign.encodeBase64(signed));
} catch (Exception e) {
}
return null;
}
public static boolean checkSign(String content, String sign, String publicKey)
{
try
{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64Sign.decode2(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance("SHA256WithRSA");
signature.initVerify(pubKey);
signature.update( content.getBytes("utf-8") );
boolean bverify = signature.verify( Base64Sign.decode2(sign) );
return bverify;
}
catch (Exception e)
{
log.error("RSA-checkSign Exception", e);
}
return false;
}
public static void main(String[] args) throws Exception {
for(String key : generateKeyPair().keySet()) {
System.out.println(key ":");
System.out.println(generateKeyPair().get(key));
}
}
}
2.工具类测试
代码语言:javascript复制package com.unwulian.chitudata;
import com.unwulian.chitudata.dto.ChiTuDataParam;
import com.unwulian.common.api.RequestBaseParam;
import com.unwulian.common.sign.RSA;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;
/**
* 测试sign
*
* @author shiye
* @create 2020-06-09 10:04
*/
public class CheckSign {
//私匙
private static String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwzHQbfvdEjADZgXmS4wu1x17N0 vZv41tPpSSmN6Yp7NlU3pRwvV2mjsCtw10/k45BBAhX2k5vojC/9k2zTLkudCfhaJcpCeADTGmUzAEvazagZu2ykppBnALNFv3DP4RPbbIj76RjTUgw8UCphvs0nx7zcY6F/7EmcNYKrARkzfFmKGDPOs cI5sb6sjUf87nRMRdRuCCLf4e3A3y 2hM1TJ8a2PAqT5cHHXlpeMW0fAzVFXapWeqHymCZjPAii9m4TV5T/l8892ID3H3Ik3MTtdxXhcUaguKYTcskBxVXRJ2pzKJ6zCT678O0vrBd4RKT227o5ajSsauXJe4Q3lAgMBAAECggEAf9MicyrF7fpnNtrkoi2jrsa5pYj98Y4L25suYhtCfQ5qpuzG ExDmn CAMGGajrfJVvpqadI9eXrDUlbq8KKdFJgIqXEsMRChtODPSTSB t3CPhCM9NoHyz3XzJ491Kecqqy96jt GAmtEy2qOaeNAgu1nf9RM1KdqxRTvJ2IA2j1sh5b1VD8FQ9Dev9ec8vjmE Qh2RGFVj8iZU7s8zy1WKUKWnZ/0F2FMVisnchB4u04jm2cjBYQWx2M/I4cZ wXv5L6Fqje/ka9p/m1PbIal4BET6tCeSG5wjhPCY7j7ThcPRMwdh98PDpwikUBFb5E9CDCiaVmaujPVIUPM9YQKBgQDWDpCQanAbVb3H7IDE 8m5ouDnpiLG7K1aJHLJgtq6V7ePUL6fqi/VruGXQrr0hR2YmGFODtgaQ5ld03mGzWalSRGpeDrbOOYFAHCaLLQsGpLj0tVNJo3caS6ujnSZRWptf3sJRFHXRZ7T/ekWcGNN93SlAK0PLON NRSyCNfVTQKBgQDTcPSrbEexCMYREAqWDco1 WAsSYGsgOCzQ9I9RVCI2RZtisqCmewiKwRX69nzE3VRI VXTGZFH6//7pxQj M/rs8YZzsNPwuguB0c D6 tdJrzfhyLMHEvU0YAiiB2ZjiRnv1D17pz8Ew8ofZ62 hjv/AsLWGNRYLbRIR2Lnu QKBgQCkXxjJnMIra2LJI6YaHVLhNt7HYz7vTA0t3DE85ju5vePZrGJEzvXee2UFtxtC6vk4FUMbIrD1MhWSA/Mc/Zslrv9eCFIBxyZyjszoxw0vlNRZF6vti36B008igYetrq00GiFLk2fZC8AT/7U It1OoIe0sNkzfv/OCUq0D7BVPQKBgAjAv1AtXlZkz5Y7PMTzczCCz0lmDZkviJ3DK/vfV7MikXwdZ766Un0jnL1rBQ27 3pNaxwPDJjF9Ao7PXtUSYsEWIxhEZ 9wWR42rOtTyOj8T8HOsa3NZpIX92jkTu2305WrqD5buts70lwcNFDns5oVgwLBKi2n9//NuVIPII5AoGBAKEsrlTYINNbfLZf6Jan6omCrr1ZRuy3k///9iA6FezGOEMmB94T7Yv6rjHORe929q0 rU p6vjWplOjGTayG1LXdm96pxcqY9uB09darV4NhunP FZ09uOj6YNyTBP2DDt9FTAkUg 9no6tXEnDav0aVQov4rHW5cvL55BYtIKa";
//公匙
private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMx0G373RIwA2YF5kuMLtcdezdPr2b NbT6UkpjemKezZVN6UcL1dpo7ArcNdP5OOQQQIV9pOb6Iwv/ZNs0y5LnQn4WiXKQngA0xplMwBL2s2oGbtspKaQZwCzRb9wz ET22yI kY01IMPFAqYb7NJ8e83GOhf xJnDWCqwEZM3xZihgzzrPnCObG rI1H/O50TEXUbggi3 HtwN8vtoTNUyfGtjwKk XBx15aXjFtHwM1RV2qVnqh8pgmYzwIovZuE1eU/5fPPdiA9x9yJNzE7XcV4XFGoLimE3LJAcVV0Sdqcyieswk u/DtL6wXeESk9tu6OWo0rGrlyXuEN5QIDAQAB";
public static void main(String[] args) throws Exception {
// Map<String, String> keyPair = RSA.generateKeyPair();
// //私匙
// String privateKey = keyPair.get("privateKey");
// //公匙
// String publicKey = keyPair.get("publicKey");
// System.out.println("私匙privateKey:" privateKey);
// System.out.println("公匙publicKey:" publicKey);
StringBuffer data = new StringBuffer();
RequestBaseParam<ChiTuDataParam> param = new RequestBaseParam<>();
param.setTimestamp("1111122222333");
ChiTuDataParam chiTuDataParam = new ChiTuDataParam();
chiTuDataParam.setAction(1);
chiTuDataParam.setCity_ids(new String[]{"c111", "c222"});
chiTuDataParam.setCo_ids(new String[]{"co1111", "co222"});
chiTuDataParam.setBuilding_ids(new String[]{"b1111", "b2222"});
data = chiTuDataParam.tranceToStr();
data = data.append("timestamp").append(param.getTimestamp());
//使用私匙加密 得到签名
String sign = RSA.sign(data.toString(), privateKey);
System.out.println("sign:" sign);
//使用公匙校验签名
boolean checkSign = RSA.checkSign(data.toString(), sign, publicKey);
System.out.println("校验签名结果:" checkSign);
}
}
3.springboot通过aop拦截进行sign校验
代码语言:javascript复制package com.unwulian.chitudata.aop;
import com.unwulian.chitudata.dto.ChiTuDataParam;
import com.unwulian.common.api.BaseResponse;
import com.unwulian.common.api.RequestBaseParam;
import com.unwulian.common.sign.RSA;
import com.unwulian.common.utils.StringUtils;
import org.apache.commons.lang.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 赤兔马服务校验签名
*
* @author shiye
* @create 2020-06-09 11:10
*/
@Aspect
@Component
public class CheckSignAOP {
protected final Logger logger = LoggerFactory.getLogger(CheckSignAOP.class);
//公匙
private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMx0G373RIwA2YF5kuMLtcdezdPr2b NbT6UkpjemKezZVN6UcL1dpo7ArcNdP5OOQQQIV9pOb6Iwv/ZNs0y5LnQn4WiXKQngA0xplMwBL2s2oGbtspKaQZwCzRb9wz ET22yI kY01IMPFAqYb7NJ8e83GOhf xJnDWCqwEZM3xZihgzzrPnCObG rI1H/O50TEXUbggi3 HtwN8vtoTNUyfGtjwKk XBx15aXjFtHwM1RV2qVnqh8pgmYzwIovZuE1eU/5fPPdiA9x9yJNzE7XcV4XFGoLimE3LJAcVV0Sdqcyieswk u/DtL6wXeESk9tu6OWo0rGrlyXuEN5QIDAQAB";
/**
* 定义切入点,切入点为com.unwulian.chitudata.controller中的所有函数
* 通过@Pointcut注解声明频繁使用的切点表达式
*/
@Pointcut("within(com.unwulian.chitudata.controller..*)")
public void BrokerAspect() {
}
/**
* @description 在连接点执行之前执行的通知
*/
@Around("BrokerAspect()")
public BaseResponse aroundAOP(ProceedingJoinPoint point) throws Throwable {
// if (!checkSignHandler(point)) {
// return BaseResponse.error("sign校验失败!");
// }
return (BaseResponse) point.proceed();
}
/**
* 校验签名
*
* @param point
* @return
*/
public boolean checkSignHandler(ProceedingJoinPoint point) {
boolean flag = false;
try {
//获取拦截方法的参数
Object[] params = point.getArgs();
if (params == null || params.length == 0) {
return flag;
}
logger.info("开始校验签名Args:{}", point.getArgs());
//获取请求头中得sign
String sign = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("sign");
if (StringUtils.isEmpty(sign)) {
// return flag;
}
StringBuffer data = new StringBuffer();
//获取请求参数
Object obj = params[0];
if (obj instanceof RequestBaseParam) {
RequestBaseParam baseParam = (RequestBaseParam) params[0];
Object t = baseParam.getT();
String timestamp = baseParam.getTimestamp();
if (t != null && t instanceof ChiTuDataParam) {
ChiTuDataParam chiTuDataParam = (ChiTuDataParam) t;
data.append(chiTuDataParam.tranceToStr());
} else if (t != null) {
//校验签名
data.append(t);
}
data.append("timestamp").append(timestamp);
} else if (obj instanceof ChiTuDataParam) {
ChiTuDataParam chiTuDataParam = (ChiTuDataParam) obj;
data.append(chiTuDataParam.tranceToStr());
data.append("timestamp").append(chiTuDataParam.getTimestamp());
}
logger.info("需要校验的参数data:{},如果我空不执行校验!", data.toString());
//校验签名
if (StringUtils.isNotEmpty(data)) {
flag = RSA.checkSign(data.toString(), sign, publicKey);
} else {
flag = true;
}
logger.info("校验签名sign结果:{}", flag);
} catch (Exception e) {
logger.info("校验签名sign异常:{}", e);
flag = false;
}
return flag;
}
}