在做接口自动化测试时,登录接口鉴权是我们首先要完成的。后续业务相关接口都需要依赖登录接口返回的token或cookie。常见的登录方式是当用户输入账号和密码点击登录时,前端会使用JSEncrypt组件对用户的相关信息进行RSA加密,今天我们就学习下如何使用python语言实现RSA加密。
RSA加密是一种非对称加密。可以在不传递秘钥情况下,完成解密。 例如:客户端发起登录请求,传送账号密码给服务器端
该模块是Python3中用来处理加密解密信息安全相关的模块。 在线安装:pip install pycryptodome
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64, json, requests, re
#被加密信息
pwd = "123456"
#公钥
public_key = '''-----BEGIN PUBLIC KEY-----
qGSIb3DQEBAQUAA4GNADCBiQKBgQCROXobn2Z2lyOZuUq5xhr/3AWuSSXCqLM2q6TEMnI2VE1BzlcxQVG
-----END PUBLIC KEY-----'''
rsakey = RSA.importKey(public_key) #传入公钥
cipher = Cipher_pkcs1_v1_5.new(rsakey) #生成对象
cipher_text = base64.b64encode(cipher.encrypt(pwd.encode(encoding="utf-8"))) #对明文pwd进行加密
print(cipher_text.decode('utf8')) #输出加密内容
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64, json, requests
#公钥
public_key = '''-----BEGIN PUBLIC KEY-----
qGSIb3DQEBAQUAA4GNADCBiQKBgQCROXobn2Z2lyOZuUq5xhr/3AWuSSXCqLM2q6TEMnI2VE1BzlcxQVG
-----END PUBLIC KEY-----'''
# 加密方法
def get_encryption_pwd(pwd):
rsakey = RSA.importKey(public_key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(pwd.encode(encoding="utf-8")))
return cipher_text.decode('utf8')
# 登录方法
def login(username, pwd):
json_params = {'publickKey': public_key, 'username': username,'rsaPassword': get_encryption_pwd(pwd)}
headers = {'Content-Type': 'application/json; charset=UTF-8'}
url = "https://xxx.com/login"
r = requests.post(url, data=json.dumps(json_params), headers=headers)
set_cookie = r.headers.get("Set-Cookie")
return set_cookie
if __name__ == '__main__':
login_info = login("admin","admin")
欢迎有疑问的同学留言! ;)