常用 Python 脚本

与 JWT 相关的 Python 脚本。

Tip

假设,验签算法都采用 RS256。

生成 JWK 格式的密钥#

推荐使用 jwcrypto 库:

Python
import json, uuid
from jwcrypto import jwk

key = jwk.JWK.generate(
	kty='RSA',
    size=2048,
    alg='RS256',
    use='sig',
    kid=str(uuid.uuid4())
)

private_jwk = key.export(private_key=True, as_dict=True)
public_jwk = key.export(as_dict=True)

print('JWK 格式的私钥: ')
print(json.dumps(private_jwk, indent=2))
print('\nJWK 格式的公钥: ')
print(json.dumps(public_jwk, indent=2))

生成 PEM 格式的密钥#

Python
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization

key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

with open("private.pem", "wb") as f:
    f.write(key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    ))

with open("public.pem", "wb") as f:
    f.write(key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    ))

注意,这其实并没有 openssl 命令来得方便:

Bash
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

JWS 构造#

对于 PEM 格式的密钥:

Python
import jwt

with open("private.pem", "rb") as f:
    private_key = f.read()
with open("public.pem", "rb") as f:
    public_key = f.read()

# 仅作为示例,并不完整
payload = {
    "iss": "https://auth.example.com",
    "role": "admin",
    ……
}

# 签名:用私钥
token = jwt.encode(
    payload,
    private_key,
    algorithm="RS256",
    headers={"kid": "key-2026-01", ……},  # # 仅作为示例,并不完整
)
print(token)

对于 JWK 格式的密钥:

x5c 证书链#

Tip

对于该参数的详细介绍,请看 Header 参数注入。

键盘快捷键

全站

CtrlK
搜索
/
搜索
?
显示快捷键
Esc
关闭弹窗、退出模式

阅读文章

T
目录
F
专注模式
A
批注模式

批注模式

P
笔
H
荧光笔
L
激光笔
E
橡皮擦
1–6
切换颜色
Shift
按住拖动画直线
CtrlZ
撤销
CtrlShiftZ
重做