Sample code for 30+ languages & platforms
Chilkat2-Python

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat Chilkat2-Python Downloads

Chilkat2-Python
import sys
import chilkat2

success = False

jws = chilkat2.Jws()

# Load the JWS compact serialization.
jwsCompact = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>"
success = jws.LoadJws(jwsCompact)
if (success == False):
    print(jws.LastErrorText)
    sys.exit()

# The file path is relative to the application's current working directory.  An absolute path
# may also be used.  Supply the path appropriate to your own environment.
# Load the signer's public key and set it for validating signature 0.
pubKey = chilkat2.PublicKey()
success = pubKey.LoadFromFile("qa_data/signer_pubkey.pem")
if (success == False):
    print(pubKey.LastErrorText)
    sys.exit()

success = jws.SetPublicKey(0,pubKey)
if (success == False):
    print(jws.LastErrorText)
    sys.exit()

# Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
v = jws.Validate(0)
if (v < 0):
    print(jws.LastErrorText)
    sys.exit()

if (v != 1):
    print("The signature is not valid.")
    sys.exit()

print("The signature is valid.")