免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3329 | 回复: 1

python ASE加密 [复制链接]

论坛徽章:
0
发表于 2012-12-05 00:22 |显示全部楼层
使用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
复制代码

论坛徽章:
0
发表于 2012-12-05 00:25 |显示全部楼层

# -*- encoding: utf-8 -*-  
from M2Crypto.EVP import Cipher  
from M2Crypto import m2  

iv = '\0' * 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))  
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP