package com.tax.util.sign;
import com.alibaba.fastjson.JSONObject;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
public class SignUtils {
private static final String RSA_CHARSET = "UTF-8";
private static final String FN_SIGN_TYPE = "signType";
private static final String SIGN_TYPE_RSA = "RSA";
public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1UqC5+PIbE+Ea9ryO8mDApKLfqjQ8o+zeElwn+0Hi+JM2GPryWYDM5PIBOwyVOIf/MAocXY9I4JU4wJxGSkfrf8F679/Pj9+AI0okNx0cTCkCL7ZXqzqtF/2DfiuwzX+XRR3kxMr6xYpfZftXVTEFwyfwXNFlAL167TOfJHvoAwIDAQAB";
public static final String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALVSoLn48hsT4Rr2vI7yYMCkot+qNDyj7N4SXCf7QeL4kzYY+vJZgMzk8gE7DJU4h/8wChxdj0jglTjAnEZKR+t/wXrv38+P34AjSiQ3HRxMKQIvtlerOq0X/YN+K7DNf5dFHeTEyvrFil9l+1dVMQXDJ/Bc0WUAvXrtM58ke+gDAgMBAAECgYEAm6wnBcOvyIOWvhmb5XY+juZKV5C/bFioojhNGp5jAMS9TrK/sJYbOM5O37Ocp/hy+ip6Y8QHol/+fU0QXmCjwR67CSdtJ8P/+oW24IFnFW63L+vJPrg8dtlD1FLgvD8yhg/49paQIy1GmhlkT+HJscywRfHTcv8NTB0ZpPJFawECQQDs/FManuRjEPohkBdNuifJJXwh3algyjlKszKK0+jc7VKh8pwfkQNCpJcaxpgwYfg4a7wj2oONmMRsKQ6Xz0TDAkEAw979b4uqrkAMUZjToNGe/owt1nqbRAvCjScqjACsmHu/+LgbbnYnKzSWi81uxn42sFD66Z5Kv5s2Tn5wbZ2bwQJACNsQ+/CuFimfPzvUMxpevDyDW/ydhLlp1KnHnLp4fDD+IoEfZmqT1Zyy7NQ5Aa3Xibw05p4WxmbMCEKsge3D4wJAAZxk4zT322UFdOpX2zu+HgPTIK9zdXTPTc/jprEeukZSRt5kw1zPZ6iQEGhJH/LLyllwJtm5baf+I1kg3ZXtQQJAYKTOjB7uhBTapJ01nppujZcA6EaUux4hY2gNtrX0kJxvGNKd4AjHMN9sVASv/Fq4k3ZxcSygZCJx933XKek+GA==";
/**
* 参数排序,拼装字符串
* @param data
* @return
*/
public static String getSortedContent(Map<String, Object> data) {
StringBuffer content = new StringBuffer();
List<String> keys = new ArrayList<String>(data.keySet());
Collections.sort(keys);
int index = 0;
for (String key : keys) {
String value = String.valueOf(data.get(key));
content.append((index == 0 ? "" : "&")).append(key).append("=").append(value);
index++;
}
return content.toString();
}
/**
* 公钥加密
* @param plainText
* @param publicKey
* @return
* @throws Exception
*/
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(cipherText);
}
/**
* 私钥解密
* @param cipherText
* @param privateKey
* @return
* @throws Exception
*/
public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
byte[] bytes = Base64.getDecoder().decode(cipherText);
Cipher decriptCipher = Cipher.getInstance("RSA");
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), StandardCharsets.UTF_8);
}
/**
* 私钥签名
* @param plainText
* @param privateKey
* @return
* @throws Exception
*/
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signature = privateSignature.sign();
return Base64.getEncoder().encodeToString(signature);
}
/**
* 公钥验证
* @param plainText
* @param signature
* @param publicKey
* @return
* @throws Exception
*/
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
throws Exception {
try {
byte[] buffer = Base64.getDecoder().decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 从字符串中加载私钥
*
* @param privateKeyStr
* 私钥数据字符串
* @throws Exception
* 加载私钥时产生的异常
*/
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
throws Exception {
try {
byte[] buffer = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
public static void main(String[] args) throws Exception {
List<String> aa = new ArrayList<>();
aa.add("1");
aa.add("2");
aa.add("3");
String aaStr = JSONObject.toJSONString(aa);
Map<String,Object> map = new HashMap<>();
map.put( "channel_code","lhhb");
map.put("channel_no","1212121212");
map.put( "channel_user","tp");
map.put("cert_no","11");
map.put("user_name","1");
map.put("phone_number","1");
map.put("bank","1");
map.put("bank_card_number","1");
map.put("bank_card_holder","1");
map.put( "notify_url","1111");
map.put("passport_photo",aaStr);
map.put("currency_code","EUR");
map.put("invite_code","1213");
map.put("tax_refund_photo",aaStr);
map.put("shopping_ticket_photo",aaStr);
map.put("signType","RSA");
// map.put("timeStemp",String.valueOf(System.currentTimeMillis()));
//参数排序
String mapSortStr = SignUtils.getSortedContent(map);
System.out.println("111111111111111"+mapSortStr);
//加载私钥
RSAPrivateKey priKey = SignUtils.loadPrivateKeyByStr(privateKey);
//私钥签名
String signStr = SignUtils.sign(mapSortStr,priKey);
System.out.println("sign:"+signStr);
//加载公钥
RSAPublicKey pubKey = SignUtils.loadPublicKeyByStr(publicKey);
//公钥验证
boolean dataStr = SignUtils.verify(mapSortStr,signStr,pubKey);
System.out.println("333333333333333"+dataStr);
//公钥加密
String priS = SignUtils.encrypt(mapSortStr,pubKey);
System.out.println(priS);
//公钥解密
String pubD = SignUtils.decrypt(priS,priKey);
System.out.println(pubD);
}
}