56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
# -*- coding: utf-8 -*-
|
||
|
||
# pip install pycryptodome
|
||
|
||
from Crypto.Cipher import AES
|
||
from binascii import b2a_hex, a2b_hex
|
||
|
||
AES_LENGTH = 16
|
||
|
||
|
||
class Crypto():
|
||
def __init__(self, key):
|
||
self.key = key
|
||
self.mode = AES.MODE_ECB
|
||
self.cryptor = AES.new(self.pad_key(self.key).encode(), self.mode)
|
||
|
||
# 加密文本text必须为16的倍数,补足为16的倍数
|
||
def pad(self, text):
|
||
while len(text) % AES_LENGTH != 0:
|
||
text += '\0'
|
||
return text
|
||
|
||
# 加密密钥需要长达16位字符,所以进行空格拼接
|
||
def pad_key(self,key):
|
||
while len(key) % AES_LENGTH != 0:
|
||
key += '\0'
|
||
return key
|
||
|
||
# 加密
|
||
def encrypt(self, text):
|
||
try:
|
||
# 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
|
||
# 加密的字符需要转换为bytes
|
||
self.ciphertext = self.cryptor.encrypt(self.pad(text).encode())
|
||
|
||
# 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
|
||
# 所以这里统一把加密后的字符串转化为16进制字符串
|
||
return b2a_hex(self.ciphertext)
|
||
except Exception as e:
|
||
return e
|
||
|
||
# 解密
|
||
def decrypt(self, text):
|
||
try:
|
||
plain_text = self.cryptor.decrypt(a2b_hex(text)).decode()
|
||
return plain_text.rstrip('\0')
|
||
except Exception as e:
|
||
return e
|
||
|
||
|
||
if __name__ == '__main__':
|
||
pc = Crypto('kingsome') # 初始化密钥
|
||
e = pc.encrypt("123456")
|
||
d = pc.decrypt(e)
|
||
print(e, d)
|