在python3.5编写了一个AES加解密程序
2016-01-06 00:17
711 查看
如题,完美支持utf-8
#coding: utf8
import sys
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class prpcrypt():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC
#加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
text = text.encode("utf-8")
#这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
length = 16
count = len(text)
add = length - (count % length)
text = text + (b'\0' * add)
self.ciphertext = cryptor.encrypt(text)
#因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
#所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(self.ciphertext).decode("ASCII")
#解密后,去掉补足的空格用strip() 去掉
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip(b'\0').decode("utf-8")
if __name__ == '__main__':
pc = prpcrypt('keyskeyskeyskeys') #初始化密钥
e = pc.encrypt("my book is free")
d = pc.decrypt(e)
print (e, d)
e = pc.encrypt("我是一个粉刷匠1231繁體testひらがな")
d = pc.decrypt(e)
print (e, d)
#coding: utf8
import sys
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class prpcrypt():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC
#加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
text = text.encode("utf-8")
#这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
length = 16
count = len(text)
add = length - (count % length)
text = text + (b'\0' * add)
self.ciphertext = cryptor.encrypt(text)
#因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
#所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(self.ciphertext).decode("ASCII")
#解密后,去掉补足的空格用strip() 去掉
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip(b'\0').decode("utf-8")
if __name__ == '__main__':
pc = prpcrypt('keyskeyskeyskeys') #初始化密钥
e = pc.encrypt("my book is free")
d = pc.decrypt(e)
print (e, d)
e = pc.encrypt("我是一个粉刷匠1231繁體testひらがな")
d = pc.decrypt(e)
print (e, d)
相关文章推荐
- SVM编程实现python
- 分享Python文本生成二维码实例
- python访问mysql数据库的实现方法(2则示例)
- 用python爬取某美剧网站的下载链接(一)
- python-73:让我们来解决这个不和谐的符号
- python-74:按原格式下载BS4官方文档
- python windows下的file()
- Python:当前路径下文件的复制
- python 字符串技巧 from python cookbook
- Python/C API 3.4 简介
- lesson1:Python 判断表达式应用
- python3.5安装加密模块pycrypto
- Python系列之 - python文件操作
- python 并发执行之多线程
- 编写高质量代码--改善python程序的建议(四)
- python并发执行之多进程
- [Python标准库]functools——管理函数的工具
- 基于python的密码管理工具
- python知识-python操作MySQL数据库
- PYTHON 奇怪现象 记录下 WindowsError: [Error 2]