|
1 | 1 | package com.laker.postman.service.http.ssl; |
2 | 2 |
|
| 3 | +import cn.hutool.core.io.FileUtil; |
| 4 | +import cn.hutool.core.util.StrUtil; |
3 | 5 | import com.laker.postman.model.ClientCertificate; |
4 | 6 | import lombok.extern.slf4j.Slf4j; |
| 7 | +import nl.altindag.ssl.pem.util.PemUtils; |
5 | 8 |
|
6 | 9 | import javax.net.ssl.KeyManager; |
7 | 10 | import javax.net.ssl.KeyManagerFactory; |
| 11 | +import javax.net.ssl.X509ExtendedKeyManager; |
8 | 12 | import javax.net.ssl.X509KeyManager; |
| 13 | +import java.io.BufferedInputStream; |
9 | 14 | import java.io.FileInputStream; |
10 | 15 | import java.io.IOException; |
11 | 16 | import java.net.Socket; |
@@ -70,28 +75,16 @@ private static KeyManager[] createKeyManagersFromPFX(ClientCertificate cert) thr |
70 | 75 | * 从 PEM 文件创建 KeyManager |
71 | 76 | */ |
72 | 77 | private static KeyManager[] createKeyManagersFromPEM(ClientCertificate cert) throws Exception { |
73 | | - // 加载证书 |
74 | | - X509Certificate certificate = loadCertificateFromPEM(cert.getCertPath()); |
| 78 | + log.debug("Loaded PEM certificate from: {} and key from: {}", cert.getCertPath(), cert.getKeyPath()); |
| 79 | + try (BufferedInputStream certInputStream = FileUtil.getInputStream(cert.getCertPath()); |
| 80 | + BufferedInputStream keyInputStream = FileUtil.getInputStream(cert.getKeyPath())) { |
75 | 81 |
|
76 | | - // 加载私钥 |
77 | | - PrivateKey privateKey = loadPrivateKeyFromPEM(cert.getKeyPath(), cert.getKeyPassword()); |
| 82 | + X509ExtendedKeyManager keyManager = StrUtil.isNotBlank(cert.getKeyPassword()) |
| 83 | + ? PemUtils.loadIdentityMaterial(certInputStream, keyInputStream, cert.getKeyPassword().toCharArray()) |
| 84 | + : PemUtils.loadIdentityMaterial(certInputStream, keyInputStream); |
78 | 85 |
|
79 | | - // 创建 KeyStore 并添加证书和私钥 |
80 | | - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); |
81 | | - keyStore.load(null, null); |
82 | | - |
83 | | - Certificate[] certChain = new Certificate[]{certificate}; |
84 | | - char[] keyPassword = cert.getKeyPassword() != null ? |
85 | | - cert.getKeyPassword().toCharArray() : new char[0]; |
86 | | - |
87 | | - keyStore.setKeyEntry("client-cert", privateKey, keyPassword, certChain); |
88 | | - |
89 | | - KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
90 | | - kmf.init(keyStore, keyPassword); |
91 | | - |
92 | | - log.debug("Loaded PEM certificate from: {} and key from: {}", |
93 | | - cert.getCertPath(), cert.getKeyPath()); |
94 | | - return kmf.getKeyManagers(); |
| 86 | + return new KeyManager[]{keyManager}; |
| 87 | + } |
95 | 88 | } |
96 | 89 |
|
97 | 90 | /** |
|
0 commit comments