RSA加密方式:
public static void main(String[] args) {
String appKey = "";
String appSecret = "";
String signTimespan = String.valueOf(System.currentTimeMillis());
String text =appKey + appSecret + signTimespan ;
KeyPair pair = SecureUtil.generateKeyPair("RSA");
// 私钥
String privateKey = Base64.encode(pair.getPrivate().getEncoded());
// 公钥
String publicKey = Base64.encode(pair.getPublic().getEncoded());
RSA rsa = new RSA(privateKey, null);
// 加密
byte[] encrypt = rsa.encrypt(text.getBytes(), KeyType.PrivateKey);
String signToken = Base64.encode(encrypt);
RSA rsaPublicKey = new RSA(null, publicKey);
byte[] decrypt = rsaPublicKey.decrypt(signToken, KeyType.PublicKey);
String s = new String(decrypt);
System.out.println(s);
}
SM2加密方式:
public static void main(String[] args) throws Exception{
String appKey = "43534";
String signTimespan = String.valueOf(System.currentTimeMillis());
String appSecret = "MFkwEwYHKoZIzj0CAQYIKoEczwrweri0DQgAEc7pyWz+u5b1jYxXmwHRkiJldRDy3tdvxk4e44NxCYYk1M+5dO7788kma9yvdhBQv8nt7klZF7E1aCpoRd9VLqg==";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(appKey).append(appSecret).append(signTimespan);
// 加密字符串
String text = stringBuilder.toString();
KeyPair pair = SecureUtil.generateKeyPair("SM2");
// 私钥
String privateKey = Base64.encode(pair.getPrivate().getEncoded());
// 公钥
String publicKey = Base64.encode(pair.getPublic().getEncoded());
SM2 sm = new SM2(privateKey, null);
// 用私钥对信息生成数字签名,
byte[] sign = sm.sign(text.getBytes(), null);
// 使用base64进行编码编码
String signToken = Base64.encode(sign);
SM2 sm1 = new SM2(null, publicKey);
// sm1.usePlainEncoding();
String text1 = stringBuilder.toString();
boolean verify = sm1.verify(text1.getBytes(), Base64.decode(signToken));
System.out.println(verify);
}
案例:
package com.interceptor; import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; import cn.hutool.crypto.asymmetric.SM2; import com.alibaba.fastjson.JSON; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.security.KeyPair; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * 加密用法-需在数据库维护以下字段 * 1.publicKey : 加密约定公钥 * 2.signType: 加密方式 MS2/RSA * 3.appKey : 税号/识别标识 * 4.appSalt : 任意随机的字符串 */ @Slf4j @Aspect @Component public class SignOauthAspect { @Autowired private SignService signService; @Value("${app.sign.hasOpen:false}") private boolean openSign; @Pointcut("@annotation(com.api.common.anno.SignOauth)") public void signOauth(){ log.info("=============验签认证初始化==============="); } @Before("signOauth()") public void signCheck(JoinPoint joinPoint) { log.info("=============验签认证校验==============="); if (openSign) { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); // 获取请求头 Enumeration<String> enumeration = request.getHeaderNames(); Map<String, Object> headers = new HashMap<>(); while (enumeration.hasMoreElements()) { String name = enumeration.nextElement(); String value = request.getHeader(name); headers.put(name, value); } log.info("SignOauthAspect-请求token:{}", JSON.toJSONString(headers)); String appKey = null == headers.get(SignOauthConst.APP_KEY) ? null : headers.get(SignOauthConst.APP_KEY).toString(); String token = null == headers.get(SignOauthConst.SIGN_TOKEN) ? null : headers.get(SignOauthConst.SIGN_TOKEN).toString(); String signTypeReq = null == headers.get(SignOauthConst.SIGN_TYPE) ? null : headers.get(SignOauthConst.SIGN_TYPE).toString(); String signNonce = null == headers.get(SignOauthConst.SIGN_NONCE) ? null : headers.get(SignOauthConst.SIGN_NONCE).toString(); String signTimespan = null == headers.get(SignOauthConst.SIGN_TIMESPAN) ? null : headers.get(SignOauthConst.SIGN_TIMESPAN).toString(); //String clientCode = null == headers.get(SignOauthConst.SIGN_CLIENT_CODE)? null : headers.get(SignOauthConst.SIGN_CLIENT_CODE).toString(); //AssertUtils.isNotEmpty(clientCode,"sign-client-code为空"); AssertUtils.isNotEmpty(appKey, "app-key为空"); AssertUtils.isNotEmpty(token, "sign-token为空"); AssertUtils.isNotEmpty(signTypeReq, "sign-type为空"); AssertUtils.isNotNull(signTimespan, "sign-timespan为空"); AssertUtils.isNotNull(signNonce, "sign-nonce为空"); Long currentTime = System.currentTimeMillis(); long gapTime = currentTime - Long.parseLong(signTimespan); Sign sign = signService.getByAppKey(appKey); if (null == sign) { throw new RuntimeException("当前接入方不存在"); } if(null == sign.getTimeOut()){ throw new RuntimeException("服务方未配置超时时间"); } long maxTime = sign.getTimeOut() * 60 * 1000; log.info("SignOauthAspect-gapTime:{}, maxTime:{}, currentTime:{} ",gapTime, maxTime, currentTime); //最大月允许客户端时间比服务端快1分钟 if (gapTime > maxTime || gapTime < -60000) { throw new RuntimeException("token超时请重新生成"); } if (sign.getClientStatus().equals("0")) { throw new RuntimeException("当前接入方已停用"); } String appSalt = sign.getAppSalt(); String signType = sign.getSignType(); String publicKey = sign.getPublicKey(); if (!signType.equals(signTypeReq)) { throw new RuntimeException("加密约定不一致"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(appKey).append(appSalt).append(signTimespan).append(signNonce); String text = stringBuilder.toString(); try { if (signType.equals("SM2")) { SM2 sm1 = new SM2(null, publicKey); boolean verify = sm1.verify(text.getBytes(), Base64.decode(token)); if (!verify) { throw new RuntimeException("验签失败"); } } else if (signType.equals("RSA")) { RSA rsaPublicKey = new RSA(null, publicKey); byte[] decrypt = rsaPublicKey.decrypt(token, KeyType.PublicKey); //解密token String decode = new String(decrypt); if (!decode.equals(text)) { throw new RuntimeException("验签失败"); } } else { throw new RuntimeException("验签失败"); } } catch (Exception e) { log.info("token校验失败-异常", e); throw new RuntimeException("token校验异常"); } } } //sm2 /*public static void main(String[] args) throws Exception{ String appKey = "91325P"; String signTimespan = String.valueOf(System.currentTimeMillis()); String appSecret = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0Dg=="; StringBuilder stringBuilder = new StringBuilder(); String nonce = "123456789"; //appKey +appSecret+sign-timespan+nonce stringBuilder.append(appKey).append(appSecret).append(signTimespan).append(nonce); // 加密字符串 String text = stringBuilder.toString(); KeyPair pair = SecureUtil.generateKeyPair("SM2"); //String privateKey = Base64.encode(pair.getPrivate().getEncoded()); // 公钥 //String publicKey = Base64.encode(pair.getPublic().getEncoded()); // 私钥 String privateKey = "MIGTAgEAMB0FZMq7LhPKz9IOen"; // 公钥 String publicKey = "MFkwEwYHKoZIzj0CAQYpw=="; SM2 sm = new SM2(privateKey, null); byte[] sign = sm.sign(text.getBytes(), null); String signToken = Base64.encode(sign); SM2 sm1 = new SM2(null, publicKey); String text1 = stringBuilder.toString(); boolean verify = sm1.verify(text1.getBytes(), Base64.decode(signToken)); System.out.println(verify); //System.out.println("signToken1-:"+ signToken1); System.out.println(); System.out.println("signToken-:"+ signToken); System.out.println(); System.out.println(); System.out.println(); System.out.println("signTimespan-:"+ signTimespan); System.out.println(); //System.out.println("privateKey-:"+ privateKey); System.out.println("publicKey-:"+ publicKey); }*/ //RSA /*public static void main(String[] args) { String appKey = "91P"; String signTimespan = String.valueOf(System.currentTimeMillis()); String appSecret = "MFkwEwYHcz1UBgi0Dg=="; String nonce = "123456789"; StringBuilder text = new StringBuilder(); text.append(appKey).append(appSecret).append(signTimespan).append(nonce); KeyPair pair = SecureUtil.generateKeyPair("RSA"); // 私钥 String privateKey =Base64.encode(pair.getPrivate().getEncoded()); // 公钥 String publicKey = Base64.encode(pair.getPublic().getEncoded()); RSA rsa = new RSA(privateKey, null); // 加密 byte[] encrypt = rsa.encrypt(text.toString().getBytes(), KeyType.PrivateKey); String signToken = Base64.encode(encrypt); RSA rsaPublicKey = new RSA(null, publicKey); byte[] decrypt = rsaPublicKey.decrypt(signToken, KeyType.PublicKey); System.out.println("signToken-"+ signToken); System.out.println("signTimespan-"+ signTimespan); System.out.println("publicKey-"+ publicKey); String s = new String(decrypt); System.out.println("text-"+s); }*/ /* public static void main(String[] args) { String appKey = "9150000356"; String signTimespan = String.valueOf(System.currentTimeMillis()); String appSecret = "MFkwEwYHKoZKoEcz1UBgi0Dg=="; StringBuilder stringBuilder = new StringBuilder(); String nonce = "9626"; String text =appKey + appSecret + signTimespan +nonce; KeyPair pair = SecureUtil.generateKeyPair("RSA"); // 私钥 String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDEwAyJZskgUNFq" + "CTSr1oaoIRJ VZi5v4j3iYvPUVCb5Tl0E" + "ZAMVux6JnGptPLrkfIGlQsHzWX77RaU0TY1iVKEGlIAmsIZ+D6hAa/giWc+2bMvc" + "sKHgzgWXWj/xEp" + "Nz6o/1heJmAQ7gJmMMzx6o6ezFAaAwaTX90oS+UCgYAVsBkLz7t4OcygKaQJ8ZoK" + "KHQzBabKflthoa8Pnuqefxkn4x/OpFN50K/7ryhPjbvq8iM7JSNbC9cJzIIlanU+" + "kUpmiRuDMUnd4xhdsh2j4AiFpjKf7ZHQlDXrJ7gkWzfbQ0EGYAvCSSsmunSTepzG" + "XO4xNMBs3VhRiwub/JSCKA==";//Base64.encode(pair.getPrivate().getEncoded()); // 公钥 String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxMAMiWbJIFDRagk0q9aG" + "qCES94mLz1FQm+U5dBGQDFbse" + "iZxqbTy65HyBpULB81l++0WlNE2NYlShBpSAJrCGfg+oQGv4IlnPtmzL3LCh4M4F" + "lwIDAQAB";//Base64.encode(pair.getPublic().getEncoded()); RSA rsa = new RSA(privateKey, null); // 加密 byte[] encrypt = rsa.encrypt(text.getBytes(), KeyType.PrivateKey); String signToken = Base64.encode(encrypt); RSA rsaPublicKey = new RSA(null, publicKey); byte[] decrypt = rsaPublicKey.decrypt(signToken, KeyType.PublicKey); String s = new String(decrypt); System.out.println("signToken: "+ signToken); System.out.println("signTimespan: "+ signTimespan); *//*System.out.println("publicKey-"+ publicKey); System.out.println("text-"+s);*//* }*/ }