原文链接:http://joelinoff.com/blog/?p=885

这里的示例显示了如何使用python以与openssl aes-256-cbc完全兼容的方式加密和解密数据。它是基于我在本网站上发布的C ++ Cipher类中所做的工作。它适用于python-2.7和python-3.x。

关键思想是基于openssl生成密钥和iv密码的数据以及它使用的“Salted__”前缀的方式。

因为我也掌握openssl的内部细节,所以先留着,等以后要是遇到需要了,在研究

使用方法

代码:

#!/usr/bin/env python
'''
Implement openssl compatible AES-256 CBC mode encryption/decryption.This module provides encrypt() and decrypt() functions that are compatible
with the openssl algorithms.This is basically a python encoding of my C++ work on the Cipher class
using the Crypto.Cipher.AES class.URL: http://projects.joelinoff.com/cipher-1.1/doxydocs/html/
'''# LICENSE
#
# MIT Open Source
#
# Copyright (c) 2014 Joe Linoff
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.import argparse
import base64
import os
import re
import hashlib
import inspect
import sys
from getpass import getpass
from Crypto.Cipher import AESVERSION='1.2'# ================================================================
# debug
# ================================================================
def _debug(msg, lev=1):'''Print a debug message with some context.'''sys.stderr.write('DEBUG:{} ofp {}\n'.format(inspect.stack()[lev][2], msg))# ================================================================
# get_key_and_iv
# ================================================================
def get_key_and_iv(password, salt, klen=32, ilen=16, msgdgst='md5'):'''Derive the key and the IV from the given password and salt.This is a niftier implementation than my direct transliteration ofthe C++ code although I modified to support different digests.CITATION: http://stackoverflow.com/questions/13907841/implement-openssl-aes-encryption-in-python@param password  The password to use as the seed.@param salt      The salt.@param klen      The key length.@param ilen      The initialization vector length.@param msgdgst   The message digest algorithm to use.'''# equivalent to:#   from hashlib import <mdi> as mdf#   from hashlib import md5 as mdf#   from hashlib import sha512 as mdfmdf = getattr(__import__('hashlib', fromlist=[msgdgst]), msgdgst)password = password.encode('ascii', 'ignore')  # convert to ASCIItry:maxlen = klen + ilenkeyiv = mdf(password + salt).digest()tmp = [keyiv]while len(tmp) < maxlen:tmp.append( mdf(tmp[-1] + password + salt).digest() )keyiv += tmp[-1]  # append the last bytekey = keyiv[:klen]iv = keyiv[klen:klen+ilen]return key, ivexcept UnicodeDecodeError:return None, None# ================================================================
# encrypt
# ================================================================
def encrypt(password, plaintext, chunkit=True, msgdgst='md5'):'''Encrypt the plaintext using the password using an opensslcompatible encryption algorithm. It is the same as creating a filewith plaintext contents and running openssl like this:$ cat plaintext<plaintext>$ openssl enc -e -aes-256-cbc -base64 -salt \\-pass pass:<password> -n plaintext@param password  The password.@param plaintext The plaintext to encrypt.@param chunkit   Flag that tells encrypt to split the ciphertextinto 64 character (MIME encoded) lines.This does not affect the decrypt operation.@param msgdgst   The message digest algorithm.'''salt = os.urandom(8)key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)if key is None:return None# PKCS#7 paddingpadding_len = 16 - (len(plaintext) % 16)if isinstance(plaintext, str):padded_plaintext = plaintext + (chr(padding_len) * padding_len)else: # assume bytespadded_plaintext = plaintext + (bytearray([padding_len] * padding_len))# Encryptcipher = AES.new(key, AES.MODE_CBC, iv)ciphertext = cipher.encrypt(padded_plaintext)# Make openssl compatible.# I first discovered this when I wrote the C++ Cipher class.# CITATION: http://projects.joelinoff.com/cipher-1.1/doxydocs/html/openssl_ciphertext = b'Salted__' + salt + ciphertextb64 = base64.b64encode(openssl_ciphertext)if not chunkit:return b64LINELEN = 64chunk = lambda s: b'\n'.join(s[i:min(i+LINELEN, len(s))]for i in range(0, len(s), LINELEN))return chunk(b64)# ================================================================
# decrypt
# ================================================================
def decrypt(password, ciphertext, msgdgst='md5'):'''Decrypt the ciphertext using the password using an opensslcompatible decryption algorithm. It is the same as creating a filewith ciphertext contents and running openssl like this:$ cat ciphertext# ENCRYPTED<ciphertext>$ egrep -v '^#|^$' | \\openssl enc -d -aes-256-cbc -base64 -salt -pass pass:<password> -in ciphertext@param password   The password.@param ciphertext The ciphertext to decrypt.@param msgdgst    The message digest algorithm.@returns the decrypted data.'''# unfilter -- ignore blank lines and commentsif isinstance(ciphertext, str):filtered = ''nl = '\n're1 = r'^\s*$'re2 = r'^\s*#'else:filtered = b''nl = b'\n're1 = b'^\\s*$'re2 = b'^\\s*#'for line in ciphertext.split(nl):line = line.strip()if re.search(re1,line) or re.search(re2, line):continuefiltered += line + nl# Base64 decoderaw = base64.b64decode(filtered)assert(raw[:8] == b'Salted__' )salt = raw[8:16]  # get the salt# Now create the key and iv.key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)if key is None:return None# The original ciphertextciphertext = raw[16:]# Decryptcipher = AES.new(key, AES.MODE_CBC, iv)padded_plaintext = cipher.decrypt(ciphertext)if isinstance(padded_plaintext, str):padding_len = ord(padded_plaintext[-1])else:padding_len = padded_plaintext[-1]plaintext = padded_plaintext[:-padding_len]return plaintext# include the code above ...
# ================================================================
# _open_ios
# ================================================================
def _open_ios(args):'''Open the IO files.'''ifp = sys.stdinofp = sys.stdoutif args.input is not None:try:ifp = open(args.input, 'rb')except IOError:print('ERROR: cannot read file: {}'.format(args.input))sys.exit(1)if args.output is not None:try:ofp = open(args.output, 'wb')except IOError:print('ERROR: cannot write file: {}'.format(args.output))sys.exit(1)return ifp, ofp# ================================================================
# _close_ios
# ================================================================
def _close_ios(ifp, ofp):'''Close the IO files if necessary.'''if ifp != sys.stdin:ifp.close()if ofp != sys.stdout:ofp.close()# ================================================================
# _write
# ================================================================
def _write(ofp, out, newline=False):'''Write out the data in the correct format.'''if ofp == sys.stdout and isinstance(out, bytes):out = out.decode('utf-8', 'ignored')ofp.write(out)if newline:ofp.write('\n')elif isinstance(out, str):ofp.write(out)if newline:ofp.write('\n')else:  # assume bytes
        ofp.write(out)if newline:ofp.write(b'\n')# ================================================================
# _write
# ================================================================
def _read(ifp):'''Read the data in the correct format.'''return ifp.read()# ================================================================
# _runenc
# ================================================================
def _runenc(args):'''Encrypt data.'''if args.passphrase is None:while True:passphrase = getpass('Passphrase: ')tmp = getpass('Re-enter passphrase: ')if passphrase == tmp:breakprint('')print('Passphrases do not match, please try again.')else:passphrase = args.passphraseifp, ofp = _open_ios(args)text = _read(ifp)out = encrypt(passphrase, text, msgdgst=args.msgdgst)_write(ofp, out, True)_close_ios(ifp, ofp)# ================================================================
# _rundec
# ================================================================
def _rundec(args):'''Decrypt data.'''if args.passphrase is None:passphrase = getpass('Passphrase: ')else:passphrase = args.passphraseifp, ofp = _open_ios(args)text = _read(ifp)out = decrypt(passphrase, text, msgdgst=args.msgdgst)_write(ofp, out, False)_close_ios(ifp, ofp)# ================================================================
# _runtest
# ================================================================
def _runtest(args):'''Run a series of iteration where each iteration generates a randompassword from 8-32 characters and random text from 20 to 256characters. The encrypts and decrypts the random data. It thencompares the results to make sure that everything works correctly.The test output looks like this:$ crypt 20002000 of 2000 100.00%  15 139 2000    0$ #     ^    ^        ^  ^   ^       ^$ #     |    |        |  |   |       +-- num failed$ #     |    |        |  |   +---------- num passed$ #     |    |        |  +-------------- size of text for a test$ #     |    |        +----------------- size of passphrase for a test$ #     |    +-------------------------- percent completed$ #     +------------------------------- total# #+------------------------------------ current test@param args  The args parse arguments.'''import stringimport randomfrom random import randint# Encrypt/decrypt N random sets of plaintext and passwords.num = args.testofp = sys.stdoutif args.output is not None:try:ofp = open(args.output, 'w')except IOError:print('ERROR: can open file for writing: {}'.format(args.output))sys.exit(1)chset = string.printablepassed = 0failed = []maxlen = len(str(num))for i in range(num):ran1 = randint(8,32)password = ''.join(random.choice(chset) for x in range(ran1))ran2 = randint(20, 256)plaintext = ''.join(random.choice(chset) for x in range(ran2))ciphertext = encrypt(password, plaintext, msgdgst=args.msgdgst)verification = decrypt(password, ciphertext, msgdgst=args.msgdgst)if plaintext != verification:failed.append( [password, plaintext] )else:passed += 1output = '%*d of %d %6.2f%% %3d %3d %*d %*d %s' % (maxlen,i+1,num,100*(i+1)/num,len(password),len(plaintext),maxlen, passed,maxlen, len(failed),args.msgdgst)if args.output is None:ofp.write('\b'*80)ofp.write(output)ofp.flush()else:ofp.write(output+'\n')ofp.write('\n')if len(failed):for i in range(len(failed)):ofp.write('%3d %2d %-34s %3d %s\n' % (i,len(failed[i][0]),'"'+failed[i][0]+'"',len(failed[i][1]),'"'+failed[i][1]+'"'))ofp.write('\n')if args.output is not None:ofp.close()# ================================================================
# _cli_opts
# ================================================================
def _cli_opts():'''Parse command line options.@returns the arguments'''mepath = os.path.abspath(sys.argv[0]).encode('utf-8')mebase = os.path.basename(mepath)description = '''Implements encryption/decryption that is compatible with opensslAES-256 CBC mode.You can use it as follows:EXAMPLE 1: {0} -> {0} (MD5)$ # Encrypt and decrypt using {0}.$ echo 'Lorem ipsum dolor sit amet' | \\{0} -e -p secret | \\{0} -d -p secretLorem ipsum dolor sit ametEXAMPLE 2: {0} -> openssl (MD5)$ # Encrypt using {0} and decrypt using openssl.$ echo 'Lorem ipsum dolor sit amet' | \\{0} -e -p secret | \\openssl enc -d -aes-256-cbc -md md5 -base64 -salt -pass pass:secretLorem ipsum dolor sit ametEXAMPLE 3: openssl -> {0} (MD5)$ # Encrypt using openssl and decrypt using {0}$ echo 'Lorem ipsum dolor sit amet' | \\openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secret{0} -d -p secretLorem ipsum dolor sit ametEXAMPLE 4: openssl -> openssl (MD5)$ # Encrypt and decrypt using openssl$ echo 'Lorem ipsum dolor sit amet' | \\openssl enc -e -aes-256-cbc -md md5 -base64 -salt -pass pass:secretopenssl enc -d -aes-256-cbc -md md5 -base64 -salt -pass pass:secretLorem ipsum dolor sit ametEXAMPLE 5: {0} -> {0} (SHA512)$ # Encrypt and decrypt using {0}.$ echo 'Lorem ipsum dolor sit amet' | \\{0} -e -m sha512 -p secret | \\{0} -d -m sha512 -p secretLorem ipsum dolor sit ametEXAMPLE 6: {0} -> openssl (SHA512)$ # Encrypt using {0} and decrypt using openssl.$ echo 'Lorem ipsum dolor sit amet' | \\{0} -e -m sha512 -p secret | \\openssl enc -d -aes-256-cbc -md sha1=512 -base64 -salt -pass pass:secretLorem ipsum dolor sit ametEXAMPLE 7:$ # Run internal tests.$ {0} -t 20002000 of 2000 100.00%%  21 104 2000    0 md5$ #     ^    ^        ^  ^   ^       ^ ^$ #     |    |        |  |   |       | +- message digest$ #     |    |        |  |   |       +--- num failed$ #     |    |        |  |   +----------- num passed$ #     |    |        |  +--------------- size of text for a test$ #     |    |        +------------------ size of passphrase for a test$ #     |    +--------------------------- percent completed$ #     +-------------------------------- total# #+------------------------------------- current test
'''.format(mebase.decode('ascii', 'ignore'))parser = argparse.ArgumentParser(prog=mebase,formatter_class=argparse.RawDescriptionHelpFormatter,description=description,)group = parser.add_mutually_exclusive_group(required=True)group.add_argument('-d', '--decrypt',action='store_true',help='decryption mode')group.add_argument('-e', '--encrypt',action='store_true',help='encryption mode')parser.add_argument('-i', '--input',action='store',help='input file, default is stdin')parser.add_argument('-m', '--msgdgst',action='store',default='md5',help='message digest (md5, sha, sha1, sha256, sha512), default is md5')parser.add_argument('-o', '--output',action='store',help='output file, default is stdout')parser.add_argument('-p', '--passphrase',action='store',help='passphrase for encrypt/decrypt operations')group.add_argument('-t', '--test',action='store',default=-1,type=int,help='test mode (TEST is an integer)')parser.add_argument('-v', '--verbose',action='count',help='the level of verbosity')parser.add_argument('-V', '--version',action='version',version='%(prog)s '+VERSION)args = parser.parse_args()return args# ================================================================
# main
# ================================================================
def main():args = _cli_opts()if args.test > 0:if args.input is not None:print('WARNING: input argument will be ignored.')if args.passphrase is not None:print('WARNING: passphrase argument will be ignored.')_runtest(args)elif args.encrypt:_runenc(args)elif args.decrypt:_rundec(args)# ================================================================
# MAIN
# ================================================================
if __name__ == "__main__":main()

View Code

提供openssl -aes-256-cbc兼容加密/解密的简单python函数相关推荐

  1. openssl 加盐_用盐打开Openssl AES 256 CBC Java Decrypt文件

    我已经尝试了几天用java解密用openssl加密的消息 . 使用以下命令加密消息: openssl enc -e -aes-256-cbc -kfile $ file.key -in toto -o ...

  2. php算法入门,a011.PHP实战:加密解密,简单算法入门

    原标题:a011.PHP实战:加密解密,简单算法入门 在PHP编程中,很多时候我们会遇到传递信息的问题,而传递过程中为了安全,我们肯定是要进行加密和解密的,这里,我们来说一说使用PHP怎么进行加密解密 ...

  3. python aes加密 cbc_Python实现AES的CBC模式加密和解密过程详解 和 chr() 函数 和 s[a:b:c] 和函数lambda...

    1.chr()函数 chr() 用一个范围在 range(256)内的(就是0-255)整数作参数,返回一个对应的字符. 2.s[a:b:c] s=(1,2,3,4,5) 1>. s[a]下标访 ...

  4. aes 256 cbc java,AES256加解密java语言实现

    AES256加解密java语言实现 写在前面 基于项目安全性需要,有时候我们的项目会使用AES 256加解密算法.以下,是针对实现AES256 Padding7加密算法实现的关键步骤解析以及此过程遇到 ...

  5. Linux的rsa命令,openssl命令行进行RSA加密解密

    openssl是一个功能强大的工具包,它集成了众多密码算法及实用工具.我们即可以利用它提供的命令台工具生成密钥.证书来加密解密文件,也可以在利用其提供的API接口在代码中对传输信息进行加密. RSA是 ...

  6. QT使用OpenSSL的DES/CBC/PKCS7加密字符串

    首先安装Openssl,然后QT项目的pro文件中添加引用 加密方法大部分来自:C++调用openssl实现DES加密解密cbc模式 zeropadding填充方式 pkcs5padding填充方式 ...

  7. go、JS AES(CBC模式)加密解密兼容

    js 代码: <!DOCTYPE html>   <html lang="en">   <head>       <meta charse ...

  8. AES加密解密(含python解析工具)

    url:https://web.ewt360.com/register/#/login 升学登录密码加密 aes简介: 密钥K:用来加密明文的密码,在对称加密算法中,加密与解密的密钥是相同的.密钥为接 ...

  9. python代码加密解密_在python中加密 – 在Javascript中解密

    您的Python代码和CryptoJS代码存在许多问题: >您使用随机IV加密Python中的一些明文.如果要检索该明文,则需要在解密期间使用相同的IV.没有IV,明文就无法恢复.通常,IV只是 ...

最新文章

  1. python怎么画心形图案_Python数学方程式画心型图案源码示例
  2. 使用腾讯云短信服务技术出现FailedOperation.TemplateIncorrectOrUnapproved
  3. 计算机常用的矢量图形文件,学位计算机考试2
  4. LINQ语句之Select/Distinct和Count/Sum/Min/Max/Avg
  5. 深度学习自学(二十二):人脸检测人脸识别-嵌入式平台方案汇总
  6. 知识图谱构建工具_自动构建知识图谱
  7. 卸载Windows下驱动并删除sys文件
  8. MFC中模拟按钮控件BN_CLICKED消息事件
  9. 【搜索引擎】Apache Solr 神经搜索
  10. 成长的路上总会有那么一群人
  11. 用计算机模拟沉船,古希腊沉船的宝物 安提凯希拉被称为古老的计算器
  12. 点线形系列1-计算两点之间的距离
  13. Js的Generator函数(一)
  14. 微信小程序商城购物车页 二维数组怎么做
  15. Windows相关系统性学习
  16. 我国计算机发展优势,浅析我国计算机应用发展.doc
  17. 【搞定Jvm面试】 JVM 垃圾回收揭秘附常见面试题解析
  18. SONY的IMX500浅谈
  19. ccsds ldpc matlab,CCSDS标准的LDPC编译码仿真
  20. NiuKe_SH17分玩具题

热门文章

  1. Java后端:Linux的基本使用学习笔记
  2. 删除表格数据后自动刷新_表格中一键即可删除重复数据,你居然还用逐条排查?...
  3. 关于synchronize与lock的区别
  4. Docker安装部署ELK教程 (Elasticsearch+Kibana+Logstash+Filebeat)
  5. halcon的算子清点:Chapter 7 :Image
  6. 关于jq+easy-ui 中上传文件所遇到的问题
  7. linux redhat、ubuntu系统 docker启动、停止命令
  8. html图片在ie中有边框,html – 表格的边框在IE中不起作用
  9. 串结构练习——字符串连接
  10. 15.泡菜:pickle模块