pyOpenSSL PKCS#12 with AES-256 encrypted private key

Viewed 11

What I'm trying to accomplish to accomplish when exporting a pfx-file from pyOpenSSL:

$ openssl pkcs12 -info -nodes -in test3.p12 -passin pass:test -noout
MAC:sha256 Iteration 1024
PKCS7 Data
Shrouded Keybag: PBES2, PBKDF2, AES-256-CBC, Iteration 100000, PRF hmacWithSHA256
PKCS7 Encrypted data: pbeWithSHA1And128BitRC2-CBC, Iteration 50000

But from my understanding when reading the functions in the library is that you can't specify the encryption type when exporting the pfx-file.

This is pretty much what I'm doing right now as of exporting:

def pem_to_pfx(self, pem_ca_path, pem_path, encrypted_key_path, p12_path, new_pwd_pfx_path):

    length = int(24)

    ## characters to generate password from
    characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")

    ## shuffling the characters
    random.shuffle(characters)

    ## picking random characters from the list
    password = []
    for i in range(length):
        password.append(random.choice(characters))

    ## shuffling the resultant password
    random.shuffle(password)

    ## converting the list to string
    passphrase_pfx = ''.join(str(e) for e in password)

    ## printing the list
    # print("".join(passphrase_pfx))

    file_name = new_pwd_pfx_path
    with open(file_name, 'w') as x_file:
        x_file.write(passphrase_pfx)
        x_file.close()

    with open(encrypted_key_path, 'rb') as f:
        encrypted_key_file = f.read()
    with open(pem_ca_path, 'r') as f:
        ca_cert_file = f.read()
    with open(pem_path, 'r') as f:
        user_cert_file = f.read()
    ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert_file)
    user_cert = crypto.load_certificate(crypto.FILETYPE_PEM, user_cert_file)
    encrypted_key = crypto.load_privatekey(crypto.FILETYPE_PEM, encrypted_key_file, passphrase=passphrase.encode('ascii'))
    p12 = OpenSSL.crypto.PKCS12()
    p12.set_privatekey(encrypted_key)
    p12.set_ca_certificates([ca_cert, user_cert])
    #p12.set_certificate(user_cert)
    open(p12_path, 'wb').write(p12.export(maciter=1024, iter=100000, passphrase=passphrase_pfx))

    if os.path.exists(pem_path):
        os.remove(pem_path)

    if os.path.exists(pem_ca_path):
        os.remove(pem_ca_path)

    if os.path.exists(encrypted_key_path):
        os.remove(encrypted_key_path)

Is it posible to accomplish something similar to the openssl output above in this library?

0 Answers
Related