我正在尝试为我们的E2E测试自动生成CA和证书。我从Bouncy Castle开始,我已经设法生成CA证书和机器证书。但是,现在我需要将BC'org.bouncycastle.crypto.AsymmetricCipherKeyPair
表示的RSA密钥对转换为java.security.KeyPair
。我似乎找不到办法做到这一点。
答案 0 :(得分:2)
可能有多种方法可以做到,但这里有一个例子:
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));
}