从RSA .pem文件中获取私钥

给定此.pem文件(使用openssl生成并使用密码加密):

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,AC009672952033EB

2wegzxf3MtncXS1CY3c.....

....

....

-----END RSA PRIVATE KEY-----

如何PrivateKey使用Java 获取对象?我编写了以下代码,但是找不到正确的方法来获取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,但我不知道如何。我尝试了这个答案和另一个答案中的方法,但是它们在解析字节数组时都导致错误。

回答:

我正在使用 (bcprov-jdk15on,bcmail-jdk15on和bcpkix-jdk15on)和

您可以使用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)。

以上是 从RSA .pem文件中获取私钥 的全部内容, 来源链接: utcz.com/qa/430524.html

回到顶部