python AES-16位加密解密功能实现
2015-12-30 12:00
936 查看
从网上搜了很多这种python AES相关内容,但是大部分都是需要自己调试修改半天才能使用,有的甚至埋下很多坑,费时费力,我这边根据项目需求,也需要弄一套AES-16位加密和解密API
我用的python加密组件是Crypto,很好用,可以从网上下载最新的库,我用的比较稳定的版本2.6,可以从https://pypi.python.org/pypi/pycrypto下载;
通过./configure,python setup.py build ,python setup.py install 三步法完成编译安装,一定要从官方下载,我当时一开始某一个网站下载一个,经过三步法虽然安装完成了,但是调试发现aes无法使用一直coredown,最后就直接删除掉,从官方下载一个。
经过调试通过的AES接口如下:
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class crypt():
def __init__(self):
self.key = '1234567890123456'
self.iv = 'This is an IV456'
self.mode = AES.MODE_CBC
self.BS = AES.block_size
self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
self.unpad = lambda s : s[0:-ord(s[-1])]
def encrypt(self, text):
text = self.pad(text)
self.obj1 = AES.new(self.key, self.mode, self.iv)
self.ciphertext = self.obj1.encrypt(text)
return b2a_hex(self.ciphertext)
def decrypt(self, text):
self.obj2 = AES.new(self.key, self.mode, self.iv)
plain_text = self.obj2.decrypt(a2b_hex(text))
return self.unpad(plain_text.rstrip('\0'))
if __name__ == '__main__':
pc = crypt()
e = pc.encrypt("hello")
print e
d = pc.decrypt(e)
print d
该接口类主要做了加密解密中补位的操作,满足16位加密和解密要求。
我用的python加密组件是Crypto,很好用,可以从网上下载最新的库,我用的比较稳定的版本2.6,可以从https://pypi.python.org/pypi/pycrypto下载;
通过./configure,python setup.py build ,python setup.py install 三步法完成编译安装,一定要从官方下载,我当时一开始某一个网站下载一个,经过三步法虽然安装完成了,但是调试发现aes无法使用一直coredown,最后就直接删除掉,从官方下载一个。
经过调试通过的AES接口如下:
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class crypt():
def __init__(self):
self.key = '1234567890123456'
self.iv = 'This is an IV456'
self.mode = AES.MODE_CBC
self.BS = AES.block_size
self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
self.unpad = lambda s : s[0:-ord(s[-1])]
def encrypt(self, text):
text = self.pad(text)
self.obj1 = AES.new(self.key, self.mode, self.iv)
self.ciphertext = self.obj1.encrypt(text)
return b2a_hex(self.ciphertext)
def decrypt(self, text):
self.obj2 = AES.new(self.key, self.mode, self.iv)
plain_text = self.obj2.decrypt(a2b_hex(text))
return self.unpad(plain_text.rstrip('\0'))
if __name__ == '__main__':
pc = crypt()
e = pc.encrypt("hello")
print e
d = pc.decrypt(e)
print d
该接口类主要做了加密解密中补位的操作,满足16位加密和解密要求。
相关文章推荐
- Python 获取Twitter用户与Friends和Followers的关系(eg, 交集,差集)
- 仿射变换(Affine transformation)与python实践
- python 字典排序
- python手记(51)
- Python 1.6 使用dict和set
- [python] 专题八.多线程编程之thread和threading
- python模拟登陆和发布信息
- python Tab自动补全命令设置
- 4. Median of Two Sorted Arrays leetcode python New season for 2016
- 【python】多个文件共用日志系统的重复打印问题
- C#中通过Process运行Python脚本
- leetcode之Binary Tree Paths
- Python 1.5 循环
- leetcode之Sum Root to Leaf Numbers
- 修改ubuntu的默认python版本
- supervisor运行python程序时的环境配置
- python之commands模块
- leetcode之Path Sum
- Python-Windows下安装BeautifulSoup和requests第三方模块
- Python 1.4 条件判断