import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.mall.common.weixin.WeixinTools;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RSAUtils {
protected final Logger logger = LoggerFactory.getLogger(RSAUtils.class);
private static final String KEY_ALGORITHM = "PKCS12";
private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
private static final String CIPHER_TYPE = "X.509";
//签名
public static String signater(String jsonStr, String alias, String pwd){
try{
// 加载私钥
KeyStore keystore = KeyStore.getInstance(KEY_ALGORITHM);
InputStream instream = WeixinTools.class.getClassLoader().getResourceAsStream("user-rsa.pfx");
keystore.load(instream, pwd.toCharArray());
PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, pwd.toCharArray());
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateKey);
signature.update(jsonStr.getBytes());
byte[] result = signature.sign();
return Base64.getEncoder().encodeToString(result);
}catch(Exception e){
log.info("易支付签名异常!{}{}", e.getMessage(), e);
}
return "";
}
//验签
public static boolean verify(String xml, String signStr, String alias, String pwd){
try {
// 加载公钥
CertificateFactory certificateFactory = CertificateFactory.getInstance(CIPHER_TYPE);
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(WeixinTools.class.getClassLoader().getResourceAsStream("efps.cer"));
PublicKey publicKey = cert.getPublicKey();
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicKey);
signature.update(xml.getBytes());
return signature.verify(Base64.getDecoder().decode(signStr));
} catch (Exception e) {
log.error("易支付证书验签异常!{}{}", e.getMessage(),e);
}
return false;
}
}
需要两个比较关键的参数:alias, password
alias: 生成证书时的别名,若是不知道,可使用如下代码来查看所有的别名:
Enumeration aliasEnum = keyStore.aliases();
String keyAlias = "" ;
while (aliasEnum.hasMoreElements()) {
keyAlias = (String) aliasEnum.nextElement();
System.out.println("别名"+keyAlias);
}
password:使用genrsa命令生成证书时设置的密码