高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

如需进一步了解可以参考:https://zh.wikipedia.org/wiki/%E9%AB%98%E7%BA%A7%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86#%E5%AF%86%E7%A0%81%E8%AF%B4%E6%98%8E

AES5种常见加密模式:

1. 电码本模式(Electronic Codebook Book (ECB))

2. 密码分组链接模式(Cipher Block Chaining (CBC))

3. 计算器模式(Counter (CTR))

4. 密码反馈模式(Cipher FeedBack (CFB))

5. 输出反馈模式(Output FeedBack (OFB))

pip install pycrypto

官方链接:https://pypi.org/project/pycrypto/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'''
new(key, *args, **kwargs)
Create a new AES cipher

:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long.
:Keywords:
mode : a *MODE_** constant
The chaining mode to use for encryption or decryption.
Default is `MODE_ECB`.
IV : byte string
The initialization vector to use for encryption or decryption.

It is ignored for `MODE_ECB` and `MODE_CTR`.

For `MODE_OPENPGP`, IV must be `block_size` bytes long for encryption
and `block_size` +2 bytes for decryption (in the latter case, it is
actually the *encrypted* IV which was prefixed to the ciphertext).
It is mandatory.

For all other modes, it must be `block_size` bytes longs. It is optional and
when not present it will be given a default value of all zeroes.
counter : callable
(*Only* `MODE_CTR`). A stateful function that returns the next
*counter block*, which is a byte string of `block_size` bytes.
For better performance, use `Crypto.Util.Counter`.
segment_size : integer
(*Only* `MODE_CFB`).The number of bits the plaintext and ciphertext
are segmented in.
It must be a multiple of 8. If 0 or not specified, it will be assumed to be 8.

:Return: an `AESCipher` object
'''
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

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

class Aes_Crypto(object):
def __init__(self, key):
#self.key = key
##建议使用以下方式
self.key=hashlib.md5(key).hexdigest()

# 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度
self.iv=16*'0'
def encrypt(self,data):
# 不足16位补'\0'
data+=int(16-(len(data) % 16)) * '\0'
obj = AES.new(self.key, AES.MODE_CBC, self.iv)
ciphertext =obj.encrypt(data)
# 转化为16进制字符串
return b2a_hex(ciphertext)

def decrypt(self,data):
obj = AES.new(self.key, AES.MODE_CBC, self.iv)
return obj.decrypt(a2b_hex(data)).rstrip('\0')


if __name__ == '__main__':
a=Aes_Crypto(16*'1')
b=a.encrypt('123456782dd000')
print("加密后结果:"+b)
c=a.decrypt(b)
print("解密后结果:"+c)

执行后的结果:

1
2
3
 python test2.py 
加密后结果:a0ac1a2c639fd4bce1e3804be22bbcbb
解密后结果:1234567890123456

Comments

2018-06-16