m1/mcrypto.py
2020-04-17 11:37:13 +08:00

56 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- 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 长度必须为16AES-128、24AES-192、或32AES-256Bytes 长度.目前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)