0

I am trying to generate an RSA private key via openssl. I use the following commands:

openssl genrsa -out rsaprivkey.pem 1024
openssl rsa -in rsaprivkey.pem -pubout -outform DER -out rsapubkey.dem
openssl pkcs8 -topk8 -outform PEM -in rsaprivkey.pem -inform PEM -out private.pk8
openssl req -new -x509 -key rsaprivkey.pem -out certificato.crt -subj "/C=IT/ST=Italia/L=Roma/O=xxxx/OU=xxxx/CN=xxxx"

i get all necessary files. The problem is that when I try to use the .pk8 file in my code, I get a java.lang.NullPointerException when I try to read the parameters that should be contained in the file (AlgorithmParameters params = epki.getAlgParameters();)

   //
        // The bytes just read are supposed to be in "EncryptedPrivateKeyInfo" info
        // The algorithm will have OID 1.2.840.113549.1.5.3 or be called "PBEWithMD5AndDES",
        // (actually, according to RFC2898, that would be "pbeWithMD5AndDES-CBC")
        // which means "Password Based Encryption Algorithm, uses Data Encryption Standard in
        // Cipher Block Chaining Mode (DES-CBC), uses MD5 to hash a password & salt to get Key
        // and Initialization Vector. Defined in RSA's PKCS#5". See RFC2898 for more.
        //
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(instream);
         System.out.println("Encrypted private key info's algorithm name : " + epki.getAlgName());

        AlgorithmParameters params = epki.getAlgParameters();
        {
                PBEParameterSpec pbeParams = (PBEParameterSpec) (params.getParameterSpec(PBEParameterSpec.class));
                Hex hex = new Hex();
                String salt = new String(hex.encode(pbeParams.getSalt()), "ASCII");
                 System.out.println("Encrypted private key info's salt           : 0x" + salt);
                 System.out.println("Encrypted private key info's iteration count: " + pbeParams.getIterationCount());
        }
        //
        // The 'keySpec' is transformed into a 'key' (to be used in a cipher) through a SecretKeyFactory
        // The password obtained earlier is used to generate a temporary "keySpec" that is used as
        // input to the SecretKeyFactory, then scratched again. What about the PBE algorithm parameter?
        // We don't need it here (empirically), but we *must* specify it later on in the cipher.        
        //
        Key encryptedKey = null;
  • Does this help? https://stackoverflow.com/questions/49932334/how-read-a-pkcs8-encrypted-private-key-which-is-also-encoded-in-der-with-bouncyc – pringi Feb 08 '22 at 15:52
  • I give it a try. Except that with a pk8 file they gave me it doesn't happen. The code works. So it's something during the generation that I'm wrong – Flavio Merolli Feb 08 '22 at 16:07

0 Answers0