【问题标题】:convert Bouncy Castle's AsymmetricCipherKeyPair (RSA) to java.security.KeyPair将 Bouncy Castle 的 AsymmetricCipherKeyPair (RSA) 转换为 java.security.KeyPair
【发布时间】:2018-08-15 22:59:11
【问题描述】:
我正在尝试为我们的 E2E 测试自动生成 CA 和证书。我从 Bouncy Castle 开始,并设法生成 CA 证书和机器证书。但是,现在我需要将 BC'org.bouncycastle.crypto.AsymmetricCipherKeyPair 代表的 RSA 密钥对转换为 java.security.KeyPair。我似乎找不到这样做的方法。
【问题讨论】:
标签:
java
encryption
bouncycastle
jce
【解决方案1】:
可能有不止一种方法可以做到这一点,但这里有一个例子:
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
private static KeyPair convertBcToJceKeyPair(AsymmetricCipherKeyPair bcKeyPair) throws Exception {
byte[] pkcs8Encoded = PrivateKeyInfoFactory.createPrivateKeyInfo(bcKeyPair.getPrivate()).getEncoded();
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pkcs8Encoded);
byte[] spkiEncoded = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(bcKeyPair.getPublic()).getEncoded();
X509EncodedKeySpec spkiKeySpec = new X509EncodedKeySpec(spkiEncoded);
KeyFactory keyFac = KeyFactory.getInstance("RSA");
return new KeyPair(keyFac.generatePublic(spkiKeySpec), keyFac.generatePrivate(pkcs8KeySpec));
}