Jardo
Jardo

Reputation: 2093

Bouncycastle Loading of PKCS8 Encrypted Private Key Failing on JBoss

I'm trying to load an encrypted DSA private key with Bouncycastle.

The key is a pem file in the following format:

-----BEGIN ENCRYPTED PRIVATE KEY-----

    ....

-----END ENCRYPTED PRIVATE KEY-----

This is my Java code:

    Security.addProvider(new BouncyCastleProvider());

    ...    

    public PrivateKey loadKey(String fileName, String password) {

        try (PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8))) {

            PKCS8EncryptedPrivateKeyInfo encryptedKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();

            InputDecryptorProvider decryptorProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
            PrivateKeyInfo keyInfo = encryptedKeyInfo.decryptPrivateKeyInfo(decryptorProvider);

            JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
            return converter.getPrivateKey(keyInfo);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

When I try to load and use the key file on Windows (with JUnit), everything works.

But when I try to run the exact same code with the exact same key file and password on JBoss, I get the following exception:

org.bouncycastle.pkcs.PKCSException: unable to read encrypted data: javax.crypto.BadPaddingException: pad block corrupted
    at org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo.decryptPrivateKeyInfo(Unknown Source)
    at com.my.app.MyClass.loadKey(MyClass.java:106)
    ... 53 more
Caused by: java.io.IOException: javax.crypto.BadPaddingException: pad block corrupted
    at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:128)
    at javax.crypto.CipherInputStream.read(CipherInputStream.java:246)
    at org.bouncycastle.util.io.Streams.pipeAll(Unknown Source)
    at org.bouncycastle.util.io.Streams.readAll(Unknown Source)
    ... 55 more
Caused by: javax.crypto.BadPaddingException: pad block corrupted
    at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.doFinal(Unknown Source)
    at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
    at javax.crypto.Cipher.doFinal(Cipher.java:2047)
    at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:125)
    ... 58 more

Any ideas what might be wrong?

Upvotes: 1

Views: 704

Answers (0)

Related Questions