{"id":885,"date":"2013-01-26T19:50:39","date_gmt":"2013-01-26T19:50:39","guid":{"rendered":"http:\/\/joelinoff.com\/blog\/?p=885"},"modified":"2026-06-28T17:38:13","modified_gmt":"2026-06-29T00:38:13","slug":"simple-python-functions-that-provide-openssl-aes-256-cbc-compatible-encryptdecrypt","status":"publish","type":"post","link":"https:\/\/joelinoff.com\/blog\/?p=885","title":{"rendered":"Simple python functions that provide openssl -aes-256-cbc compatible encrypt\/decrypt"},"content":{"rendered":"The example here shows how to encrypt and decrypt data using python in a way that is fully compatible with openssl aes-256-cbc. It is based on the work that I did in C++ Cipher class that is published on this site. It works for both python-2.7 and python-3.x.\n\nThe key idea is based on the way that openssl generates the key and iv data from password as well as the &#8220;Salted__&#8221; prefix that it uses.\n\nThe complete routine can be downloaded here: <a href=\"http:\/\/downloads.joelinoff.com\/mycrypt.py\" title=\"mycrypt.py\">mycrypt.py<\/a>.\n<!--more-->\nWhen you download the script from this section you will be able to perform operations like this.\n\n\n<pre class=\"wp-block-code language-bash\"><code class=\"language-bash\">$ # Encrypt and decrypt using mycrypt.py.\n$ echo 'Lorem ipsum dolor sit amet' |\\\n    .\/mycrypt.py -e -p secret |\\\n    .\/mycrypt.py -d -p secret\nLorem ipsum dolor sit amet\n\n$ # Encrypt using mycrypt.py and decrypt using openssl\n$ # with the SHA512 message digest.\n$ echo 'Lorem ipsum dolor sit amet' |\\\n    .\/mycrypt.py -e -m sha512 -p secret |\\\n    openssl enc -d -aes-256-cbc -md sha512 -base64 -salt -pass pass:secret\nLorem ipsum dolor sit amet\n\n$ # Encrypt using openssl and decrypt using mycrypt.py.\n$ echo 'Lorem ipsum dolor sit amet' |\\\n    openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secret |\\\n    .\/mycrypt.py -d -p secret\nLorem ipsum dolor sit amet\n\n$ # Encrypt and decrypt using openssl.\n    openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secret |\\\n    openssl enc -d -aes-256-cbc -md md5 -base64 -salt -pass pass:secret\nLorem ipsum dolor sit amet<\/code><\/pre>\n\n\n<h1>Basic Routines<\/h1>\nThe code shown below implements the encrypt and decrypt routines.\n\n\n<pre class=\"wp-block-code language-python\"><code class=\"language-python\">#!\/usr\/bin\/env python\n'''\nImplement openssl compatible AES-256 CBC mode encryption\/decryption.\n\nThis module provides encrypt() and decrypt() functions that are compatible\nwith the openssl algorithms.\n\nThis is basically a python encoding of my C++ work on the Cipher class\nusing the Crypto.Cipher.AES class.\n\nURL: http:\/\/projects.joelinoff.com\/cipher-1.1\/doxydocs\/html\/\n'''\n\n# LICENSE\n#\n# MIT Open Source\n#\n# Copyright (c) 2014 Joe Linoff\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation files\n# (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and\/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport argparse\nimport base64\nimport os\nimport re\nimport hashlib\nimport inspect\nimport sys\nfrom getpass import getpass\nfrom Crypto.Cipher import AES\n\nVERSION='1.2'\n\n\n# ================================================================\n# debug\n# ================================================================\ndef _debug(msg, lev=1):\n    '''\n    Print a debug message with some context.\n    '''\n    sys.stderr.write('DEBUG:{} ofp {}\\n'.format(inspect.stack()[lev][2], msg))\n\n\n# ================================================================\n# get_key_and_iv\n# ================================================================\ndef get_key_and_iv(password, salt, klen=32, ilen=16, msgdgst='md5'):\n    '''\n    Derive the key and the IV from the given password and salt.\n\n    This is a niftier implementation than my direct transliteration of\n    the C++ code although I modified to support different digests.\n\n    CITATION: http:\/\/stackoverflow.com\/questions\/13907841\/implement-openssl-aes-encryption-in-python\n\n    @param password  The password to use as the seed.\n    @param salt      The salt.\n    @param klen      The key length.\n    @param ilen      The initialization vector length.\n    @param msgdgst   The message digest algorithm to use.\n    '''\n    # equivalent to:\n    #   from hashlib import &lt;mdi&gt; as mdf\n    #   from hashlib import md5 as mdf\n    #   from hashlib import sha512 as mdf\n    mdf = getattr(__import__('hashlib', fromlist=[msgdgst]), msgdgst)\n    password = password.encode('ascii', 'ignore')  # convert to ASCII\n\n    try:\n        maxlen = klen + ilen\n        keyiv = mdf(password + salt).digest()\n        tmp = [keyiv]\n        while len(tmp) &lt; maxlen:\n            tmp.append( mdf(tmp[-1] + password + salt).digest() )\n            keyiv += tmp[-1]  # append the last byte\n        key = keyiv[:klen]\n        iv = keyiv[klen:klen+ilen]\n        return key, iv\n    except UnicodeDecodeError:\n        return None, None\n\n\n# ================================================================\n# encrypt\n# ================================================================\ndef encrypt(password, plaintext, chunkit=True, msgdgst='md5'):\n    '''\n    Encrypt the plaintext using the password using an openssl\n    compatible encryption algorithm. It is the same as creating a file\n    with plaintext contents and running openssl like this:\n\n    $ cat plaintext\n\n    $ openssl enc -e -aes-256-cbc -base64 -salt \\\\\n        -pass pass: -n plaintext\n\n    @param password  The password.\n    @param plaintext The plaintext to encrypt.\n    @param chunkit   Flag that tells encrypt to split the ciphertext\n                     into 64 character (MIME encoded) lines.\n                     This does not affect the decrypt operation.\n    @param msgdgst   The message digest algorithm.\n    '''\n    salt = os.urandom(8)\n    key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)\n    if key is None:\n        return None\n\n    # PKCS#7 padding\n    padding_len = 16 - (len(plaintext) % 16)\n    if isinstance(plaintext, str):\n        padded_plaintext = plaintext + (chr(padding_len) * padding_len)\n    else: # assume bytes\n        padded_plaintext = plaintext + (bytearray([padding_len] * padding_len))\n\n    # Encrypt\n    cipher = AES.new(key, AES.MODE_CBC, iv)\n    ciphertext = cipher.encrypt(padded_plaintext)\n\n    # Make openssl compatible.\n    # I first discovered this when I wrote the C++ Cipher class.\n    # CITATION: http:\/\/projects.joelinoff.com\/cipher-1.1\/doxydocs\/html\/\n    openssl_ciphertext = b'Salted__' + salt + ciphertext\n    b64 = base64.b64encode(openssl_ciphertext)\n    if not chunkit:\n        return b64\n\n    LINELEN = 64\n    chunk = lambda s: b'\\n'.join(s[i:min(i+LINELEN, len(s))]\n                                for i in range(0, len(s), LINELEN))\n    return chunk(b64)\n\n\n# ================================================================\n# decrypt\n# ================================================================\ndef decrypt(password, ciphertext, msgdgst='md5'):\n    '''\n    Decrypt the ciphertext using the password using an openssl\n    compatible decryption algorithm. It is the same as creating a file\n    with ciphertext contents and running openssl like this:\n\n    $ cat ciphertext\n    # ENCRYPTED\n    &lt;ciphertext&gt;\n    $ egrep -v '^#|^$' | \\\\\n        openssl enc -d -aes-256-cbc -base64 -salt -pass pass: -in ciphertext\n    @param password   The password.\n    @param ciphertext The ciphertext to decrypt.\n    @param msgdgst    The message digest algorithm.\n    @returns the decrypted data.\n    '''\n\n    # unfilter -- ignore blank lines and comments\n    if isinstance(ciphertext, str):\n        filtered = ''\n        nl = '\\n'\n        re1 = r'^\\s*$'\n        re2 = r'^\\s*#'\n    else:\n        filtered = b''\n        nl = b'\\n'\n        re1 = b'^\\\\s*$'\n        re2 = b'^\\\\s*#'\n\n    for line in ciphertext.split(nl):\n        line = line.strip()\n        if re.search(re1,line) or re.search(re2, line):\n            continue\n        filtered += line + nl\n\n    # Base64 decode\n    raw = base64.b64decode(filtered)\n    assert(raw[:8] == b'Salted__' )\n    salt = raw[8:16]  # get the salt\n\n    # Now create the key and iv.\n    key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)\n    if key is None:\n        return None\n\n    # The original ciphertext\n    ciphertext = raw[16:]\n\n    # Decrypt\n    cipher = AES.new(key, AES.MODE_CBC, iv)\n    padded_plaintext = cipher.decrypt(ciphertext)\n\n    if isinstance(padded_plaintext, str):\n        padding_len = ord(padded_plaintext[-1])\n    else:\n        padding_len = padded_plaintext[-1]\n    plaintext = padded_plaintext[:-padding_len]\n    return plaintext<\/code><\/pre>\n\n\n<h1>The Rest of the Program<\/h1>\nThe following code shows how to use the previous code to create tool that will encrypt and decrypt in the command line.\n\n\n<pre class=\"wp-block-code language-python\"><code class=\"language-python\"># include the code above ...\n# ================================================================\n# _open_ios\n# ================================================================\ndef _open_ios(args):\n    '''\n    Open the IO files.\n    '''\n    ifp = sys.stdin\n    ofp = sys.stdout\n\n    if args.input is not None:\n        try:\n            ifp = open(args.input, 'rb')\n        except IOError:\n            print('ERROR: cannot read file: {}'.format(args.input))\n            sys.exit(1)\n\n    if args.output is not None:\n        try:\n            ofp = open(args.output, 'wb')\n        except IOError:\n            print('ERROR: cannot write file: {}'.format(args.output))\n            sys.exit(1)\n\n    return ifp, ofp\n\n\n# ================================================================\n# _close_ios\n# ================================================================\ndef _close_ios(ifp, ofp):\n    '''\n    Close the IO files if necessary.\n    '''\n    if ifp != sys.stdin:\n        ifp.close()\n\n    if ofp != sys.stdout:\n        ofp.close()\n\n\n# ================================================================\n# _write\n# ================================================================\ndef _write(ofp, out, newline=False):\n    '''\n    Write out the data in the correct format.\n    '''\n    if ofp == sys.stdout and isinstance(out, bytes):\n        out = out.decode('utf-8', 'ignored')\n        ofp.write(out)\n        if newline:\n            ofp.write('\\n')\n    elif isinstance(out, str):\n        ofp.write(out)\n        if newline:\n            ofp.write('\\n')\n    else:  # assume bytes\n        ofp.write(out)\n        if newline:\n            ofp.write(b'\\n')\n\n\n# ================================================================\n# _write\n# ================================================================\ndef _read(ifp):\n    '''\n    Read the data in the correct format.\n    '''\n    return ifp.read()\n\n\n# ================================================================\n# _runenc\n# ================================================================\ndef _runenc(args):\n    '''\n    Encrypt data.\n    '''\n    if args.passphrase is None:\n        while True:\n            passphrase = getpass('Passphrase: ')\n            tmp = getpass('Re-enter passphrase: ')\n            if passphrase == tmp:\n                break\n            print('')\n            print('Passphrases do not match, please try again.')\n    else:\n        passphrase = args.passphrase\n\n    ifp, ofp = _open_ios(args)\n    text = _read(ifp)\n    out = encrypt(passphrase, text, msgdgst=args.msgdgst)\n    _write(ofp, out, True)\n    _close_ios(ifp, ofp)\n\n\n# ================================================================\n# _rundec\n# ================================================================\ndef _rundec(args):\n    '''\n    Decrypt data.\n    '''\n    if args.passphrase is None:\n        passphrase = getpass('Passphrase: ')\n    else:\n        passphrase = args.passphrase\n\n    ifp, ofp = _open_ios(args)\n    text = _read(ifp)\n    out = decrypt(passphrase, text, msgdgst=args.msgdgst)\n    _write(ofp, out, False)\n    _close_ios(ifp, ofp)\n\n\n# ================================================================\n# _runtest\n# ================================================================\ndef _runtest(args):\n    '''\n    Run a series of iteration where each iteration generates a random\n    password from 8-32 characters and random text from 20 to 256\n    characters. The encrypts and decrypts the random data. It then\n    compares the results to make sure that everything works correctly.\n\n    The test output looks like this:\n\n    $ crypt 2000\n    2000 of 2000 100.00%  15 139 2000    0\n    $ #     ^    ^        ^  ^   ^       ^\n    $ #     |    |        |  |   |       +-- num failed\n    $ #     |    |        |  |   +---------- num passed\n    $ #     |    |        |  +-------------- size of text for a test\n    $ #     |    |        +----------------- size of passphrase for a test\n    $ #     |    +-------------------------- percent completed\n    $ #     +------------------------------- total\n    # #+------------------------------------ current test\n\n    @param args  The args parse arguments.\n    '''\n    import string\n    import random\n    from random import randint\n\n    # Encrypt\/decrypt N random sets of plaintext and passwords.\n    num = args.test\n    ofp = sys.stdout\n    if args.output is not None:\n        try:\n            ofp = open(args.output, 'w')\n        except IOError:\n            print('ERROR: can open file for writing: {}'.format(args.output))\n            sys.exit(1)\n\n    chset = string.printable\n    passed = 0\n    failed = []\n    maxlen = len(str(num))\n    for i in range(num):\n        ran1 = randint(8,32)\n        password = ''.join(random.choice(chset) for x in range(ran1))\n\n        ran2 = randint(20, 256)\n        plaintext = ''.join(random.choice(chset) for x in range(ran2))\n\n        ciphertext = encrypt(password, plaintext, msgdgst=args.msgdgst)\n        verification = decrypt(password, ciphertext, msgdgst=args.msgdgst)\n\n        if plaintext != verification:\n            failed.append( [password, plaintext] )\n        else:\n            passed += 1\n\n        output = '%*d of %d %6.2f%% %3d %3d %*d %*d %s' % (maxlen,i+1,\n                                                           num,\n                                                           100*(i+1)\/num,\n                                                           len(password),\n                                                           len(plaintext),\n                                                           maxlen, passed,\n                                                           maxlen, len(failed),\n                                                           args.msgdgst)\n        if args.output is None:\n            ofp.write('\\b'*80)\n            ofp.write(output)\n            ofp.flush()\n        else:\n            ofp.write(output+'\\n')\n\n    ofp.write('\\n')\n\n    if len(failed):\n        for i in range(len(failed)):\n            ofp.write('%3d %2d %-34s %3d %s\\n' % (i,\n                                                  len(failed[i][0]),\n                                                  '\"'+failed[i][0]+'\"',\n                                                  len(failed[i][1]),\n                                                  '\"'+failed[i][1]+'\"'))\n        ofp.write('\\n')\n\n    if args.output is not None:\n        ofp.close()\n\n\n# ================================================================\n# _cli_opts\n# ================================================================\ndef _cli_opts():\n    '''\n    Parse command line options.\n    @returns the arguments\n    '''\n    mepath = os.path.abspath(sys.argv[0]).encode('utf-8')\n    mebase = os.path.basename(mepath)\n\n    description = '''\nImplements encryption\/decryption that is compatible with openssl\nAES-256 CBC mode.\n\nYou can use it as follows:\n\n    EXAMPLE 1: {0} -&gt; {0} (MD5)\n        $ # Encrypt and decrypt using {0}.\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            {0} -e -p secret | \\\\\n            {0} -d -p secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 2: {0} -&gt; openssl (MD5)\n        $ # Encrypt using {0} and decrypt using openssl.\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            {0} -e -p secret | \\\\\n            openssl enc -d -aes-256-cbc -md md5 -base64 -salt -pass pass:secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 3: openssl -&gt; {0} (MD5)\n        $ # Encrypt using openssl and decrypt using {0}\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secret\n            {0} -d -p secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 4: openssl -&gt; openssl (MD5)\n        $ # Encrypt and decrypt using openssl\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secret\n            openssl enc -d -aes-256-cbc -md md5 -base64 -salt -pass pass:secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 5: {0} -&gt; {0} (SHA512)\n        $ # Encrypt and decrypt using {0}.\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            {0} -e -m sha512 -p secret | \\\\\n            {0} -d -m sha512 -p secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 6: {0} -&gt; openssl (SHA512)\n        $ # Encrypt using {0} and decrypt using openssl.\n        $ echo 'Lorem ipsum dolor sit amet' | \\\\\n            {0} -e -m sha512 -p secret | \\\\\n            openssl enc -d -aes-256-cbc -md sha1=512 -base64 -salt -pass pass:secret\n        Lorem ipsum dolor sit amet\n\n    EXAMPLE 7:\n        $ # Run internal tests.\n        $ {0} -t 2000\n        2000 of 2000 100.00%%  21 104 2000    0 md5\n        $ #     ^    ^        ^  ^   ^       ^ ^\n        $ #     |    |        |  |   |       | +- message digest\n        $ #     |    |        |  |   |       +--- num failed\n        $ #     |    |        |  |   +----------- num passed\n        $ #     |    |        |  +--------------- size of text for a test\n        $ #     |    |        +------------------ size of passphrase for a test\n        $ #     |    +--------------------------- percent completed\n        $ #     +-------------------------------- total\n        # #+------------------------------------- current test\n'''.format(mebase.decode('ascii', 'ignore'))\n\n    parser = argparse.ArgumentParser(prog=mebase,\n                                     formatter_class=argparse.RawDescriptionHelpFormatter,\n                                     description=description,\n                                     )\n\n    group = parser.add_mutually_exclusive_group(required=True)\n    group.add_argument('-d', '--decrypt',\n                       action='store_true',\n                       help='decryption mode')\n    group.add_argument('-e', '--encrypt',\n                       action='store_true',\n                       help='encryption mode')\n    parser.add_argument('-i', '--input',\n                        action='store',\n                        help='input file, default is stdin')\n    parser.add_argument('-m', '--msgdgst',\n                        action='store',\n                        default='md5',\n                        help='message digest (md5, sha, sha1, sha256, sha512), default is md5')\n    parser.add_argument('-o', '--output',\n                        action='store',\n                        help='output file, default is stdout')\n    parser.add_argument('-p', '--passphrase',\n                        action='store',\n                        help='passphrase for encrypt\/decrypt operations')\n    group.add_argument('-t', '--test',\n                       action='store',\n                       default=-1,\n                       type=int,\n                       help='test mode (TEST is an integer)')\n    parser.add_argument('-v', '--verbose',\n                        action='count',\n                        help='the level of verbosity')\n    parser.add_argument('-V', '--version',\n                        action='version',\n                        version='%(prog)s '+VERSION)\n\n    args = parser.parse_args()\n    return args\n\n\n# ================================================================\n# main\n# ================================================================\ndef main():\n    args = _cli_opts()\n    if args.test &gt; 0:\n        if args.input is not None:\n            print('WARNING: input argument will be ignored.')\n        if args.passphrase is not None:\n            print('WARNING: passphrase argument will be ignored.')\n        _runtest(args)\n    elif args.encrypt:\n        _runenc(args)\n    elif args.decrypt:\n        _rundec(args)\n\n\n# ================================================================\n# MAIN\n# ================================================================\nif __name__ == \"__main__\":\n    main()<\/code><\/pre>\n\n\n\n","protected":false},"excerpt":{"rendered":"<p>The example here shows how to encrypt and decrypt data using python in a way that is fully compatible with openssl aes-256-cbc. It is based on the work that I did in C++ Cipher class that is published on this site. It works for both python-2.7 and python-3.x. The key idea is based on the &hellip; <a href=\"https:\/\/joelinoff.com\/blog\/?p=885\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Simple python functions that provide openssl -aes-256-cbc compatible encrypt\/decrypt<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[5,7,16],"tags":[],"class_list":["post-885","post","type-post","status-publish","format-standard","hentry","category-programming","category-python","category-sysadmin"],"_links":{"self":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/885","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=885"}],"version-history":[{"count":20,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/885\/revisions"}],"predecessor-version":[{"id":1783,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/885\/revisions\/1783"}],"wp:attachment":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=885"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=885"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=885"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}