使用Python Crypto 进行密码加密与解密

1
from Crypto.Cipher import AES
2
from Crypto import Random
3
from binascii import b2a_hex, a2b_hex
4
from django.conf import settings
5
# ENCRYPT_KEY = settings.ENCRYPT_KEY
6
ENCRYPT_KEY = 'passplatairtimes'.encode('utf-8')
7
8
def encrypt_string(string):
9
    '''
10
        加密字符串
11
    :param string: 需加密字符串
12
    :return: 加密字符串
13
    '''
14
    iv = Random.new().read(AES.block_size)
15
    myclipher = AES.new(ENCRYPT_KEY, AES.MODE_CFB, iv)
16
    clipher_text = iv + myclipher.encrypt(string.encode('utf-8'))
17
18
    return b2a_hex(clipher_text).decode()
19
20
def decrypt_string(encrypt_string):
21
    '''
22
        字符串解密
23
    :param encrypt_string: 密文
24
    :return: 解密后字符串
25
    '''
26
    # key = settings.ENCRYPT_KEY
27
    # string = encrypt_string.encode('utf-8')
28
    # print(string[16:])
29
30
    mydecypt = AES.new(ENCRYPT_KEY, AES.MODE_CFB, a2b_hex(encrypt_string)[:16])
31
    descrypttext = mydecypt.decrypt(a2b_hex(encrypt_string)[16:])
32
33
    return descrypttext.decode()
34
35
36
if __name__ == '__main__':
37
    a = encrypt_string('xxxxxxxxxxxxx1x?.\/xxx$#@#!^')
38
    b = decrypt_string(a)
39
    print(b)