Encrypting JWTs

With JWTs (JSON Web Tokens), we can create a claim and then sign it with public key encryption or HMAC. But what if we want to encrypt data…

Encrypting JWTs

With JWTs (JSON Web Tokens), we can create a claim and then sign it with public key encryption or HMAC. But what if we want to encrypt data with a JWT? For this, we can use AES encryption to encrypt the data. The header then becomes the form of:

{
"alg": "dir",
"enc": "A128GCM"
}

and where the payload is a byte stream that is encoded into the JWT:

In this case, there is no key wrapping involved, and where we must use the same key to encrypt and decrypt. Note, that HMAC signature contains the hash of the key. If we want to wrap the key we can define with:

{
"alg": "A128KW",
"enc": "A128GCM"
}

This gives:

We can now implement this with [here]:

from jose import jwe
import hashlib
import sys
import binascii

message='test'
method='A128GCM'
password='pass'
management='dir'


if (len(sys.argv)>1):
message=str(sys.argv[1])
if (len(sys.argv)>2):
password=str(sys.argv[2])
if (len(sys.argv)>3):
method=str(sys.argv[3])
if (len(sys.argv)>4):
management=str(sys.argv[4])

print(f"Message: {message}")
print(f"Password: {password}")
print(f"Method: {method}\n")
pwd = hashlib.sha256(password.encode())
key=pwd.digest()


if ("128" in method): key=key[:16]
if ("192" in method): key=key[:24]
if ("256" in method): key=key[:32]

print(f"Key used: {binascii.hexlify(key)}\n")

try:
token=jwe.encrypt('Hello, World!',key, algorithm=management, encryption=method)
print(f"Token: {token}")
rtn=jwe.decrypt(token,key)
print(f"Decrypted: {rtn}")

except Exception as error:

print(error)

In this case, we basically take a passphrase, and then take a SHA-256 hash, and then convert it to the required key size:

pwd = hashlib.sha256(password.encode())
key=pwd.digest()

if ("128" in method): key=key[:16]
if ("192" in method): key=key[:24]
if ("256" in method): key=key[:32]

Note, that, in production, we would use HKDF rather than SHA-256. A sample run is:

Message: hello
Password: 0123456789ABCDEF
Method: A128GCM

Key used: b'2125b2c332b1113aae9bfc5e9f7e3b4c'

Token: b'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..0-TDWKTp7yZ7_1iW6P2JZw.1h2EOrVp9IBXFlehTA.Lj97SnfMjdd-lvbEhRDTuw'
Decrypted: b'Hello, World!'

Find out more about JWTs here:

https://asecuritysite.com/jwt