python ASE加密解密算法代码
专题教程:
AES加密解密算法与实现代码
python aes加密解密算法与模块用法教程
使用Crypto模块,AES256位加密。其中key的位数绝对了加密的方法:
key可以是16位、24位 或 32 位长度, 对应为 AES-128, AES-196 和 AES-256.
要加密的明文,大小必须位16字节的倍数,不足或者超过16字节的,用空格补全为16字节的倍数。
解密后,去除尾部的空格。
代码:
#!/usr/bin/env python
#
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
代码2:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from M2Crypto.EVP import Cipher
from M2Crypto import m2
iv = ' ' * 16 #任意设置
passKey = "1234567812345678"
text = "defabcdeabcdef1231231231231231adfasdfsdfasdfasdfadfasdfasdfasdfasdfasdf"
def encrypt(buf):
#ecb 模式不受iv影响
cipher = Cipher(alg='aes_128_ecb', key=passKey, iv=iv, op=1) # 1 is encrypt
# padding 有时设置为1
cipher.set_padding(padding=m2.no_padding)
v = cipher.update(buf)
v = v + cipher.final()
del cipher #需要删除
out = ""
for i in v:
out += "%02X" % (ord(i))
print out
return v
def decrypt(buf):
cipher = Cipher(alg='aes_128_ecb', key=passKey, iv=iv, op=0) # 0 is decrypt
cipher.set_padding(padding=m2.no_padding)
v = cipher.update(buf)
v = v + cipher.final()
del cipher #需要删除
print v
return v
decrypt(encrypt(text))