python将jwths256加密——pyjwt库

2021-12-07 14:11:10 浏览数 (1)

加载对应的库:

$ pip install pyjwt

文档地址在:

https://pyjwt.readthedocs.io/en/stable/

一个非常简单的例子:

代码语言:javascript复制
import jwt
encoded_jwt = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
print(encoded_jwt)
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U
jwt.decode(encoded_jwt, "secret", algorithms=["HS256"])
{'some': 'payload'}

还有几类其他加密的方式:

文章目录
  • 1 Encoding & Decoding Tokens with HS256
  • 2 Encoding & Decoding Tokens with RS256 (RSA)
  • 3 设置特殊的Headers
  • 4 Reading Headers without Validation

1 Encoding & Decoding Tokens with HS256

代码语言:javascript复制
import jwt
key = "secret"
encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
print(encoded)
>>> eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
jwt.decode(encoded, key, algorithms="HS256")
>>> {'some': 'payload'}

2 Encoding & Decoding Tokens with RS256 (RSA)

代码语言:javascript复制
import jwt
private_key = b"-----BEGIN PRIVATE KEY-----nMIGEAgEAMBAGByqGSM49AgEGBS..."
public_key = b"-----BEGIN PUBLIC KEY-----nMHYwEAYHKoZIzj0CAQYFK4EEAC..."
encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")
print(encoded)
>>> eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
decoded = jwt.decode(encoded, public_key, algorithms=["RS256"])
>>> {'some': 'payload'}

如果需要PrivateKey ,还需要:

代码语言:javascript复制
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

pem_bytes = b"-----BEGIN PRIVATE KEY-----nMIGEAgEAMBAGByqGSM49AgEGBS..."
passphrase = b"your password"

private_key = serialization.load_pem_private_key(
    pem_bytes, password=passphrase, backend=default_backend()
)
encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")

3 设置特殊的Headers

代码语言:javascript复制
jwt.encode(
...     {"some": "payload"},
...     "secret",
...     algorithm="HS256",
...     headers={"kid": "230498151c214b788dd97f22b85410a5"},
... )
>>> 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjIzMDQ5ODE1MWMyMTRiNzg4ZGQ5N2YyMmI4NTQxMGE1In0.eyJzb21lIjoicGF5bG9hZCJ9.DogbDGmMHgA_bU05TAB-R6geQ2nMU2BRM-LnYEtefwg'

4 Reading Headers without Validation

代码语言:javascript复制
jwt.get_unverified_header(encoded)
>>> {'alg': 'RS256', 'typ': 'JWT', 'kid': 'key-id-12345...'}

0 人点赞