0
点赞
收藏
分享

微信扫一扫

Python3实现jsencrypt RSA公钥格式化和加密

young_d807 2022-07-12 阅读 67


jsencrypt是前端常用的加密组件,那么用Python3如何实现呢?

import requests
from urllib.parse import urlencode
import json
import os
import time
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

URL_BASE = 'http://xxx.com/'
headers_ajax = {"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"Accept":"application/json, text/javascript, */*; q=0.01"}

def handle_pub_key(pub_key):
"""
处理公钥格式
:param pub_key:
:return:
"""
start = '-----BEGIN PUBLIC KEY-----\n'
end = '-----END PUBLIC KEY-----'
result = ''
# 分割key,每64位长度换一行
length = len(pub_key)
divide = 64 # 切片长度
offset = 0 # 拼接长度
while length - offset > 0:
if length - offset > divide:
result += pub_key[offset:offset + divide] + '\n'
else:
result += pub_key[offset:] + '\n'
offset += divide
result = start + result + end
return result

def get_password():
"""
RSA加密
:return:
"""
r = requests.post(URL_BASE+ "getPublicKey.action", data={"username": username}, allow_redirects=False, headers=headers_ajax)
publicKey = json.loads(r.text)['publicKey']

publicKey = handle_pub_key(publicKey)
rsakey = RSA.importKey(publicKey)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(password.encode('utf-8')))
passwordVal = cipher_text.decode('utf-8')
with open(password_path, "w+") as f:
f.write(passwordVal)
return

import base64
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA


def encrpt(password, public_key):
rsakey = RSA.importKey(public_key)
cipher = Cipher_pksc1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(password.encode()))
return cipher_text.decode()


# key是公钥,需要修改成自己的
key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC//WCWUQiDiIh8GhQfEwfU9OM7khBwlXE1HGEoBNakQJcr7iUPBUPADoik8d55z4KWCMgeImV+GHjGY/h8Vpy4nZ2AqmNlbz7MAtq9ln4p4EtgAvTqA8RFxV7SORd/GYio+mPh80T+zQJJwKpkxT1uewbU9LrSbqbkEtYpg9u2QIDAQAB'
public_key = '-----BEGIN PUBLIC KEY-----\n' + key + '\n-----END PUBLIC KEY-----'
password = encrpt('xxxxxx', public_key)
print('password:', password)

参考

​​https://github.com/travist/jsencrypt​​​

https://npmcdn.com/jsencrypt
https://mp.weixin.qq.com/s?__biz=MzI2OTQ1NzEyMQ==&mid=2247483716&idx=1&sn=e88f6ab5f037c780c1b0593bb8538145&chksm=eae142cadd96cbdcd7b49b1ad411f82e1f173725f0862cc27e722cbb539901ed3e1bab6fe1d5&scene=21#wechat_redirect


举报

相关推荐

0 条评论