4

我有一个 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;
}

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

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

感谢帮助我:)

4

2 回答 2

6

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

openssl rsa -in /path/to/originalkeywithpass.key -out /path/to/newkeywithnopass.key
于 2014-07-25T11:55:09.663 回答
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);
    }
}
于 2020-10-15T09:59:14.623 回答