public String getRsaPriKeyByP12(String p12FilePath, String p12Pswd) throws KeyStoreException, NoSuchProviderException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
InputStream fis = new FileInputStream(p12FilePath);
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
keyStore.load(fis, p12Pswd.toCharArray());
Enumeration<String> aliases = keyStore.aliases();
String keyAlias = null;
if (aliases.hasMoreElements()) {
keyAlias = (String) aliases.nextElement();
System.out.println("p12's alias----->" + keyAlias);
}
PrivateKey priKey = (PrivateKey) (keyStore.getKey(keyAlias, null));
System.out.println("私钥:\n" + priKey);
String rsaBase64Prikey = Base64.encodeToString(priKey.getEncoded());
System.out.println("私钥RSA:\n" + rsaBase64Prikey);
return rsaBase64Prikey;
}
public String getRsaPublicKeyByCer(String cerFilePath) throws CertificateException, FileNotFoundException {
InputStream is = new FileInputStream(cerFilePath);
CertificateFactory cf = CertificateFactory.getInstance("x509");
Certificate cerCert = cf.generateCertificate(is);
PublicKey publicKey = cerCert.getPublicKey();
String rsaBase64publickey = Base64.encodeToString(publicKey.getEncoded());
System.out.println("public key:\n" + rsaBase64publickey);
return rsaBase64publickey;
}
测试
@Test
public void test() throws UnrecoverableKeyException, CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, NoSuchProviderException {
String PayP12FilePath = "E:\\pay.p12";
String PayCerFilePath = "E:\\pay.cer";
String PayP12Password = "a123456";
getRsaPriKeyByP12(PayP12FilePath, PayP12Password);
getRsaPublicKeyByCer(PayCerFilePath );