将 Bouncy Castle 的 AsymmetricCipherKeyPair (RSA) 转换为 java.security.KeyPair

convert Bouncy Castle's AsymmetricCipherKeyPair (RSA) to java.security.KeyPair

我正在尝试为我们的 E2E 测试自动生成 CA 和证书。我从 Bouncy Castle 开始,我已经成功地生成了 CA 证书和机器证书。但是,现在我需要将 BC' org.bouncycastle.crypto.AsymmetricCipherKeyPair 表示的 RSA 密钥对转换为 java.security.KeyPair。我似乎找不到办法做到这一点。

可能有不止一种方法,但这里有一个例子:

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));
}