Read an encrypted private key with bouncycastle/spongycastle

杀马特。学长 韩版系。学妹 提交于 2019-11-29 12:08:36
Bludwarf

To sum up what I found on this topic here and there :

Here is the final code if you want to get the modulus for example :

// For JcaPEMKeyConverter().setProvider("BC")
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

// Using bcpkix-jdk14-1.48
PEMParser pemParser = new PEMParser(new FileReader(file));
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;
    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);

return privateKey;

And then you can call for example :

privateKey.getModulus();
monim

Using the answer for this question you should do the following

File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
Object object = pemParser.readObject();
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
}

Then you can say

PrivateKey key = kp.getPrivateKey();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!