将 Bouncy Castle 的非对称密码密钥对 (RSA) 转换为 java.security.KeyPair

问题描述 投票:0回答:1

我正在尝试自动生成用于 E2E 测试的 CA 和证书。我从 Bouncy Castle 开始,成功生成了 CA 证书和机器证书。但是,现在我需要将 BC'

org.bouncycastle.crypto.AsymmetricCipherKeyPair
表示的 RSA 密钥对转换为
java.security.KeyPair
。我似乎找不到办法做到这一点。

java encryption bouncycastle jce
1个回答
6
投票

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

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

这是一个相反的示例,将 java

KeyPair
转换为 Bouncy Castle
AsymmetricCipherKeyPair

private static AsymmetricCipherKeyPair convertJceToBcKeyPair(KeyPair javaKeyPair) {
    RSAPublicKey javaRsaPub = (RSAPublicKey) javaKeyPair.getPublic();
    RSAKeyParameters bcRsaPub = new RSAKeyParameters(false, javaRsaPub.getModulus(), javaRsaPub.getPublicExponent());
    if (javaKeyPair.getPrivate() instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey javaRsaPriv = (RSAPrivateCrtKey) javaKeyPair.getPrivate();
        RSAKeyParameters bcRsaPriv = new RSAPrivateCrtKeyParameters(
                javaRsaPriv.getModulus(),
                javaRsaPriv.getPublicExponent(),
                javaRsaPriv.getPrivateExponent(),
                javaRsaPriv.getPrimeP(),
                javaRsaPriv.getPrimeQ(),
                javaRsaPriv.getPrimeExponentP(),
                javaRsaPriv.getPrimeExponentQ(),
                javaRsaPriv.getCrtCoefficient()
        );
        return new AsymmetricCipherKeyPair(bcRsaPub, bcRsaPriv);
    } else {
        RSAPrivateKey javaRsaPriv = (RSAPrivateKey) javaKeyPair.getPrivate();
        RSAKeyParameters bcRsaPriv = new RSAKeyParameters(
                true,
                javaRsaPriv.getModulus(),
                javaRsaPriv.getPrivateExponent()
        );
        return new AsymmetricCipherKeyPair(bcRsaPub, bcRsaPriv);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.