撸了今年阿里、网易和美团的面试,我有一个重要发现.......>>>
前言:最近接了一个支付平台,提供了.pfx私钥文件以及.cer公钥文件,对于不常用的加密技术的人来说一头雾水。
代码:
public static String sign(String pfxFile, String pfxPwd, String str, String signature, String coding) {
try {
//获取pfx文件的prikey
Security.addProvider(new BouncyCastleProvider());
KeyStore e = KeyStore.getInstance("PKCS12", "BC");
FileInputStream fis = new FileInputStream(pfxFile);
e.load(fis, pfxPwd.toCharArray());
Enumeration aliases = e.aliases();
String keyAlias = null;
PrivateKey priKey = null;
if (aliases != null) {
while (aliases.hasMoreElements()) {
keyAlias = (String) aliases.nextElement();
priKey = (PrivateKey) e.getKey(keyAlias, pfxPwd.toCharArray());
if (priKey != null) {
break;
}
}
}
//使用Signature加密
Signature signet = Signature.getInstance(signature);
signet.initSign(priKey);
signet.update(str.getBytes(coding));
byte[] signed = signet.sign();
String strSign = new String(Base64.encode(signed));
return strSign;
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
调用:
System.out.println(sign("C://xxx.pfx","123456","123","MD5withRSA","UTF-8"));
cer公钥代码:
//通过cer文件获取到publickey
String e ="c://xxx.cer";
logger.debug("公钥证书路径:" + e);
FileInputStream in = new FileInputStream(e);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cac = cf.generateCertificate(in);
PublicKey pubKey = cac.getPublicKey();
in.close();
//通过pubkey加密
Signature signetcheck = Signature.getInstance("MD5withRSA");
signetcheck.initVerify(pubKey);
signetcheck.update(Base64.decode(msg));
//验证是否一样
if (!signetcheck.verify(Base64.decode(check))) {
throw new 异常("Verify Signature Error");
}
博客地址:http://my.oschina.net/wangnian