Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build and sign a jwt with a hardware key #3201

Open
ThierryThevenet opened this issue Dec 13, 2024 · 0 comments
Open

Build and sign a jwt with a hardware key #3201

ThierryThevenet opened this issue Dec 13, 2024 · 0 comments
Assignees
Labels

Comments

@ThierryThevenet
Copy link
Member

ThierryThevenet commented Dec 13, 2024

need before #2706

Problem : if we use a harware key, we dont have access to the private key so we cannot use the standard Dart JOSE package to build and sign a jwt. The objective here is to code a small lib to sign a jwt with a hardware key. We will use it later in the protocole OIDC4VC.

Here is an example of a python code to build the jwt bearing in mind that we will need to use the smartphone hardware to sign the message digest of the payload and header.

header is the jwt header, payload is the jwt payload, private key is here a software key


def sign_jwt(header, payload, private_key):
    # Base64 url safe encoding of header and payload without padding
    header_b64 = base64.urlsafe_b64encode(json.dumps(header).encode()).decode().rstrip("=")
    payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
    
    # calculate the message digest with sha256
    message = header_b64 + "." + payload_b64
    m = hashlib.sha256()
    m.update(message.encode())
    message_digest = m.digest()
    
    # sign the message digest with ecdsa key (P-256)
   
    sk = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.NIST256p)
    signature_bytes = sk.sign_digest(message_digest)
    
    # encode signature with base64 url safe and no padding
    signature_b64 = base64.urlsafe_b64encode(signature_bytes).decode().rstrip("=")
    
    # return jwt
    return header_b64 + '.' + payload_b64 + '.' + signature_b64

In the example above the software key must be replaced by a hardware key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants