简体   繁体   中英

How to set cipher mode in pyOpenSSL?

I am trying to translate this cli command into python: openssl genpkey -aes-256-cbc -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out my-private-key.pem

So far, the best option I have found is pyOpenSSL, however, I cannot seem to set the cbc cipher mode. At the moment this is how my code looks:

gen_key = OpenSSL.crypto.PKey()

gen_key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)

OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, gen_key, cipher='aes256', passphrase=b"some_passphrase")

This however only specifies the cipher, not its mode. When I try to specify the cipher with cipher='aes256-cbc' or cipher='aescbc256' I get an invalid cipher name error. I would be extremely grateful if someone could help me setup my aes256 cipher to cbc mode.

For the ciphername argument, you can use the algorithm names printed out by the command openssl list -cipher-commands . There you will see mentioned aes-256-cbc , which is the name that you were looking for.

You can use those ciphers in a case insensitive way and most of them listed have aliases that you can use as well. For example if you use openssl -list -cipher-algorithms , you will notice

aes256 => AES-256-CBC

so it turns out you were using CBC mode already.

You can verify this also by feeding the generated PEM into the openssl asn1parse command, which starts like this (I added a print statement to the code to print the PEM):

$ python dumpkey.py | openssl asn1parse
    0:d=0  hl=4 l=1325 cons: SEQUENCE          
    4:d=1  hl=2 l=  87 cons: SEQUENCE          
    6:d=2  hl=2 l=   9 prim: OBJECT            :PBES2
   17:d=2  hl=2 l=  74 cons: SEQUENCE          
   19:d=3  hl=2 l=  41 cons: SEQUENCE          
   21:d=4  hl=2 l=   9 prim: OBJECT            :PBKDF2
   32:d=4  hl=2 l=  28 cons: SEQUENCE          
   34:d=5  hl=2 l=   8 prim: OCTET STRING      [HEX DUMP]:DAA5C15B1DB3C8CF
   44:d=5  hl=2 l=   2 prim: INTEGER           :0800
   48:d=5  hl=2 l=  12 cons: SEQUENCE          
   50:d=6  hl=2 l=   8 prim: OBJECT            :hmacWithSHA256
   60:d=6  hl=2 l=   0 prim: NULL              
   62:d=3  hl=2 l=  29 cons: SEQUENCE          
   64:d=4  hl=2 l=   9 prim: OBJECT            :aes-256-cbc

I do not know for sure whether all names mentioned in the list -cipher-commands are compatible with dump_privatekey() and also not whether that list is exhaustive (barring the aliases).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM