阅读Java中的私有加密密钥

时间:2013-07-15 15:29:36

标签: java encryption private-key

我有以下代码:

    PEMParser pemParser;
    File telexuskeys = new File(locationKey);
    if(telexuskeys.exists())
        pemParser = new PEMParser(new FileReader(telexuskeys));
    else{
        usage(ops);
        throw new FileNotFoundException("The key file (company's certificate) doesn't exist!");
    }

    System.out.println("Loading company's certificate");

    Object object = pemParser.readObject();
    Object object2 = pemParser.readObject();

    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordPem.toCharArray());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); 

    byte[] keyBytes = PrivateKeyInfo.getInstance(object2).getEncoded();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");        
    PrivateKey pk = kf.generatePrivate(spec);

我的pem文件只有证书和私钥。我曾经能够读取文件并获取私钥,但现在该文件受密码保护(加密)。什么是我仍然缺少的指令。我知道我需要使用PEMDecryptorProvider和JcaPEMKeyConverter对象才能获得它,但我没有找到正确的组合。

1 个答案:

答案 0 :(得分:4)

以下代码为我工作。 (使用Bouncy Castle的bcpkix和bcprov库)。

private PrivateKey readPrivateKey(String privateKeyPath, String keyPassword) throws IOException {

    FileReader fileReader = new FileReader(privateKeyPath);
    PEMParser keyReader = new PEMParser(fileReader);

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(keyPassword.toCharArray());

    Object keyPair = keyReader.readObject();
    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProv);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    keyReader.close();
    return converter.getPrivateKey(keyInfo);