如何在 python 中使用 RSA SHA-256 签署令牌?

amd*_*dan 5 python sha256 jwt private-key rsa-sha256

我正在尝试用 python 对 JWT 进行编码,我需要用 base64 对其进行编码,我就是这么做的。然后我必须在发送到服务器之前用私钥对其进行签名。其实我被屏蔽了,什么时候签名我不知道怎么办,我从昨天开始就在网上搜索,我有点迷失了。这是我的代码。

import jwt

print ("\nStart..")

encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')

print("\nJWT : ",encoded)

try:
    decoded = jwt.decode(encoded, 'secret', algorithms=['HS256'])
except jwt.InvalidTokenError:
    print("Invalid token!!")

print("\ndecoded : ", decoded)

print("\nencodage : ")

#LOAD THE PRIVATE KEY


#SIGN THE ENCODED token
Run Code Online (Sandbox Code Playgroud)

还有我的密钥的格式,它是 RSA 私钥。

-----BEGIN RSA PRIVATE KEY-----
dsjkfhsdfkshkdfhks...
-----END RSA PRIVATE KEY-----
Run Code Online (Sandbox Code Playgroud)

我向服务器 crt.crt 提供了一个证书,我认为我需要用我的私钥进行加密,然后他们将能够使用证书中的密钥来解密消息,这就是我的理解。

预先感谢,G.B

小智 2

您可以尝试并参考:

from Crypto.PublicKey import RSA
from Crypto.Cipher import HS256

def encrypt_text(input_text):
   utf8_text = input_text.encode('utf-8')
   pub_key = RSA.importKey(open(settings.RSA).read())
   cipher = HS256.new(public_key)
   cipher_text = base64.encodebytes(cipher.encrypt(utf8_text))
   return cipher_text.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

创建公钥和私钥:

ssh-keygen -t rsa -C "your_email@example.com"
Run Code Online (Sandbox Code Playgroud)

希望有帮助