问题描述:
前端使用 JSEncrypt 对数据进行 RSA 加密后经 axios 传回Python后端,当后端进行解密时发生以下错误:
...
File "C:\Users\wei\Desktop\MiniPlayer-Server\.\utils\security.py", line 57, in rsa_decrypt
return rsa.decrypt(data,key).decode('utf-8')
File "C:\Python310\lib\site-packages\rsa\pkcs1.py", line 265, in decrypt
raise DecryptionError("Decryption failed")
rsa.pkcs1.DecryptionError: Decryption failed
解密函数如下代码块:
def rsa_decrypt(data:bytes):
if RSA_PRI_KEY is None:
with open('private.pem','rb') as privateFile:
key = rsa.PrivateKey.load_pkcs1(privateFile.read())
return rsa.decrypt(data,key).decode('utf-8')
很明显,如果需要解密数据,传入解密函数的数据必须为bytes类型,于是很多人就使用str.encode('utf-8')进行编码。
可是!由前端 JSEncrypt 进行加密后的数据还会进行一次base64编码,因此只要像以下方法操作即可:
import base64
passwd = rsa_decrypt(base64.b64decode(data))
def rsa_decrypt(data:bytes):
if RSA_PRI_KEY is None:
with open('private.pem','rb') as privateFile:
key = rsa.PrivateKey.load_pkcs1(privateFile.read())
return rsa.decrypt(data,key).decode('utf-8')
发表回复