支持读取PKCS12格式的key(私钥)pfx格式的证书

This commit is contained in:
maxf 2018-12-20 17:03:54 +08:00
parent cb78538c01
commit 7368baf553

View File

@ -1,5 +1,7 @@
package com.yexuejc.base.encrypt;
import com.yexuejc.base.util.StrUtil;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -12,6 +14,7 @@ import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Enumeration;
/**
* RSA加解密 证书模式
@ -42,7 +45,7 @@ public class RSA2 {
}
/**
* 得到私钥
* 读取JKS格式的key私钥keystore格式
*
* @param filepath 私钥路径
* @param alias 证书别名
@ -55,11 +58,54 @@ public class RSA2 {
* @throws UnrecoverableKeyException
*/
public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
KeyStore ks = KeyStore.getInstance("JKS");
return getPrivateKey(filepath, alias, password, "JKS");
}
/**
* 读取PKCS12格式的key私钥pfx格式
*
* @param filepath 私钥路径
* @param alias 证书别名 可空
* @param password 证书密码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws UnrecoverableKeyException
*/
public static RSAPrivateKey getPrivateKeyFromPKCS12(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
return getPrivateKey(filepath, alias, password, "PKCS12");
}
/**
* 读取key私钥
*
* @param filepath 私钥路径
* @param alias 证书别名 可空
* @param password 证书密码
* @param type 证书格式
* @return
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws UnrecoverableKeyException
*/
public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password, String type) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
KeyStore ks = KeyStore.getInstance(type);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filepath);
ks.load(fileInputStream, password.toCharArray());
if (StrUtil.isEmpty(alias)) {
Enumeration<?> aliases = ks.aliases();
if (aliases != null) {
if (aliases.hasMoreElements()) {
alias = (String) aliases.nextElement();
}
}
}
} finally {
if (fileInputStream != null) {
fileInputStream.close();