diff --git a/src/main/java/com/yexuejc/base/encrypt/RSA2.java b/src/main/java/com/yexuejc/base/encrypt/RSA2.java index 17adc07..20f516b 100644 --- a/src/main/java/com/yexuejc/base/encrypt/RSA2.java +++ b/src/main/java/com/yexuejc/base/encrypt/RSA2.java @@ -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();