- 论坛徽章:
- 0
|
使用Crypto模块,AES256位加密。其中key的位数绝对了加密的方法:
key可以是16位、24位 或 32 位长度, 对应为 AES-128, AES-196 和 AES-256.
要加密的明文,大小必须位16字节的倍数,不足或者超过16字节的,用空格补全为16字节的倍数。
解密后,去除尾部的空格。
from Crypto.Cipher import AES
class mycrypt():
def __init__(self,key):
self.key = key
self.mode = AES.MODE_CBC
def myencrypt(self,text):
cryptor = AES.new(key,self.mode)
length = 16
count = text.count('')
if count < length:
add = (length-count) + 1
text = text + (' ' * add)
elif count > length:
add = (length-(count % length)) + 1
text = text + (' ' * add)
self.ciphertext = cryptor.encrypt(text)
return self.ciphertext
def mydecrypt(self,text):
cryptor = AES.new(key,self.mode)
plain_text = cryptor.decrypt(text)
return plain_text
text = "98789khjsajfilahfpoiwufipoasufipo"
key = "9878*(&^^&)0LLIu(*&^))#$@!KJLKJj"
en = mycrypt(key)
entext = en.myencrypt(text)
print entext
detext = en.mydecrypt(entext).rstrip()
print detext
复制代码 |
|