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

    How to load an RSA private key from a file?

    843811
      Hi,
      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.

      Thanks,
      Justin
        • 1. Re: How to load an RSA private key from a file?
          843811
                     File pubKeyFile = ...
                     File privKeyFile = ...
          
                     // read public key DER file
                      DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
                      byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
                      dis.readFully(pubKeyBytes);
                      dis.close();
                      
                      // read private key DER file
                      dis = new DataInputStream(new FileInputStream(privKeyFile));
                      byte[] privKeyBytes = new byte[(int)privKeyFile.length()];
                      dis.read(privKeyBytes);
                      dis.close();
                      
                      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:
          sabre150
          • 2. Re: How to load an RSA private key from a file?
            843811
            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

            [PRIVATE_KEY_GOES_HERE]

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

            [CERTIFICATE_REQUEST_INFORMATION_GOES_HERE]

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

            Thanks,
            Justin
            • 3. Re: How to load an RSA private key from a file?
              843811
              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.
              or
              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:
              sabre150
              • 4. Re: How to load an RSA private key from a file?
                843811
                Thank you very much -- that worked. My previous attempt of converting with openssl wasn't correct.

                Justin
                • 5. Re: How to load an RSA private key from a file?
                  843811
                  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-----
                  MIICXAIBAAKBgQDJutiaRQS8wDLoB1pcMfsACFSZKpYuHYBIoVRTo+yKLp9O42XT
                  kDIVkO2B05NzgdLZPhFWCHxWau4NJbPwTqaKvQ7AmIlmWjXsEaanbG2RnJNLdWgi
                  xLlDewH69Rt51MHiscLb8MEsa6k7TyF5fEGkV71ox3wRtLqHTWE98YPmAwIDAQAB
                  AoGAOMEOi2h7irbwG4NmEqYlHb86PdVTZyn5m3V4CggGVmIDg+hKD5lz3clmaK4j
                  v814ipIBwpikkpOG4cAHvcYC6GmDXT7ky691HgJjAVL0RTn7D95yWHcD6xZYD4KX
                  vFNBp2+FOZRomwe8vJbX7l77n/uLSrvOnSnD6HZ+dCj1/sECQQDt201MkO4KR7AV
                  N3AN7aPy+L5OJusLFkMGgyvn0NZTy+bJiPhdTHHeE3c8HM04qqBhM3NFypdFrcra
                  WYfvBGzTAkEA2R4V70colayuAusRocn8Lpyp9NLhPAFxG/PiQkHLpMFMDyYTF+kI
                  MJAf0/naoAg3GMmvNWvujrD1EHA5MokkEQJAf7PIUp1VUCug/CMhhDjcVyz5b5gx
                  hWhUYAC45+MVzzOgGv/w6JaMZADreVi1TgE9zjIDZ6sXgI+IY6bB9q/XhQJBAI7o
                  l6V8oAEMvSjckyl76sq/gbrNB0XY6RtuBvJ3nlQeizK5a/3j++kDJIABSF7nqWRe
                  dD3kggxX+6ZLR8q0rBECQBDwHdF8DW0xECPQlLczSk1z+sUOQiONIDZ9SFz7P8q6
                  IMUKSslXzYEMWvglhMUf0D7SCXyWwf/EEMgo+Qt9VUk=
                  -----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()];
                  dis.read(privKeyBytes);
                  dis.close();

                  // 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
                                 e.printStackTrace();
                            } catch (IOException e) {
                                 // TODO Auto-generated catch block
                                 e.printStackTrace();
                            } catch (NoSuchAlgorithmException e) {
                                 // TODO Auto-generated catch block
                                 e.printStackTrace();
                            } catch (InvalidKeySpecException e) {
                                 // TODO Auto-generated catch block
                                 e.printStackTrace();
                            }
                       }
                  }


                  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?
                    843811
                    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?
                      PhHein
                      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.