使用BouncyCastle从PEM Key获取KeyPair

时间:2013-03-27 10:28:47

标签: java bouncycastle pem

我有一个PEM Key,我希望得到一个KeyPair和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;
}

它回报我: 未加密的密钥 - 无需密码 org.bouncycastle.asn1.x509.SubjectPublicKeyInfo无法强制转换为org.bouncycastle.openssl.PEMKeyPair

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

感谢帮助我:)

2 个答案:

答案 0 :(得分:5)

如果您的私钥具有密码短语,则可能会出现此异常。尝试删除密码:

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

答案 1 :(得分:0)

您可以使用以下代码

PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();

例如:

public PrivateKey getKeyFromClassPath(String filename) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream stream = loader.getResourceAsStream("certificates/" + filename);
    if (stream == null) {
        throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    try {
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pp = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        pp.close();
        return kp.getPrivate();
    } catch (IOException ex) {
        throw new CertificateException("Could not read private key from classpath", ex);
    }
}