以编程方式将PEM文件转换为PKCS8 [英] Converting PEM file to PKCS8 programmatically

查看:148
本文介绍了以编程方式将PEM文件转换为PKCS8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将pem文件转换为pk8.我可以在终端上使用openssl来做到这一点;

I want to convert pem file to pk8. I can do this with openssl on terminal as ;

openssl pkcs8 -topk8 -inform PEM -outform DER -in client-key.pem -out client-key.pk8 -nocrypt

但是我需要在Java上以编程方式执行此操作.看起来好像有一个用于加密的软件包,其中包含openssl实现,例如 Bounty Castle ,但我不知道如何执行此转换过程.有办法吗?

But I need to do this programmatically on java. Its look like there is a package for cryptography which contains openssl implementation as Bounty Castle but I couldn't figure out how can do this converting process. Is there a way for doing that ?

推荐答案

Bouncy Castle的测试代码包含一个如何在函数

The test code of Bouncy Castle contains an example of how to read an RSA Private key, in the function ParserTest.doOpenSslRsaTest. Here is a slight modification of that example, it can handle both encrypted and non-encrypted keys as input (and in the latter case, the passphrase will not be used):

private static KeyPair pemRSAP1ReadKeyPair(String pemfilename, String passphrase)
throws FileNotFoundException, IOException
{
    KeyPair result = null;

    FileReader reader = new FileReader(pemfilename);
    PEMParser parser = new PEMParser(reader);
    Object pemobj = parser.readObject();
    parser.close();
    reader.close();

    if (pemobj  == null || 
        !((pemobj instanceof PEMKeyPair) || (pemobj instanceof PEMEncryptedKeyPair))) {
        System.out.println("Unable to read key pair");
    } else {
        PEMKeyPair pemkp;
        if (pemobj instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair kp = (PEMEncryptedKeyPair)pemobj;
            PEMDecryptorProvider decprov = new BcPEMDecryptorProvider(passphrase.toCharArray());
            pemkp = kp.decryptKeyPair(decprov);
        } else {
            pemkp = (PEMKeyPair)pemobj;
        }
        result = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemkp);
    }
    return result;
}

将其放在一起进行转换:

Putting it together to do the conversion:

Security.addProvider(new BouncyCastleProvider());

try {
    KeyPair kp = pemRSAP1ReadKeyPair("rsakey_enc.pem", "changeit");
    PrivateKey privkey = kp.getPrivate();
    if (!(privkey instanceof RSAPrivateKey)) {
        System.out.println("PEM input file does not contain an RSA private key");
    } else {
        pemRSAP8WritePrivateKey(privkey, "rsakey.p8", "abracadabra");
    }    
} catch (Exception e) {
    System.out.println("Caught exception: " + e.getMessage());
}

这篇关于以编程方式将PEM文件转换为PKCS8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆