String to Private Key

classic Classic list List threaded Threaded
7 messages Options
Reply | Threaded
Open this post in threaded view
|

String to Private Key

Juan Carlos González Sosa

Hello, I just started using bouncy castle tonight and can’t seem to figure it out.

 

I’m trying to make a web server with java on which I ask for a private key to encode a String.

 

Right now I have the following:

 

if (filePart != null && filePart.getSubmittedFileName() != null && !filePart.getSubmittedFileName().equals("")) {

                //Read the file and get it on a variable  

 ByteArrayOutputStream out = null;

                    InputStream fileContent = null;

                    try {

                        out = new ByteArrayOutputStream();

                        fileContent = filePart.getInputStream();

                        int read = 0;

                        final byte[] bytes = new byte[1024];

                        while ((read = fileContent.read(bytes)) != -1) {

                            out.write(bytes, 0, read);

                        }

 

                        privateKey=getPrivateKeyFromString(out.toString());        //Can something like this be done with BouncyCastles?

                   

} catch (FileNotFoundException ex) {

                        logger.info(ex.toString());

                    } catch (IOException ex) {

                        Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);

                    } catch (Exception ex) {

                        Logger.getLogger(HomeController.class.getName()).log(Level.SEVERE, null, ex);

                    } finally {

                        if (out != null) {

                            out.close();

                        }

                        if (fileContent != null) {

                            fileContent.close();

                        }

                    }

 

I tried looking on documentation and a bit on google but I think people don’t generally ask for a private key on a web server. I do.

 

Thanks for the help.

Juan Gonzalez



Este mensaje y sus anexos pueden contener informacion confidencial. Si usted no es el destinatario de este mensaje, se le notifica que cualquier revision, retransmision, distribucion, copiado u otro uso o acto realizado con base en o relacionado con el contenido de este mensaje y sus anexos, estan prohibidos. Si usted ha recibido este mensaje y sus anexos por error, le suplicamos lo notifique al remitente respondiendo el presente correo electronico y borre el presente y sus anexos de su sistema sin conservar copia de los mismos. Muchas gracias.

This message and the attachments to it may contain information which is confidential. if your are not the intended recipient(s) for this message, you are on notice that any review, retransmission, dissemination, distribution, copying or other use or taking any action based upon or relative to the information contained in this message and its attachments, is prohibited. If you are not the intended recipient(s) of this message or its attachments, please immediately advise the sender by reply e-mail and delete this message and its attachments from your system without keeping a copy. Thank you.
Reply | Threaded
Open this post in threaded view
|

Re: String to Private Key

Lothar Kimmeringer-4
Hi,

Am 22.04.2017 um 01:02 schrieb Juan Carlos González Sosa:

>                         *privateKey=getPrivateKeyFromString(out.toString());
>        //Can something like this be done with BouncyCastles?*

first of all: out.toString() is bad, don't do that but use the method that
allows you to provide a charset and use the correct one. Alternatively
create a reader or take the one that might be available by a method in filePart.

About your question: I don't know of a single method that simply creates a
private key from some binary blob (there are binary formats that aren't text-
based so you shouldn't convert the file into a string anyway.

I implemented my own method peeking into the binary data to do an educated
guess and read the private key in dependence of the outcome of this guess.
Maybe newer versions of BC (I created that code more than ten years ago)
have something similar so another answer might bring that up.

But for starters: Do you restict the format to be uploaded to the web-
server? If you only accept PEM-encoded data you can use PEMParser. Here
the code that would create a private key from PEM-encoded data:


     /**
      * Reads a private key from PEM encoded data
      * @param keydata The data to create the key from
      * @param passphrase The passphrase to be used for decrypting the key or
      * <code>null</code> if no decryption is necessary
      * @return The decoded private key as a key pair. There is no guarantee that
      * a public key is part of the pair as well
      * @throws IOException Will be thrown if there was an error
      * while reading from the stream
      */
     public static KeyPair readPEMKey(String keydata, final char[] passphrase) throws IOException {
         PEMParser pemReader = new PEMParser(new StringReader(keydata));
         try{
             Object key = pemReader.readObject();
             if (key instanceof PEMEncryptedKeyPair){
                 PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider(BC_PROVIDER).build(passphrase);
                 key = ((PEMEncryptedKeyPair) key).decryptKeyPair(decProv);
             }
             PEMKeyPair keyPair = (PEMKeyPair) key;
             return BC_PEM_KEY_CONVERTER.getKeyPair(keyPair);
         }
         finally{
             pemReader.close();
         }
     }

BC_PEM_KEY_CONVERTER is an instance of JcaPEMKeyConverter.

Binary formats are a bit more complicated since you need to find out if we're
talking about a DER-encoded RSA or DH private key or a PKCS#12 keystore, etc.


Cheers, Lothar

Reply | Threaded
Open this post in threaded view
|

RE: String to Private Key

Juan Carlos González Sosa
Hi Lothar,

Thank you for your answer, it was enlightening. I will restrict the format of the private key to a .pem so I can use this implementation.

I'm having trouble finding and importing the following classes:
PEMParser, PEMEncryptedKeyPair, PEMDecryptorProvider, JcePEMDecryptorProviderBuilder, PEMEncryptedKeyPair, PEMKeyPair

I'm sorry I really am a newbie

-----Mensaje original-----
De: Lothar Kimmeringer [mailto:[hidden email]]
Enviado el: domingo, 23 de abril de 2017 03:06 p.m.
Para: [hidden email]
Asunto: Re: [dev-crypto] String to Private Key

Hi,

Am 22.04.2017 um 01:02 schrieb Juan Carlos González Sosa:

>                         *privateKey=getPrivateKeyFromString(out.toString());
>        //Can something like this be done with BouncyCastles?*

first of all: out.toString() is bad, don't do that but use the method that allows you to provide a charset and use the correct one. Alternatively create a reader or take the one that might be available by a method in filePart.

About your question: I don't know of a single method that simply creates a private key from some binary blob (there are binary formats that aren't text- based so you shouldn't convert the file into a string anyway.

I implemented my own method peeking into the binary data to do an educated guess and read the private key in dependence of the outcome of this guess.
Maybe newer versions of BC (I created that code more than ten years ago) have something similar so another answer might bring that up.

But for starters: Do you restict the format to be uploaded to the web- server? If you only accept PEM-encoded data you can use PEMParser. Here the code that would create a private key from PEM-encoded data:


     /**
      * Reads a private key from PEM encoded data
      * @param keydata The data to create the key from
      * @param passphrase The passphrase to be used for decrypting the key or
      * <code>null</code> if no decryption is necessary
      * @return The decoded private key as a key pair. There is no guarantee that
      * a public key is part of the pair as well
      * @throws IOException Will be thrown if there was an error
      * while reading from the stream
      */
     public static KeyPair readPEMKey(String keydata, final char[] passphrase) throws IOException {
         PEMParser pemReader = new PEMParser(new StringReader(keydata));
         try{
             Object key = pemReader.readObject();
             if (key instanceof PEMEncryptedKeyPair){
                 PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider(BC_PROVIDER).build(passphrase);
                 key = ((PEMEncryptedKeyPair) key).decryptKeyPair(decProv);
             }
             PEMKeyPair keyPair = (PEMKeyPair) key;
             return BC_PEM_KEY_CONVERTER.getKeyPair(keyPair);
         }
         finally{
             pemReader.close();
         }
     }

BC_PEM_KEY_CONVERTER is an instance of JcaPEMKeyConverter.

Binary formats are a bit more complicated since you need to find out if we're talking about a DER-encoded RSA or DH private key or a PKCS#12 keystore, etc.


Cheers, Lothar


Este mensaje y sus anexos pueden contener informacion confidencial. Si usted no es el destinatario de este mensaje, se le notifica que cualquier revision, retransmision, distribucion, copiado u otro uso o acto realizado con base en o relacionado con el contenido de este mensaje y sus anexos, estan prohibidos. Si usted ha recibido este mensaje y sus anexos por error, le suplicamos lo notifique al remitente respondiendo el presente correo electronico y borre el presente y sus anexos de su sistema sin conservar copia de los mismos. Muchas gracias.

This message and the attachments to it may contain information which is confidential. if your are not the intended recipient(s) for this message, you are on notice that any review, retransmission, dissemination, distribution, copying or other use or taking any action based upon or relative to the information contained in this message and its attachments, is prohibited. If you are not the intended recipient(s) of this message or its attachments, please immediately advise the sender by reply e-mail and delete this message and its attachments from your system without keeping a copy. Thank you.



Reply | Threaded
Open this post in threaded view
|

RE: String to Private Key

George Stanchev
Juan,

If you post your question on StackOverflow, perhaps you will have better luck finding answers. Just a suggestion. Good luck in your effort.

George

-----Original Message-----
From: Juan Carlos González Sosa [mailto:[hidden email]]
Sent: Monday, April 24, 2017 5:55 PM
To: [hidden email]
Subject: RE: [dev-crypto] String to Private Key

Hi Lothar,

Thank you for your answer, it was enlightening. I will restrict the format of the private key to a .pem so I can use this implementation.

I'm having trouble finding and importing the following classes:
PEMParser, PEMEncryptedKeyPair, PEMDecryptorProvider, JcePEMDecryptorProviderBuilder, PEMEncryptedKeyPair, PEMKeyPair

I'm sorry I really am a newbie

-----Mensaje original-----
De: Lothar Kimmeringer [mailto:[hidden email]] Enviado el: domingo, 23 de abril de 2017 03:06 p.m.
Para: [hidden email]
Asunto: Re: [dev-crypto] String to Private Key

Hi,

Am 22.04.2017 um 01:02 schrieb Juan Carlos González Sosa:

>                         *privateKey=getPrivateKeyFromString(out.toString());
>        //Can something like this be done with BouncyCastles?*

first of all: out.toString() is bad, don't do that but use the method that allows you to provide a charset and use the correct one. Alternatively create a reader or take the one that might be available by a method in filePart.

About your question: I don't know of a single method that simply creates a private key from some binary blob (there are binary formats that aren't text- based so you shouldn't convert the file into a string anyway.

I implemented my own method peeking into the binary data to do an educated guess and read the private key in dependence of the outcome of this guess.
Maybe newer versions of BC (I created that code more than ten years ago) have something similar so another answer might bring that up.

But for starters: Do you restict the format to be uploaded to the web- server? If you only accept PEM-encoded data you can use PEMParser. Here the code that would create a private key from PEM-encoded data:


     /**
      * Reads a private key from PEM encoded data
      * @param keydata The data to create the key from
      * @param passphrase The passphrase to be used for decrypting the key or
      * <code>null</code> if no decryption is necessary
      * @return The decoded private key as a key pair. There is no guarantee that
      * a public key is part of the pair as well
      * @throws IOException Will be thrown if there was an error
      * while reading from the stream
      */
     public static KeyPair readPEMKey(String keydata, final char[] passphrase) throws IOException {
         PEMParser pemReader = new PEMParser(new StringReader(keydata));
         try{
             Object key = pemReader.readObject();
             if (key instanceof PEMEncryptedKeyPair){
                 PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider(BC_PROVIDER).build(passphrase);
                 key = ((PEMEncryptedKeyPair) key).decryptKeyPair(decProv);
             }
             PEMKeyPair keyPair = (PEMKeyPair) key;
             return BC_PEM_KEY_CONVERTER.getKeyPair(keyPair);
         }
         finally{
             pemReader.close();
         }
     }

BC_PEM_KEY_CONVERTER is an instance of JcaPEMKeyConverter.

Binary formats are a bit more complicated since you need to find out if we're talking about a DER-encoded RSA or DH private key or a PKCS#12 keystore, etc.


Cheers, Lothar


Este mensaje y sus anexos pueden contener informacion confidencial. Si usted no es el destinatario de este mensaje, se le notifica que cualquier revision, retransmision, distribucion, copiado u otro uso o acto realizado con base en o relacionado con el contenido de este mensaje y sus anexos, estan prohibidos. Si usted ha recibido este mensaje y sus anexos por error, le suplicamos lo notifique al remitente respondiendo el presente correo electronico y borre el presente y sus anexos de su sistema sin conservar copia de los mismos. Muchas gracias.

This message and the attachments to it may contain information which is confidential. if your are not the intended recipient(s) for this message, you are on notice that any review, retransmission, dissemination, distribution, copying or other use or taking any action based upon or relative to the information contained in this message and its attachments, is prohibited. If you are not the intended recipient(s) of this message or its attachments, please immediately advise the sender by reply e-mail and delete this message and its attachments from your system without keeping a copy. Thank you.




Reply | Threaded
Open this post in threaded view
|

Re: String to Private Key

Lothar Kimmeringer-4
In reply to this post by Juan Carlos González Sosa
Hi,

Am 25.04.2017 um 01:54 schrieb Juan Carlos González Sosa:

> I'm having trouble finding and importing the following classes:
> PEMParser, PEMEncryptedKeyPair, PEMDecryptorProvider, JcePEMDecryptorProviderBuilder, PEMEncryptedKeyPair, PEMKeyPair

what version of BouncyCastle are you using? There has been a change in class names
and if you can't find the given names you might use a deprecated one.


Cheers, Lothar

Reply | Threaded
Open this post in threaded view
|

Re: String to Private Key

David Hook-3

Also, are you using the bcpkix jar as well? These classes are not in the
provider jar.

Regards,

David

On 25/04/17 17:18, Lothar Kimmeringer wrote:

> Hi,
>
> Am 25.04.2017 um 01:54 schrieb Juan Carlos González Sosa:
>
>> I'm having trouble finding and importing the following classes:
>> PEMParser, PEMEncryptedKeyPair, PEMDecryptorProvider,
>> JcePEMDecryptorProviderBuilder, PEMEncryptedKeyPair, PEMKeyPair
>
> what version of BouncyCastle are you using? There has been a change in
> class names
> and if you can't find the given names you might use a deprecated one.
>
>
> Cheers, Lothar
>
>


Reply | Threaded
Open this post in threaded view
|

RE: String to Private Key

Juan Carlos González Sosa
I used a version that supports the import of those clases and was able to implement your code.

Thanks a bunch!

Kind regards,
 Juan Carlos

-----Mensaje original-----
De: David Hook [mailto:[hidden email]]
Enviado el: martes, 25 de abril de 2017 05:05 p.m.
Para: [hidden email]
Asunto: Re: [dev-crypto] String to Private Key


Also, are you using the bcpkix jar as well? These classes are not in the provider jar.

Regards,

David

On 25/04/17 17:18, Lothar Kimmeringer wrote:

> Hi,
>
> Am 25.04.2017 um 01:54 schrieb Juan Carlos González Sosa:
>
>> I'm having trouble finding and importing the following classes:
>> PEMParser, PEMEncryptedKeyPair, PEMDecryptorProvider,
>> JcePEMDecryptorProviderBuilder, PEMEncryptedKeyPair, PEMKeyPair
>
> what version of BouncyCastle are you using? There has been a change in
> class names and if you can't find the given names you might use a
> deprecated one.
>
>
> Cheers, Lothar
>
>



Este mensaje y sus anexos pueden contener informacion confidencial. Si usted no es el destinatario de este mensaje, se le notifica que cualquier revision, retransmision, distribucion, copiado u otro uso o acto realizado con base en o relacionado con el contenido de este mensaje y sus anexos, estan prohibidos. Si usted ha recibido este mensaje y sus anexos por error, le suplicamos lo notifique al remitente respondiendo el presente correo electronico y borre el presente y sus anexos de su sistema sin conservar copia de los mismos. Muchas gracias.

This message and the attachments to it may contain information which is confidential. if your are not the intended recipient(s) for this message, you are on notice that any review, retransmission, dissemination, distribution, copying or other use or taking any action based upon or relative to the information contained in this message and its attachments, is prohibited. If you are not the intended recipient(s) of this message or its attachments, please immediately advise the sender by reply e-mail and delete this message and its attachments from your system without keeping a copy. Thank you.