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

笑着哭i 提交于 2020-01-03 00:54:11

问题


I am trying to automate generation of CA and certificates for our E2E testing. I started with Bouncy Castle and I have managed to generate CA cert and machine cert. However, now I need to convert the RSA keypair represented by BC' org.bouncycastle.crypto.AsymmetricCipherKeyPair to java.security.KeyPair. I cannot seem to find a way to do this.


回答1:


There's probably more than one way to do it, but here is one example:

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


来源:https://stackoverflow.com/questions/49158734/convert-bouncy-castles-asymmetriccipherkeypair-rsa-to-java-security-keypair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!