|
@ -1,9 +1,9 @@ |
|
|
#!/usr/bin/env python |
|
|
#!/usr/bin/env python |
|
|
# -*- coding:utf-8 -*- |
|
|
# -*- coding:utf-8 -*- |
|
|
#@author: rui.xu |
|
|
#@author: rui.xu |
|
|
#这里使用pycrypto库 |
|
|
#这里使用pycrypto库 |
|
|
#按照方法:easy_install pycrypto |
|
|
#按照方法:easy_install pycrypto |
|
|
|
|
|
|
|
|
from Crypto.Cipher import AES |
|
|
from Crypto.Cipher import AES |
|
|
from binascii import b2a_hex, a2b_hex |
|
|
from binascii import b2a_hex, a2b_hex |
|
|
from django.conf import settings |
|
|
from django.conf import settings |
|
@ -13,7 +13,7 @@ class prpcrypt(): |
|
|
def __init__(self,key): |
|
|
def __init__(self,key): |
|
|
self.key = key |
|
|
self.key = key |
|
|
self.mode = AES.MODE_CBC |
|
|
self.mode = AES.MODE_CBC |
|
|
|
|
|
|
|
|
#加密函数,如果text不足16位就用空格补足为16位, |
|
|
#加密函数,如果text不足16位就用空格补足为16位, |
|
|
#如果大于16当时不是16的倍数,那就补足为16的倍数。 |
|
|
#如果大于16当时不是16的倍数,那就补足为16的倍数。 |
|
|
def encrypt(self,text): |
|
|
def encrypt(self,text): |
|
@ -36,22 +36,22 @@ class prpcrypt(): |
|
|
#因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 |
|
|
#因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 |
|
|
#所以这里统一把加密后的字符串转化为16进制字符串 |
|
|
#所以这里统一把加密后的字符串转化为16进制字符串 |
|
|
return b2a_hex(self.ciphertext) |
|
|
return b2a_hex(self.ciphertext) |
|
|
|
|
|
|
|
|
#解密后,去掉补足的空格用strip() 去掉 |
|
|
#解密后,去掉补足的空格用strip() 去掉 |
|
|
def decrypt(self,text): |
|
|
def decrypt(self,text): |
|
|
cryptor = AES.new(self.key,self.mode,b'0000000000000000') |
|
|
cryptor = AES.new(self.key,self.mode,b'0000000000000000') |
|
|
plain_text = cryptor.decrypt(a2b_hex(text)).decode("utf8") |
|
|
plain_text = cryptor.decrypt(a2b_hex(text)).decode("utf8") |
|
|
return plain_text.rstrip('\0') |
|
|
return plain_text.rstrip('\0') |
|
|
|
|
|
|
|
|
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥 |
|
|
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥 |
|
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
if __name__ == '__main__': |
|
|
# for test |
|
|
# for test |
|
|
print(settings.CRYPT_KEY) |
|
|
print(settings.CRYPT_KEY) |
|
|
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥 |
|
|
pc = prpcrypt(settings.CRYPT_KEY.encode('utf8')) #初始化密钥 |
|
|
import sys |
|
|
import sys |
|
|
str = sys.argv[1] |
|
|
str = sys.argv[1] |
|
|
e = pc.encrypt(str) #加密 |
|
|
e = pc.encrypt(str) #加密 |
|
|
print("加密:",e) |
|
|
print("加密:",e) |
|
|
d = pc.decrypt(e) #解密 |
|
|
d = pc.decrypt(e) #解密 |
|
|
print("解密:",d) |
|
|
print("解密:",d) |
|
|