7 Replies Latest reply on Oct 29, 2009 8:03 AM by PhHein

    How to load an RSA private key from a file?

      I'm a newbie in regards to the Security APIs and I have need to have an instance of 'PrivateKey' passed off to an library I'm working with (GData to be specific).

      My public key was generated with OpenSSL and is a 1024-bit RSA key encoded in an X.509 certificate in PEM format. I also have my private key in a separate file and I would like to load the private key from that file and have it converted into correct instance of 'PrivateKey'. Can some one point in a general direction on how I would accomplish this?

      Any help would be appreciated.

        • 1. Re: How to load an RSA private key from a file?
                     File pubKeyFile = ...
                     File privKeyFile = ...
                     // read public key DER file
                      DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
                      byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
                      // read private key DER file
                      dis = new DataInputStream(new FileInputStream(privKeyFile));
                      byte[] privKeyBytes = new byte[(int)privKeyFile.length()];
                      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                      // decode public key
                      X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
                      RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
                      // decode private key
                      PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
                      RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
          Message was edited by:
          • 2. Re: How to load an RSA private key from a file?
            Thank-you for such a quick response. I tried out the code sample you suggested, however, when invoking keyFactory.generatePublic or keyFactory.generatePrivate, I get the exception:

            java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
                 at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:163)
                 at java.security.KeyFactory.generatePublic(KeyFactory.java:284)

            What's specific about opening up a 'DER' key file versus a PEM key file? Mine is saved 'PEM' so the private key file resembles:

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


            -----END RSA PRIVATE KEY-----
            -----BEGIN CERTIFICATE REQUEST-----


            -----END CERTIFICATE REQUEST-----

            • 3. Re: How to load an RSA private key from a file?
              PEM files consist of a header, body and footer as ASCII characters with the body being the Base64 encoded content of the DER file. You can convert PEM to DER in two obvious ways -

              1) Use openssl to convert the PEM to DER using something like
                         openssl rsa -inform PEM -in rsapriv.pem -outform DER -pubout -out rsapub.der
                         openssl pkcs8 -topk8 -inform PEM -in rsapriv.pem -outform DER -nocrypt -out rsapriv.der
              Check the openssl 'man page' for further details.
              2) Within your Java, strip the header and footer and then Base64 decode the body before using the body to create the keys.

              Message was edited by:
              • 4. Re: How to load an RSA private key from a file?
                Thank you very much -- that worked. My previous attempt of converting with openssl wasn't correct.

                • 5. Re: How to load an RSA private key from a file?
                  Dear Guys,

                  Using Export option in IE, I have exported .PFX file with Private key and certificate.

                  Using OpenSSL command, converted .PFX to .PEM file

                  openssl pkcs12 -in like.pfx -out like.pem -nocerts -nodes

                  I got the message
                  MAC verified OK

                  The content of like.PEM file is

                  Bag Attributes
                  localKeyID: 01 00 00 00
                  Microsoft CSP Name: Microsoft Enhanced Cryptographic Provider v1.0
                  friendlyName: 21e25e47d94303b0f4efd0be57f606a7_77d1e77a-0baf-4fae-a5f8-c9fd61669a13
                  Key Attributes
                  X509v3 Key Usage: 10
                  -----BEGIN RSA PRIVATE KEY-----
                  -----END RSA PRIVATE KEY-----

                  I used the following command to convert this .PEM file .DER file

                  openssl pkcs8 -topk8 -nocrypt -in like.pem -outform DER -out like.der

                  I tried to generate Private Key object in Java by using the following code

                  package com.my.pkcs7;

                  import java.io.DataInputStream;
                  import java.io.File;
                  import java.io.FileInputStream;
                  import java.io.FileNotFoundException;
                  import java.io.IOException;
                  import java.security.KeyFactory;
                  import java.security.NoSuchAlgorithmException;
                  import java.security.PrivateKey;
                  import java.security.spec.InvalidKeySpecException;
                  import java.security.spec.PKCS8EncodedKeySpec;

                  public class ExtractPrivateKey {
                       public static void main(String[] args) {
                  // read private key DER file
                            String privKeyFile = System.getProperty("user.home") + File.separator + "pkcs7" + File.separator + "like.der";
                            File file = new File(privKeyFile);
                  DataInputStream dis;
                            try {
                                 dis = new DataInputStream(new FileInputStream(file));
                  byte[] privKeyBytes = new byte[(int)privKeyFile.length()];

                  // decode private key
                  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                  PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
                  System.out.println("Private Key Spec " + privSpec);

                  PrivateKey privKey = keyFactory.generatePrivate(privSpec);
                  System.out.println("Private Key CONTENT:::::: " + privKey);

                            } catch (FileNotFoundException e) {
                                 // TODO Auto-generated catch block
                            } catch (IOException e) {
                                 // TODO Auto-generated catch block
                            } catch (NoSuchAlgorithmException e) {
                                 // TODO Auto-generated catch block
                            } catch (InvalidKeySpecException e) {
                                 // TODO Auto-generated catch block

                  When I run this program I am getting the following exception

                  Private Key Spec java.security.spec.PKCS8EncodedKeySpec@18d107f
                  java.security.spec.InvalidKeySpecException: Unknown key spec.
                       at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePrivate(Unknown Source)
                       at com.sun.net.ssl.internal.ssl.JSA_RSAKeyFactory.engineGeneratePrivate(Unknown Source)
                       at java.security.KeyFactory.generatePrivate(Unknown Source)
                       at com.my.pkcs7.ExtractPrivateKey.main(ExtractPrivateKey.java:37)

                  Kindly I request you guys to give some inputs to move further on this.
                  • 6. Re: How to load an RSA private key from a file?
                    Hi, I have a similar problem.

                    I need to load an RSA private key in DER format from a file but, the private key is encrypted using PBE so I need to use the password to decrypt it.

                    My first question: if I'm using PBE can I change from PEM to DER format decoding the body and deleting the footer and header from Java???
                    My second question: how could I use the Class EncryptedPrivateKeyInfo to recover the private key using PBE?

                    I've searched for information about this but I can't find anything useful.

                    Thanks in advance.
                    • 7. Re: How to load an RSA private key from a file?
                      Welcome to the forum. Please don't post in threads that are long dead. When you have a question, start your own topic. Feel free to provide a link to an old post that may be relevant to your problem.

                      I'm locking this thread now.