Skip to content

Unable to load pem pkcs8 encrypted private key which worked in v44 #12958

@deivse

Description

@deivse

Hi, I've encountered a possible regression with v45 with loading encrypted PEM private keys.
I confirmed that this works on v44, on v45 I'm getting the following exception from load_pem_private_key:

ValueError: Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters). Details: ASN.1 parsing error: invalid value

Here's a private key for replication (this is of course not used anywhere 😄): test_pkey.pem.txt, the password is "password".

The key is generated, encrypted and serialized with the following java code, using bouncycastle 1.70

public static KeyPair generateRsaKeyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(4096);
    return keyGenerator.generateKeyPair();
}

public static String serializePem(PemObjectGenerator generator) {
    StringWriter pemOut = new StringWriter();
    PemWriter pw = new PemWriter(pemOut);

    try {
        pw.writeObject(generator);
        pw.flush();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write Key to PEM.", e);
    }

    return pemOut.toString();
}

public static String toPemPkcs8(PrivateKey privateKey, char[] password) {
    JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES);
    encryptorBuilder.setPassword(password);
    OutputEncryptor outputEncryptor;
    try {
        outputEncryptor = encryptorBuilder.build();
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }

    try {
        return serializePem(new JcaPKCS8Generator(privateKey, outputEncryptor));
    } catch (PemGenerationException e) {
        throw new RuntimeException(e);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions