Help with EncryptedPrivateKeyInfo

View: New views
3 Messages — Rating Filter:   Alert me  

Help with EncryptedPrivateKeyInfo

by Wong Mozqueda Jorge Arturo :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.

Hi I've just started with cryptography,

 

What I'm trying to do is to actualize some libraries that use bouncycastle to read private keys and certificates, this is part of that code that works fine with bc 1.15 that reads a private key from a file.

private static java.security.KeyPair obtenerLlavesFormatoDER(byte[] codigoASN1, char[] fraseDeSeguridad){

        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo informacionDeLlavePrivadaEncriptada;

 

         try{

            java.io.ByteArrayInputStream flujoDeBytes = new java.io.ByteArrayInputStream(codigoASN1);

            org.bouncycastle.asn1.ASN1InputStream flujoFormatoDER = new           org.bouncycastle.asn1.ASN1InputStream(flujoDeBytes);

           

            org.bouncycastle.asn1.DERSequence secuenciaDERllaveEncriptada;

            secuenciaDERllaveEncriptada = (org.bouncycastle.asn1.DERSequence) flujoFormatoDER.readObject();

            informacionDeLlavePrivadaEncriptada = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(secuenciaDERllaveEncriptada);

                

            flujoDeBytes.close();

            flujoFormatoDER.close();

        }catch (java.lang.Exception ex) {

            ex.printStackTrace();

        }

But this code is too complex and used and old version of bc, when I tried to actualize the libraries to the newest version of bc, the code showed a lot of errors in the casts.

 

I couldn't found examples of implementation using org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo so, I tried using javax.crypto.EncryptedPrivateKeyInfo in this code I found that is more simple and clear.

private static KeyPair obtenerLlavesFormatoDER(byte[] encryptedPKInfo, char[] password){
        KeyPair parDeLlaves = null;
        
        try {
                java.security.Security.addProvider(new BouncyCastleProvider());
                EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(
                                                        encryptedPKInfo);
                Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName(),"BC");
                PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
                SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo
                                                        .getAlgName(),"BC");
                cipher.init(Cipher.DECRYPT_MODE,
                        skFac.generateSecret(pbeKeySpec), ePKInfo.getAlgParameters());
                PKCS8EncodedKeySpec pkcs8Spec = ePKInfo.getKeySpec(cipher);
                KeyFactory          keyFact = KeyFactory.getInstance("RSA","BC");
                RSAPrivateCrtKey          privKey = (RSAPrivateCrtKey)keyFact.generatePrivate(pkcs8Spec);
                RSAPublicKeySpec rsaPubKeySpec = new RSAPublicKeySpec(privKey.getModulus(), privKey.getPublicExponent());
                RSAPublicKey rsaPubKey = (RSAPublicKey) keyFact.generatePublic(rsaPubKeySpec);
                
                parDeLlaves = new KeyPair(rsaPubKey, privKey);
            } catch (IOException ex) {
                ex.printStackTrace();
            }catch(NoSuchAlgorithmException ex){
                ex.printStackTrace();
            }catch(NoSuchPaddingException ex){
                ex.printStackTrace();
            }catch(NoSuchProviderException ex){
                ex.printStackTrace();
            }catch(InvalidAlgorithmParameterException ex){
                ex.printStackTrace();
            }catch(InvalidKeyException ex){
                ex.printStackTrace();
            }finally{
                return parDeLlaves;
            }
    }

But it launched a java.security.NoSuchAlgorithmException: No such algorithm: 1.2.840.113549.1.5.13 in the line

Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName(),"BC");

I have no evidence that the key is an instance of EncryptedPrivateKeyInfo but I ran out of ideas, do you have any suggestions about what can I do or example code??? I would appreciate any help, thanks in advance.

 


Parent Message unknown RE: Help with EncryptedPrivateKeyInfo

by Wong Mozqueda Jorge Arturo :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Maarten and everybody,

Sorry about the code, it's not mine but I'll change the variable names,

The code I sent is code that is working now but with an earlier version of bc (1.15), I wanted to simplify and actualize it to an newer version (1.43) with code I've found in David Hook's book but it's not working.

I'm trying to make the old code works with bc 1.43, this is my first try:

private static java.security.KeyPair EncryptedPrivateKeyInfoExample(byte[] data, char[] password){
   
      ByteArrayInputStream    bIn = new ByteArrayInputStream(data);
        ASN1InputStream         aIn = new ASN1InputStream(bIn);

    org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo encryptedPKInfo = null;
        try {
            encryptedPKInfo = new       org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) aIn.readObject());
      } catch (IOException ex) {
            ex.printStackTrace();
      }
      AlgorithmIdentifier algIdentifier = encryptedPKInfo.getEncryptionAlgorithm();
       
        PBKDF2Params pbkdf2Params = null;
      EncryptionScheme encryptionScheme = null;
           
      PBES2Parameters parameters = new PBES2Parameters((DERSequence)algIdentifier.getParameters());
           
      pbkdf2Params = (PBKDF2Params) parameters.getKeyDerivationFunc().getParameters();
      encryptionScheme = parameters.getEncryptionScheme();
           
           
      int iterationCount = pbkdf2Params.getIterationCount().intValue();
      byte[] salt = pbkdf2Params.getSalt();
      byte[] passwordPKCS5 = PBEParametersGenerator.PKCS5PasswordToBytes(password);
           
      PBEParametersGenerator PBEGenerator = new org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator();
      PBEGenerator.init(passwordPKCS5, salt, LongLlave3DES);
           
      DEROctetString encryptionSchemeASN1 = (DEROctetString)encryptionScheme.getObject();
      byte[] octetsIV = encryptionSchemeASN1.getOctets();
           
      CipherParameters derivedParameters = PBEGenerator.generateDerivedParameters(LongLlave3DES);
      CipherParameters derivedParametersIV = new org.bouncycastle.crypto.params.ParametersWithIV(derivedParameters, octetsIV);
           
      DESedeEngine tripleDESEngine = new DESedeEngine();
      CBCBlockCipher CBCmode = new CBCBlockCipher(tripleDESEngine);
           
      BufferedBlockCipher cryptographicCypher = new org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher(CBCmode);
      cryptographicCypher.init(false, derivedParametersIV);
           
      byte[] encryptedData = encryptedPKInfo.getEncryptedData();
      byte[] decryptedData = new byte[cryptographicCypher.getOutputSize(encryptedData.length)];
      int length = cryptographicCypher.processBytes(encryptedData, 0, encryptedData.length, decryptedData, 0);
      try{
      cryptographicCypher.doFinal(decryptedData, length);
      }catch(InvalidCipherTextException ex){
            ex.printStackTrace();
      }
}

But it launch an exception in the last try/catch

Is an org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted and I'm really clueless about why it is launching this exception.

I'd appreciate any help implementing org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.


-----Mensaje original-----
De: Maarten Bodewes [mailto:maarten.bodewes@...]
Enviado el: Martes, 03 de Noviembre de 2009 06:46 PM
Para: Wong Mozqueda Jorge Arturo
Asunto: Re: [dev-crypto] Help with EncryptedPrivateKeyInfo

Hi Jorge,

I've got little experience with PKCS#5, but you can easily lookup the
OID given in google. Then you get to the page:

http://www.alvestrand.no/objectid/1.2.840.113549.1.5.13.html

So this is PBES2 (which I do not have experience with at all).

However, there seems to be some code for the RSA test vectors in the class:

org.bouncycastle.crypto.test.PKCS5Test

Does anyone know why the PBES2 is not registered with the OID as
alias, or is this specific PBES2 algorithm missing from BC?

Hope that helps (a bit).

Regards,
Maarten

PS code/document in English if anywhere possible, your international
colleagues will like you for it

On Tue, Nov 3, 2009 at 6:21 PM, Wong Mozqueda Jorge Arturo
<jwong@...> wrote:

> Hi I've just started with cryptography,
>
>
>
> What I'm trying to do is to actualize some libraries that use bouncycastle
> to read private keys and certificates, this is part of that code that works
> fine with bc 1.15 that reads a private key from a file.
>
> private static java.security.KeyPair obtenerLlavesFormatoDER(byte[]
> codigoASN1, char[] fraseDeSeguridad){
>
>         org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo
> informacionDeLlavePrivadaEncriptada;
>
>
>
>          try{
>
>             java.io.ByteArrayInputStream flujoDeBytes = new
> java.io.ByteArrayInputStream(codigoASN1);
>
>             org.bouncycastle.asn1.ASN1InputStream flujoFormatoDER = new
>           org.bouncycastle.asn1.ASN1InputStream(flujoDeBytes);
>
>
>
>             org.bouncycastle.asn1.DERSequence secuenciaDERllaveEncriptada;
>
>             secuenciaDERllaveEncriptada =
> (org.bouncycastle.asn1.DERSequence) flujoFormatoDER.readObject();
>
>             informacionDeLlavePrivadaEncriptada = new
> org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(secuenciaDERllaveEncriptada);
>
>
>
>             flujoDeBytes.close();
>
>             flujoFormatoDER.close();
>
>         }catch (java.lang.Exception ex) {
>
>             ex.printStackTrace();
>
>         }
>
> But this code is too complex and used and old version of bc, when I tried to
> actualize the libraries to the newest version of bc, the code showed a lot
> of errors in the casts.
>
>
>
> I couldn't found examples of implementation using
> org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo so, I tried using
> javax.crypto.EncryptedPrivateKeyInfo in this code I found that is more
> simple and clear.
>
> private static KeyPair obtenerLlavesFormatoDER(byte[] encryptedPKInfo,
> char[] password){
>
>         KeyPair parDeLlaves = null;
>
>
>
>         try {
>
>                 java.security.Security.addProvider(new
> BouncyCastleProvider());
>
>                 EncryptedPrivateKeyInfo ePKInfo = new
> EncryptedPrivateKeyInfo(
>
>                                                         encryptedPKInfo);
>
>                 Cipher cipher =
> Cipher.getInstance(ePKInfo.getAlgName(),"BC");
>
>                 PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
>
>                 SecretKeyFactory skFac =
> SecretKeyFactory.getInstance(ePKInfo
>
>                                                         .getAlgName(),"BC");
>
>                 cipher.init(Cipher.DECRYPT_MODE,
>
>                         skFac.generateSecret(pbeKeySpec),
> ePKInfo.getAlgParameters());
>
>                 PKCS8EncodedKeySpec pkcs8Spec = ePKInfo.getKeySpec(cipher);
>
>                 KeyFactory          keyFact =
> KeyFactory.getInstance("RSA","BC");
>
>                 RSAPrivateCrtKey          privKey =
> (RSAPrivateCrtKey)keyFact.generatePrivate(pkcs8Spec);
>
>                 RSAPublicKeySpec rsaPubKeySpec = new
> RSAPublicKeySpec(privKey.getModulus(), privKey.getPublicExponent());
>
>                 RSAPublicKey rsaPubKey = (RSAPublicKey)
> keyFact.generatePublic(rsaPubKeySpec);
>
>
>
>                 parDeLlaves = new KeyPair(rsaPubKey, privKey);
>
>             } catch (IOException ex) {
>
>                 ex.printStackTrace();
>
>             }catch(NoSuchAlgorithmException ex){
>
>                 ex.printStackTrace();
>
>             }catch(NoSuchPaddingException ex){
>
>                 ex.printStackTrace();
>
>             }catch(NoSuchProviderException ex){
>
>                 ex.printStackTrace();
>
>             }catch(InvalidAlgorithmParameterException ex){
>
>                 ex.printStackTrace();
>
>             }catch(InvalidKeyException ex){
>
>                 ex.printStackTrace();
>
>             }finally{
>
>                 return parDeLlaves;
>
>             }
>
>     }
>
> But it launched a java.security.NoSuchAlgorithmException: No such algorithm:
> 1.2.840.113549.1.5.13 in the line
>
> Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName(),"BC");
>
> I have no evidence that the key is an instance of EncryptedPrivateKeyInfo
> but I ran out of ideas, do you have any suggestions about what can I do or
> example code??? I would appreciate any help, thanks in advance.
>
>

RE: Help with EncryptedPrivateKeyInfo

by David Hook-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Pad block corrupted either means that the data has been read wrongly (as
in it's base64 and it's been parsed as a binary), or the key is wrong.

It might help to look at the source for:

org.bouncycastle.jce.provider.test.EncryptedPrivateKeyInfoTest

Regards,

David

On Wed, 2009-11-04 at 10:18 -0600, Wong Mozqueda Jorge Arturo wrote:

> Hi Maarten and everybody,
>
> Sorry about the code, it's not mine but I'll change the variable names,
>
> The code I sent is code that is working now but with an earlier version of bc (1.15), I wanted to simplify and actualize it to an newer version (1.43) with code I've found in David Hook's book but it's not working.
>
> I'm trying to make the old code works with bc 1.43, this is my first try:
>
> private static java.security.KeyPair EncryptedPrivateKeyInfoExample(byte[] data, char[] password){
>    
>       ByteArrayInputStream    bIn = new ByteArrayInputStream(data);
> ASN1InputStream         aIn = new ASN1InputStream(bIn);
>
>     org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo encryptedPKInfo = null;
> try {
>             encryptedPKInfo = new       org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) aIn.readObject());
>       } catch (IOException ex) {
>             ex.printStackTrace();
>       }
>       AlgorithmIdentifier algIdentifier = encryptedPKInfo.getEncryptionAlgorithm();
>
> PBKDF2Params pbkdf2Params = null;
>       EncryptionScheme encryptionScheme = null;
>            
>       PBES2Parameters parameters = new PBES2Parameters((DERSequence)algIdentifier.getParameters());
>            
>       pbkdf2Params = (PBKDF2Params) parameters.getKeyDerivationFunc().getParameters();
>       encryptionScheme = parameters.getEncryptionScheme();
>            
>            
>       int iterationCount = pbkdf2Params.getIterationCount().intValue();
>       byte[] salt = pbkdf2Params.getSalt();
>       byte[] passwordPKCS5 = PBEParametersGenerator.PKCS5PasswordToBytes(password);
>            
>       PBEParametersGenerator PBEGenerator = new org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator();
>       PBEGenerator.init(passwordPKCS5, salt, LongLlave3DES);
>            
>       DEROctetString encryptionSchemeASN1 = (DEROctetString)encryptionScheme.getObject();
>       byte[] octetsIV = encryptionSchemeASN1.getOctets();
>            
>       CipherParameters derivedParameters = PBEGenerator.generateDerivedParameters(LongLlave3DES);
>       CipherParameters derivedParametersIV = new org.bouncycastle.crypto.params.ParametersWithIV(derivedParameters, octetsIV);
>            
>       DESedeEngine tripleDESEngine = new DESedeEngine();
>       CBCBlockCipher CBCmode = new CBCBlockCipher(tripleDESEngine);
>            
>       BufferedBlockCipher cryptographicCypher = new org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher(CBCmode);
>       cryptographicCypher.init(false, derivedParametersIV);
>            
>       byte[] encryptedData = encryptedPKInfo.getEncryptedData();
>       byte[] decryptedData = new byte[cryptographicCypher.getOutputSize(encryptedData.length)];
>       int length = cryptographicCypher.processBytes(encryptedData, 0, encryptedData.length, decryptedData, 0);
>       try{
>       cryptographicCypher.doFinal(decryptedData, length);
>       }catch(InvalidCipherTextException ex){
>             ex.printStackTrace();
>       }
> }
>
> But it launch an exception in the last try/catch
>
> Is an org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted and I'm really clueless about why it is launching this exception.
>
> I'd appreciate any help implementing org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.
>
>
> -----Mensaje original-----
> De: Maarten Bodewes [mailto:maarten.bodewes@...]
> Enviado el: Martes, 03 de Noviembre de 2009 06:46 PM
> Para: Wong Mozqueda Jorge Arturo
> Asunto: Re: [dev-crypto] Help with EncryptedPrivateKeyInfo
>
> Hi Jorge,
>
> I've got little experience with PKCS#5, but you can easily lookup the
> OID given in google. Then you get to the page:
>
> http://www.alvestrand.no/objectid/1.2.840.113549.1.5.13.html
>
> So this is PBES2 (which I do not have experience with at all).
>
> However, there seems to be some code for the RSA test vectors in the class:
>
> org.bouncycastle.crypto.test.PKCS5Test
>
> Does anyone know why the PBES2 is not registered with the OID as
> alias, or is this specific PBES2 algorithm missing from BC?
>
> Hope that helps (a bit).
>
> Regards,
> Maarten
>
> PS code/document in English if anywhere possible, your international
> colleagues will like you for it
>
> On Tue, Nov 3, 2009 at 6:21 PM, Wong Mozqueda Jorge Arturo
> <jwong@...> wrote:
> > Hi I've just started with cryptography,
> >
> >
> >
> > What I'm trying to do is to actualize some libraries that use bouncycastle
> > to read private keys and certificates, this is part of that code that works
> > fine with bc 1.15 that reads a private key from a file.
> >
> > private static java.security.KeyPair obtenerLlavesFormatoDER(byte[]
> > codigoASN1, char[] fraseDeSeguridad){
> >
> >         org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo
> > informacionDeLlavePrivadaEncriptada;
> >
> >
> >
> >          try{
> >
> >             java.io.ByteArrayInputStream flujoDeBytes = new
> > java.io.ByteArrayInputStream(codigoASN1);
> >
> >             org.bouncycastle.asn1.ASN1InputStream flujoFormatoDER = new
> >           org.bouncycastle.asn1.ASN1InputStream(flujoDeBytes);
> >
> >
> >
> >             org.bouncycastle.asn1.DERSequence secuenciaDERllaveEncriptada;
> >
> >             secuenciaDERllaveEncriptada =
> > (org.bouncycastle.asn1.DERSequence) flujoFormatoDER.readObject();
> >
> >             informacionDeLlavePrivadaEncriptada = new
> > org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(secuenciaDERllaveEncriptada);
> >
> >
> >
> >             flujoDeBytes.close();
> >
> >             flujoFormatoDER.close();
> >
> >         }catch (java.lang.Exception ex) {
> >
> >             ex.printStackTrace();
> >
> >         }
> >
> > But this code is too complex and used and old version of bc, when I tried to
> > actualize the libraries to the newest version of bc, the code showed a lot
> > of errors in the casts.
> >
> >
> >
> > I couldn't found examples of implementation using
> > org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo so, I tried using
> > javax.crypto.EncryptedPrivateKeyInfo in this code I found that is more
> > simple and clear.
> >
> > private static KeyPair obtenerLlavesFormatoDER(byte[] encryptedPKInfo,
> > char[] password){
> >
> >         KeyPair parDeLlaves = null;
> >
> >
> >
> >         try {
> >
> >                 java.security.Security.addProvider(new
> > BouncyCastleProvider());
> >
> >                 EncryptedPrivateKeyInfo ePKInfo = new
> > EncryptedPrivateKeyInfo(
> >
> >                                                         encryptedPKInfo);
> >
> >                 Cipher cipher =
> > Cipher.getInstance(ePKInfo.getAlgName(),"BC");
> >
> >                 PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
> >
> >                 SecretKeyFactory skFac =
> > SecretKeyFactory.getInstance(ePKInfo
> >
> >                                                         .getAlgName(),"BC");
> >
> >                 cipher.init(Cipher.DECRYPT_MODE,
> >
> >                         skFac.generateSecret(pbeKeySpec),
> > ePKInfo.getAlgParameters());
> >
> >                 PKCS8EncodedKeySpec pkcs8Spec = ePKInfo.getKeySpec(cipher);
> >
> >                 KeyFactory          keyFact =
> > KeyFactory.getInstance("RSA","BC");
> >
> >                 RSAPrivateCrtKey          privKey =
> > (RSAPrivateCrtKey)keyFact.generatePrivate(pkcs8Spec);
> >
> >                 RSAPublicKeySpec rsaPubKeySpec = new
> > RSAPublicKeySpec(privKey.getModulus(), privKey.getPublicExponent());
> >
> >                 RSAPublicKey rsaPubKey = (RSAPublicKey)
> > keyFact.generatePublic(rsaPubKeySpec);
> >
> >
> >
> >                 parDeLlaves = new KeyPair(rsaPubKey, privKey);
> >
> >             } catch (IOException ex) {
> >
> >                 ex.printStackTrace();
> >
> >             }catch(NoSuchAlgorithmException ex){
> >
> >                 ex.printStackTrace();
> >
> >             }catch(NoSuchPaddingException ex){
> >
> >                 ex.printStackTrace();
> >
> >             }catch(NoSuchProviderException ex){
> >
> >                 ex.printStackTrace();
> >
> >             }catch(InvalidAlgorithmParameterException ex){
> >
> >                 ex.printStackTrace();
> >
> >             }catch(InvalidKeyException ex){
> >
> >                 ex.printStackTrace();
> >
> >             }finally{
> >
> >                 return parDeLlaves;
> >
> >             }
> >
> >     }
> >
> > But it launched a java.security.NoSuchAlgorithmException: No such algorithm:
> > 1.2.840.113549.1.5.13 in the line
> >
> > Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName(),"BC");
> >
> > I have no evidence that the key is an instance of EncryptedPrivateKeyInfo
> > but I ran out of ideas, do you have any suggestions about what can I do or
> > example code??? I would appreciate any help, thanks in advance.
> >
> >