학습

Python pyjwt

Grower 2022. 8. 20. 16:38

PyJWT 2.4.0

Released: May 13, 2022

 

 

Installation

You can install PyJWT with pip:

$ pip install pyjwt

Cryptographic Dependencies (Optional)

If you are planning on encoding or decoding tokens using certain digital signature algorithms (like RSA or ECDSA), you will need to install the cryptography library. This can be installed explicitly, or as a required extra in the pyjwt requirement:

번역:

특정 디지털 서명 알고리즘(예: RSA 또는 ECDSA)을 사용하여 토큰을 인코딩하거나 디코딩하려는 경우 암호화 라이브러리를 설치해야 합니다. 이 기능은 명시적으로 설치하거나 Pyjwt 요구 사항에 필요한 추가 기능으로 설치할 수 있습니다.

$ pip install pyjwt[crypto]

The pyjwt[crypto] format is recommended in requirements files in projects using PyJWT, as a separate cryptography requirement line may later be mistaken for an unused requirement and removed.

번역:

PyJWT를 사용하는 프로젝트의 요구사항 파일에서 pyjwt[crypto] 형식을 사용하는 것이 좋습니다. 별도의 암호화 요구사항 라인이 나중에 사용되지 않는 요구사항으로 잘못 인식되어 제거될 수 있기 때문입니다.

 

Usage Examples

Encoding & Decoding Tokens with HS256

>>> 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'}

Encoding & Decoding Tokens with RS256 (RSA)

RSA encoding and decoding require the cryptography module. See Cryptographic Dependencies (Optional).

번역:

RSA 인코딩 및 디코딩에는 암호화 모듈이 필요합니다. 암호화 종속성(선택사항)을 참조하십시오.

>>> 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'}

If your private key needs a passphrase, you need to pass in a PrivateKey object from cryptography.

번역:

개인 키에 암호 구문이 필요한 경우 암호화에서 개인 키 개체를 전달해야 합니다.

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")

If you are repeatedly encoding with the same private key, reusing the same RSAPrivateKey also has performance benefits because it avoids the CPU-intensive RSA_check_key primality test.

번역:

동일한 개인 키로 반복적으로 인코딩하는 경우 동일한 RSAPrivateKey를 재사용하면 CPU 집약적인 RSA_check_key primity 테스트를 피할 수 있으므로 성능상의 이점도 있습니다.

 

# 소스

제가 작성한 코드를 공유합니다.

import jwt
from Crypto.PublicKey import RSA

def rsa_key_create():
  keyPair = RSA.generate(3072)
  f = open('myprivkey.pem', 'wb')
  f.write(keyPair.export_key())
  f.close()

  pubKey = keyPair.publickey()
  f = open('publicKey.pem', 'wb')
  f.write(pubKey.export_key())
  f.close()

def load_rsa_privKey():
  f = open('myprivkey.pem', 'r')
  key = f.read()
  return key

def load_rsa_publicKey():
  f = open('publicKey.pem', 'r')
  key = f.read()
  return key

def jwt_encode(privKey):
  encoded = jwt.encode({"some": "payload"}, privKey, algorithm="RS256")
  return encoded

def jwt_decoded(encoded):
  publicKey = load_rsa_publicKey()
  decoded = jwt.decode(encoded, publicKey, algorithms="RS256")
  return decoded

privKey = load_rsa_privKey()
encoded = jwt_encode(privKey)
print(encoded)
decoded = jwt_decoded(encoded)
print(decoded)

 

 

# 참고

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

 

Welcome to PyJWT — PyJWT 2.4.0 documentation

© Copyright 2015-2022, José Padilla Revision 83ff831a.

pyjwt.readthedocs.io