1

I got private key which I would like to export to .pem format Problem is that, when I call privateKey.getEncoded() I get null. But I can get all info like exponent, modulus and so one (all from interface RSAPrivateKey). privateKey is org.mozilla.jss.pkcs11.PK11RSAPrivateKey Object.

    public String exportPrivateKey(PrivateKey privateKey) throws Throwable {
    byte[] encoded = privateKey.getEncoded();//this is null:<
    String body = DatatypeConverter.printBase64Binary(encoded);

    return RSA_PRIVATE_HEADER + body + RSA_PRIVATE_FOOTER;
}

How to export that key to pem file?

  • 1
    Huh, the implementations I see on the internet all return `null` for those values. Are you sure you can export private key information from a security token? It is possible, but normally you cannot simply extract private key key information from the token; that's kind of the idea of the token in the first place. – Maarten Bodewes Oct 31 '15 at 12:06
  • 1
    You might want to see if you can cast to `RSAPrivateCrtKey` as well; that contains more parameters for a more efficient RSA operation. – Maarten Bodewes Oct 31 '15 at 12:08
  • @MaartenBodewes yup I can cast but meanwhile(and I get access to p,q etc) I found piece of code which give me encoded version. If You could check this answer below... – Marcin Mierzejewski Oct 31 '15 at 12:58

1 Answers1

1

Method I found in PKCS12Export, and it propably works:P

private byte[] getEncodedKey(PrivateKey var1) throws Exception {
    CryptoManager var2 = CryptoManager.getInstance();
    CryptoToken var3 = var2.getInternalKeyStorageToken();
    KeyGenerator var4 = var3.getKeyGenerator(KeyGenAlgorithm.DES3);
    SymmetricKey var5 = var4.generate();
    KeyWrapper var6 = var3.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
    byte[] var7 = new byte[]{(byte)1, (byte)1, (byte)1, (byte)1, (byte)1, (byte)1, (byte)1, (byte)1};
    IVParameterSpec var8 = new IVParameterSpec(var7);
    var6.initWrap(var5, var8);
    byte[] var9 = var6.wrap(var1);
    Cipher var10 = var3.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
    var10.initDecrypt(var5, var8);
    return var10.doFinal(var9);
}
  • 2
    Yes, wrapping and then decryption could work pretty well. You should however still convert to base 64 and add the header and footer. You could use the `PEMWriter` functionality in Bouncy Castle for this... If the above works you are probably left with a PKCS#8 encoded private key (using only the inner PKCS#8 ASN.1 structures). – Maarten Bodewes Oct 31 '15 at 14:47
  • @MaartenBodewes : Thanks for Help Maarten! Maybe You know if can I find similiar PFX/PKCS12Writer functionality in Bouncy Castle?:P – Marcin Mierzejewski Nov 03 '15 at 07:58
  • 1
    Yes, many of the PKCS standards should be in there somewhere, PKCS#12 is definitely one of them. – Maarten Bodewes Nov 03 '15 at 10:08