Python Crypto.Cipher加密包

The Crypto.Cipher package contains algorithms for protecting the confidentiality of data.

Crypto.Cipher包含保护机密数据的加密算法。

Installation(安装)

  1. an almost drop-in replacement for the old PyCrypto library. You install it with:
    替换旧版本PyCrypto库安装

    pip install pycryptodome
    
  2. a library independent of the old PyCrypto. You install it with:
    独立于旧版本PyCrypto库的安装

    pip install pycryptodomex
    

Introduction(介绍)

There are three types of encryption algorithms:
Crypto.Cipher包含三种加密算法

  • Symmetric ciphers: all parties use the same key, for both decrypting and encrypting data. Symmetric ciphers are typically very fast and can process very large amount of data.
    对称加密算法:加解密数据使用同一秘钥,对称加密算法速度极快,能够快速处理非常庞大的数据。

  • Asymmetric ciphers: senders and receivers use different keys. Senders encrypt with public keys (non-secret) whereas receivers decrypt with private keys (secret). Asymmetric ciphers are typically very slow and can process only very small payloads. Example: PKCS#1 OAEP (RSA).
    非对称加密算法:发送者与接收者使用不同的秘钥,发送者使用公钥(非密)加密而接收者使用私钥解密。非对称加密算法速度很慢,只能够处理非常少的有效载荷(数据)。例如PKCS#1 OAEP (RSA)。

  • Hybrid ciphers: the two types of ciphers above can be combined in a construction that inherits the benefits of both. An asymmetric cipher is used to protect a short-lived symmetric key, and a symmetric cipher (under that key) encrypts the actual message.
    混合型加密算法:结合以上两种加密算法的优势。非对称加密算法经常被用来保护短活的对称秘钥,对称加密算法(使用对称秘钥)加密真实的信息。

基本的cipher API

You instantiate a cipher object by calling the new() function from the relevant cipher module (e.g. Crypto.Cipher.AES.new()). The first parameter is always the cryptographic key; its length depends on the particular cipher. You can (and sometimes must) pass additional cipher- or mode-specific parameters to new() (such as a nonce or a mode of operation).

通过从相关的cipher模块中调用new()函数实例化一个cipher对象(e.g. Crypto.Cipher.AES.new()),第一个参数是秘钥,长度取决于具体的加密算法,也可以(有时必须)传递额外的参数(随机数或者操作模式)

For encrypting, you call the encrypt() method of the cipher object with the plaintext. The method returns the piece of ciphertext. For most algorithms, you may call encrypt() multiple times (i.e. once for each piece of plaintext).

加密的时候直接调用实例的encrypt()方法,传递明文文本参数,结果返回一段加密文本,对于大多数的算法,可以多次调用encrypt()方法(例如对于每个片段调用一次)

For decrypting, you call the decrypt() method of the cipher object with the ciphertext. The method returns the piece of plaintext. For most algorithms, you may call decrypt() multiple times (i.e. once for each piece of ciphertext).

解密的时候直接调用decrypt(),传递明文文本参数,结果返回一段明文文本,对于大多数的算法,可以多次调用decrypt()方法(例如对于每个片段调用一次)

一个最基本的例子

注意

Plaintexts and ciphertexts (input/output) are all byte strings. An error will occur with Python 3 strings, Python 2 Unicode strings, or byte arrays.
明文与加密文本(输入输出)都是字节字符,对于python3字符或者python2 Unicode字符或者字节数组会发生错误。

更过的例子

Salsa20 is a stream cipher designed by Daniel J. Bernstein. The secret key is by preference 256 bits long, but it can also work with 128 bit keys.

Salsa20是由Daniel J. Bernstein设计的算法,秘钥长度一般是256字节长,但是也支持128位

1.1 通过 Salsa20 加密数据:

>>> from Crypto.Cipher import Salsa20
>>> plaintext = b'Attack at dawn'
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> cipher = Salsa20.new(key=secret)
>>> msg = cipher.nonce + cipher.encrypt(plaintext)

1.2 通过 Salsa20 解密数据:

>>> from Crypto.Cipher import Salsa20
>>>
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> msg_nonce = msg[:8]
>>> ciphertext = msg[8:]
>>> cipher = Salsa20.new(key=secret, nonce=msg_nonce)
>>> plaintext = cipher.decrypt(ciphertext)

注意:

Salsa20 does not guarantee authenticity of the data you decrypt! In other words, an attacker may manipulate the data in transit. In order to prevent it, you must couple it with a Message Authentication Code (such as HMAC).

Salsa20并不保证加密数据的保密性,也就是说,攻击者可能在传输中或者数据,为了避免这种情况的发生,就需要使用信息保密代码去力偶数据(如HMAC)

ChaCha20 is a stream cipher designed by Daniel J. Bernstein. The secret key is 256 bits long.

ChaCha20是由Daniel J. Bernstein设计的流算法,秘钥长度为256字节。

2.1 通过 ChaCha20 加密数据:

>>> from Crypto.Cipher import ChaCha20
>>> plaintext = b'Attack at dawn'
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> cipher = ChaCha20.new(key=secret)
>>> msg = cipher.nonce + cipher.encrypt(plaintext)

2.2 通过 ChaCha20 解密数据:

>>> from Crypto.Cipher import ChaCha20
>>> secret = b'*Thirty-two byte (256 bits) key*'
>>> msg_nonce = msg[:8]
>>> ciphertext = msg[8:]
>>> cipher = ChaCha20.new(key=secret, nonce=msg_nonce)
>>> plaintext = cipher.decrypt(ciphertext)

注意事项同上

AES (Advanced Encryption Standard) is a symmetric block cipher standardized by NIST . It has a fixed data block size of 16 bytes. Its keys can be 128, 192, or 256 bits long.

AES is very fast and secure, and it is the de facto standard for symmetric encryption.

AES (高级/先进加密标准)是一个由NIST标准化的对称的块加密算法。它具有固定的16字节的数据块,秘钥可以是128、192、256位的。AES速度快并且安全,是对称加密的事实标准。

3.1通过 AES 加密数据:

>>> from Crypto.Cipher import AES
>>> key = b'Sixteen byte key'
>>> cipher = AES.new(key, AES.MODE_EAX)
>>>
>>> nonce = cipher.nonce
>>> ciphertext, tag = cipher.encrypt_and_digest(data)

3.2 通过 AES 解密数据:

>>> from Crypto.Cipher import AES
>>> key = b'Sixteen byte key'
>>> cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
>>> plaintext = cipher.decrypt(ciphertext)
>>> try:
>>>     cipher.verify(tag)
>>>     print("The message is authentic:", plaintext)
>>> except ValueError:
>>>     print("Key incorrect or message corrupted")

最后上一个实用类

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

class AESEncrypt(object):

    def __init__(self, key, key_length=16, allow_null=False):

        self.key = key
        self.key_length = key_length

        # It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long.
        self.mode = AES.MODE_CBC
        self.cryptor = AES.new(self.key, self.mode, self.key)
        self.allow_null = allow_null

    def encrypt(self, text):

        if not isinstance(text, basestring):
            raise TypeError("unicode/str objects only")

        if len(text) == 0:
            if self.allow_null:
                return ''

        _text = text + ('\0' * (self.key_length - len(text) % self.key_length))
        ciphertext = self.cryptor.encrypt(_text)
        return b2a_hex(ciphertext)

    def decrypt(self, text):

        if not isinstance(text, basestring):
            raise TypeError("unicode/str objects only")

        if len(text) == 0:
            if self.allow_null:
                return ''

        plain_text = self.cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')

def aes_encrypt(plain_text='', allow_null=False, key=DEFAULT_ENCRYPT_KEY):

    assert len(key) == 16, u'key error, The length of the need to 16, not {}'.format(len(key))

    return AESEncrypt(key=key, allow_null=allow_null).encrypt(plain_text)

def aes_decrypt(crypt_text='', allow_null=False, key=DEFAULT_ENCRYPT_KEY):

    assert len(key) == 16, u'key error, The length of the need to 16, not {}'.format(len(key))

    return AESEncrypt(key=key, allow_null=allow_null).decrypt(crypt_text)
(0)

相关推荐

  • 安全系列之——手写 JAVA 加密、解密

    网络安全一般需要注意以下几个关键点: 完整性(Integrity):确保信息在传输过程中,没有被篡改. 私密性(Confidentiality):也就是通过加密,确保只有可信的实体可以看到这些信息. ...

  • Windows下用Python3解密Chrome的Cookie值

    目录 0. 前言 1.参考文献 2.分析 3.流程 4.代码 4.1 代码结构 4.2 aesgcm.py 4.3 chromeCookieJar.py 4.4 decrypt.py 4.5 main ...

  • WEP详解

    WEP详解

  • Python项目生成依赖包清单requirements.txt方法总结

    一.背景 工作中跨环境运行相同项目时,总会出现缺少各种包的问题,还需要一个个安装,相当的蛋疼,这里推荐一个工具叫pipreqs,可以通过一条命令直接生成项目所有依赖包清单requirements.tx ...

  • 第 56 天:Python 爬虫之 urllib 包基本使用

    urllib 是一个 python 内置包,不需要额外安装即可使用,包里面包含了以下几个用来处理 url 的模块: urllib.request,用来打开和读取 url,意思就是可以用它来模拟发送请求 ...

  • Python 的AES加密与解密

    AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windows下使用AE ...

  • python财经数据接口包-Tushare

    使用对象 量化投资分析师(Quant) 对金融市场进行大数据分析的企业和个人 开发以证券为基础的金融类产品和解决方案的公司 正在学习利用python进行数据分析的人 使用前提¶ 安装Python 安装 ...

  • 正确安装python量化交易常用包talib

    首先你要明确你的系统版本,win32系统还是Linux,X86还是X64: 如果你的系统是x86平台,在安装了anaconda 的基础上,可以直接使用pip安装,命令如下: pip install t ...

  • Python网络编程 —— 粘包问题及解决方法

    Python网络编程 —— 粘包问题及解决方法

  • WIFI抓包OmniPeek工具--抓取WPA加密包如何解密步骤

    一.设置OmniPeek 可以在开始抓包的时候,提前设置好,ap的SSID和密码 注意:在解密包的抓取过程,必须包含四笔EAPOL-Key的包,然后在后续的时间里接着抓取TCP,DHCP等包. 二.抓 ...

  • 【Python爬虫】:破解网站字体加密和反反爬虫

    前言:字体反爬,也是一种常见的反爬技术,例如58同城,猫眼电影票房,汽车之家,天眼查,实习僧等网站.这些网站采用了自定义的字体文件,在浏览器上正常显示,但是爬虫抓取下来的数据要么就是乱码,要么就是变成 ...

  • 千万别说你会Python!如果不知道这10个Python包!

    世界上有超过200,000个Python程序包(这只是基于官方的Python程序包索引PyPI托管的程序包). 这就引出了一个问题:拥有这么多的软件包,每个Python程序员都需要学习哪些软件包是最重 ...