java 使用 BouncyCastle 从 PEM Key 获取 KeyPair

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15656644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:26:04  来源:igfitidea点击:

Get KeyPair from PEM Key with BouncyCastle

javabouncycastlepem

提问by user2119056

I have a PEM Key and I want to get a KeyPair with it and bouncycastle. I found this code which seems good but I have a cast exception.

我有一个 PEM 密钥,我想用它和 bouncycastle 获得一个密钥对。我发现这段代码看起来不错,但我有一个强制转换异常。

function loadKey() {
    File privateKeyFile = new File(keyPath);
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    PEMDecryptorProvider decProv = new     JcePEMDecryptorProviderBuilder().build(password.toCharArray());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    Object object = pemParser.readObject();
    KeyPair kp;

    if (object instanceof PEMEncryptedKeyPair) {
        Logger.info("Encrypted key - we will use provided password");
        kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    }
    else {
        Logger.info("Unencrypted key - no password needed");    
        kp = converter.getKeyPair((PEMKeyPair) object);
    }

    return kp;
}

And it returns me : Unencrypted key - no password needed org.bouncycastle.asn1.x509.SubjectPublicKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair

它返回给我:未加密的密钥 - 不需要密码 org.bouncycastle.asn1.x509.SubjectPublicKeyInfo 不能转换为 org.bouncycastle.openssl.PEMKeyPair

I tried several methods but i didn't succeed.

我尝试了几种方法,但没有成功。

Thanks to help me :)

感谢帮助我:)

回答by Sarang

If you have a private key that has passphrase you might get this exception. Try removing the passphrase:

如果您有一个带有密码短语的私钥,您可能会遇到此异常。尝试删除密码:

openssl rsa -in /path/to/originalkeywithpass.key -out /path/to/newkeywithnopass.key