java – 从RSA .pem文件中获取PrivateKey [复制]

参见英文答案 > Decrypting an OpenSSL PEM Encoded RSA private key with Java?                                    1个
鉴于此.pem文件(使用openssl生成并使用密码加密):

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,AC009672952033EB

2wegzxf3MtncXS1CY3c.....
....
....
-----END RSA PRIVATE KEY-----

如何在Java中获取PrivateKey对象?我写了下面的代码,但我找不到获得KeySpec的正确方法:

PrivateKey readFromPem(File keyFile, String password){
    PemReader r = new PemReader(new InputStreamReader(new FileInputStream(keyFile)));
    PemObject pemObject = r.readPemObject();
    byte[] encodedKey = pemObject.getContent();

    KeySpec keySpec = ???? // how to get this?

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey key = keyFactory.generatePrivate(keySpec);
    return key;
}

我想我应该构建一个RSAPrivateKeySpec,但我不知道如何.我尝试了从this answerthis other answer开始的方法,但是在解析字节数组时它们都会导致错误.

我正在使用BouncyCastle 1.57(bcprov-jdk15on,bcmail-jdk15on和bcpkix-jdk15on)和Java 7.

您可以使用JcaPEMKeyConverter类读取私钥.
以下代码适用于带密码和无密码的密钥:

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;

// don't forget to add the provider
Security.addProvider(new BouncyCastleProvider());
String password = "your password";

// reads your key file
PEMParser pemParser = new PEMParser(new FileReader(keyFile));
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
    // Encrypted key - we will use provided password
    PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) object;
    // uses the password to decrypt the key
    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
    kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
} else {
    // Unencrypted key - no password needed
    PEMKeyPair ukp = (PEMKeyPair) object;
    kp = converter.getKeyPair(ukp);
}

// RSA
KeyFactory keyFac = KeyFactory.getInstance("RSA");
RSAPrivateCrtKeySpec privateKey = keyFac.getKeySpec(kp.getPrivate(), RSAPrivateCrtKeySpec.class);

System.out.println(privateKey.getClass());

privateKey的类将是java.security.spec.RSAPrivateCrtKeySpec(它扩展了RSAPrivateKeySpec).

相关文章
相关标签/搜索