【发布时间】:2021-07-12 12:49:27
【问题描述】:
最好展示我的问题并在之后进行解释(我正在使用 KeyStore Explorer 来查看我的 .pfx 文件):
基本上,我想要右边的结果,但我得到左边的结果。
更准确地说:KeyStore 应该在一个条目中包含私钥和证书链 (KeyPair)。
我不知何故无法让它在 java 中工作。这是我试图在左边得到结果: 下面代码的问题是,它没有验证证书并将它们添加为受信任的证书。
/**
* Creates and returns a new {@link KeyStore} from the provided information.
* @param keystoreType The {@link KeyStore}s type. Recommended: "pkcs12".
* Check {@link KeyStore#getInstance(String)} for details.
* @param passwordAsCharArray Password to encrypt this {@link KeyStore} and its keys.
* @param certificateChain The certificate chain is simply an array of {@link X509Certificate}s.
* @param privateKey The {@link PrivateKey}.
* @param publicKey The {@link PublicKey}.
* @throws KeyStoreException
*/
public KeyStore buildAndGetKeystore(String keystoreType, char[] passwordAsCharArray,
X509Certificate[] certificateChain, PrivateKey privateKey, PublicKey publicKey)
throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException, EmptyStringException, EmptyCharArrayException, EmptyCertificateChainException {
// Check for null parameters
Objects.requireNonNull(keystoreType);
Objects.requireNonNull(passwordAsCharArray);
Objects.requireNonNull(certificateChain);
Objects.requireNonNull(privateKey);
Objects.requireNonNull(publicKey);
// Check for empty parameters
if (keystoreType.isEmpty()) throw new EmptyStringException("Parameter 'keystoreType' should NOT be empty!");
if (passwordAsCharArray.length==0) throw new EmptyCharArrayException("Parameter 'passwordAsCharArray' should NOT be empty!");
if (certificateChain.length==0) throw new EmptyCertificateChainException("Parameter 'certificateChain' should NOT be empty!");
// Initialise a new keystore
KeyStore keystore = KeyStore.getInstance(keystoreType);
keystore.load(null, passwordAsCharArray); // Pass null to tell java this is a new keystore
// Insert certificates
for (int i = 0; i < certificateChain.length; i++) {
keystore.setCertificateEntry(""+i, certificateChain[i]);
}
// Write private key (with password protection) to keystore.
// NOTE: I tried this before and it only writes
// the private key to the .pfx file and ignores the domain chain
//keystore.setKeyEntry("sso-signing-key", privateKey, passwordAsCharArray, certificateChain);
return keystore;
}
一些额外的细节:
右侧的 KeyStore 是这样创建的:首先在 sslforfree.com 生成证书,然后将它们转换为带有 https://decoder.link/converter 的 PKCS12 KeyStore
【问题讨论】:
标签: java ssl ssl-certificate keystore encryption-asymmetric