Skip to content

Instantly share code, notes, and snippets.

@tioover
Created August 5, 2014 03:27
Show Gist options
  • Save tioover/9af6eb7475e898df8a5a to your computer and use it in GitHub Desktop.
Save tioover/9af6eb7475e898df8a5a to your computer and use it in GitHub Desktop.
import unittest
import logging
import time
import requests
import simplejson as json # simplejson 可以改成 Python 标准库 import josn
from Crypto.Cipher import AES # 加密模块为 pycrypto ,需要安装
# 加密密钥为 1234567890123456 加密方法为 AES ECB ,字节填充方法为 PKCS#7
# 加解密器
class Crypto(object):
mode = AES.MODE_ECB
BS = 16
def __init__(self, key):
self.key = key
def pad(self, string):
"""填充字符串尾部以满足区块长度
填充方法为 PKCS#7
http://tools.ietf.org/html/rfc2315"""
fill = self.BS - len(string) % self.BS
return string + chr(fill) * fill
@staticmethod
def unpad(string):
"""解填充"""
return string[0: -ord(string[-1])]
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode)
return cryptor.encrypt(self.pad(str(text.decode("utf-8"))))
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode)
ret = self.unpad(cryptor.decrypt(text))
return ret
crypto = Crypto("1234567890123456")
# 测试用例
class APITest(unittest.TestCase):
def sent(self, url, data): # 发送和接受数据的方法
url = "http://apis.anquan.org/brand/" + url
data = crypto.encrypt(json.dumps(data)) # 加密以后的数据
request = requests.post(url, data) # 将加密以后的数据作为 post 的 content
a = crypto.decrypt(request.content) # 解密服务器响应
return json.loads(a)
def get_token(self):
return self.sent("acquiretoken/", {"app_id": "test", "secret": "test"})['token']
def test_acquire_token(self):
logging.debug(self.get_token())
def test_verify_code(self):
token = self.get_token()
ret = self.sent("verifycode/", {"token": token, "code": "test"})
logging.debug(ret)
def test_use_code(self):
token = self.get_token()
ret = self.sent("usecode/", {"token": token, "code": "test", "use_time": int(time.time())})
logging.debug(ret)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment