IPWorks Encrypt 2020 Python Edition

Questions / Feedback?

JWS Class

Properties   Methods   Events   Configuration Settings   Errors  

Create, Sign and Verify JSON Web Signatures (JWS).

Syntax

class ipworksencrypt.JWS

Remarks

The JWS class supports signing and verifying JSON Web Signatures (JWS).

Specify any payload via input properties and use sign to create a JWS message using a variety of algorithms including HMAC, RSA, and ECDSA. Use verify to verify the signature of any received JWS message. The following algorithms are supported:

  • HS256
  • HS384
  • HS512
  • RS256
  • RS384
  • RS512
  • PS256
  • PS384
  • PS512
  • ES256
  • ES384
  • ES512
  • None

See algorithm for more details about supported algorithms.

Signing

The sign method may be used to sign a payload with a variety of algorithms. Before calling the sign method set algorithm to the algorithm which will be used to sign the message. The result of signing is a compact serialized JWS string. For instance:

eyJhbGciOiJIUzI1NiJ9.dGVzdA.o_JihJlCwvBO1AgY_Ao3_VBivdFmj3ufv3ZWAqYF4Ow

The class is agnostic of the payload that is signed. Any value may be signed. key_id may be set to include an identifier to help the receiving party identify the key used to sign the message. The following properties are applicable when calling this method:

  • algorithm (required)
  • certificate (conditional - required for ECDSA and RSA)
  • key (conditional - required for HMAC)
  • header_params
  • key_id
  • overwrite

Input and Output Properties

The class will determine the source and destination of the input and output based on which properties are set.

The order in which the input properties are checked is as follows:

When a valid source is found the search stops. The order in which the output properties are checked is as follows:

Notes for HMAC Algorithms (HS256, HS384, HS512)

When algorithm is set to a HMAC algorithm key must be set to a key of appropriate length for the algorithm. The key should be the same number of bits as the algorithm being used. For instance a 256 bit key would be used for HS256.

The example code below uses the EzRand class to generate a key, but the key may be created using any means. The key must be known by both parties in order for signing and verification to take place.


//Generate a 256 bit (32 byte) key
Ezrand ezrand = new Ezrand();
ezrand.RandBytesLength = 32;
ezrand.GetNextBytes();
byte[] key = ezrand.RandBytesB;

//Sign the payload using HS256
Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsHS256;
jws.InputMessage = "test data";
jws.KeyB = key;
jws.Sign();

string signedData = jws.OutputMessage;

To use an existing HMAC key provide the bytes to the key property. For instance:


//HMAC SHA-256 Key
byte[] key = new byte[] { 170, 171, 221, 209, 7, 181, 48, 178, 48, 118, 242, 132, 36, 218, 74, 140, 216, 165, 161, 70, 11, 42, 246, 205, 235, 231, 19, 48, 87, 141, 122, 10 };

//Sign the payload using HS256
Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsHS256;
jws.InputMessage = "test data";
jws.KeyB = key;
jws.Sign();

string signedData = jws.OutputMessage;

Notes for RSA Algorithms (RS256, RS384, RS512, PS256, PS384, PS512)

The RSA based algorithms use asymmetric encryption. Signing is done with a private key and verification is done with a public key. The private key may be in PFX or PEM format.


Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsRS256;
jws.Certificate = new Certificate(CertStoreTypes.cstPFXFile, "..\\jwt.pfx", "test", "*");
jws.InputMessage = "test";
jws.Sign();

string signedMessage = jws.OutputMessage;

Notes for ECDSA Algorithms (ES256, ES384, ES512)

ECDSA algorithms require a valid ECC private key to sign. The ECC class can be used to create or import an ECC key into the Certificate format accepted by the JWS class.


//Create an ECC key with SHA-256
Ecc ecc = new Ecc();
ecc.HashAlgorithm = EccHashAlgorithms.ehaSHA256;
ecc.CreateKey();

string privKey = ecc.Key.PrivateKey;

//Sign the payload using ES256
Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsES256;
jws.Certificate = new Certificate(CertStoreTypes.cstPEMKeyBlob, privKey, "", "*");
jws.InputMessage = "test";
jws.Sign();

string signedMessage = jws.OutputMessage;

To use an existing ECC Key populate the Rx, Ry, and K values of Key property in the ECC class first. For instance:


//Import an existing ECC private key
Ecc ecc = new Ecc();

byte[] x_bytes = new byte[] { 171, 170, 196, 151, 94, 196, 231, 12, 128, 232, 17, 61, 45, 105, 41, 209, 192, 187, 112, 242, 110, 178, 95, 240, 36, 55, 83, 171, 190, 176, 78, 13 };
byte[] y_bytes = new byte[] { 197, 75, 134, 245, 245, 28, 199, 9, 7, 117, 1, 54, 49, 178, 135, 252, 62, 89, 35, 180, 117, 80, 231, 23, 110, 250, 28, 124, 219, 253, 224, 156 };
byte[] k_bytes = new byte[] { 81, 65, 201, 24, 235, 249, 162, 148, 169, 150, 109, 181, 61, 238, 145, 122, 31, 30, 151, 94, 239, 90, 222, 217, 63, 103, 54, 2, 176, 232, 248, 168 };

ecc.Key.RxB = x_bytes;
ecc.Key.RyB = y_bytes;
ecc.Key.KB = k_bytes;

string privKey = ecc.Key.PrivateKey;

//Sign the payload using ES256
Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsES256;
jws.Certificate = new Certificate(CertStoreTypes.cstPEMKeyBlob, privKey, "", "*");
jws.InputMessage = "test";
jws.Sign();

string signedMessage = jws.OutputMessage;

Notes for Unsecured (none)

To create a JWS token without any security set algorithm to jwsNone.


Jws jws = new Jws();
jws.Algorithm = JwsAlgorithms.jwsNone;
jws.InputMessage = "test";
jws.Sign();

string unsecuredMessage = jws.OutputMessage;

Signature Verification

The verify method may be used to verify a received JWS message. Before calling the verify method set input_message or input_file to a valid compact serialized JWS string. For instance:

eyJhbGciOiJIUzI1NiJ9.dGVzdA.o_JihJlCwvBO1AgY_Ao3_VBivdFmj3ufv3ZWAqYF4Ow

key or certificate should be set to the HMAC key or public certificate respectively. If the correct key or certificate is not known ahead of time the KeyId parameter of the on_signer_info event may be used to identify the correct key.

If this method returns without error verification was successful. If verification fails then this method fails with an error. After calling this method the payload will be present in the output_message or file specified by output_file and the Header* properties will contain the headers. Headers of the parsed message are also available through the on_header_param event.

The following properties are applicable when calling this method:

Input and Output Properties

The class will determine the source and destination of the input and output based on which properties are set.

The order in which the input properties are checked is as follows:

When a valid source is found the search stops. The order in which the output properties are checked is as follows:

Notes for HMAC Algorithms (HS256, HS384, HS512)

When verifying a message originally signed with a HMAC algorithm key must be set to the same key used during signing. The key must be known by both parties in order for signing and verification to take place.


byte[] key = new byte[] { 170, 171, 221, 209, 7, 181, 48, 178, 48, 118, 242, 132, 36, 218, 74, 140, 216, 165, 161, 70, 11, 42, 246, 205, 235, 231, 19, 48, 87, 141, 122, 10 };

Jws jws = new Jws();
jws.KeyB = key;
jws.InputMessage = signedData;
jws.Verify();

string verifiedPayload = jws.OutputMessage;

Notes for RSA Algorithms (RS256, RS384, RS512, PS256, PS384, PS512)

The RSA based algorithms use asymmetric encryption. Signing is done with a private key and verification is done with a public key. The public key is typically in PEM format.


Jws jws = new Jws();
jws.Certificate = new Certificate("..\\jwt.cer"); 
jws.InputMessage = signedData;
jws.Verify();

string verifiedPayload = jws.OutputMessage;

Notes for ECDSA Algorithms (ES256, ES384, ES512)

ECDSA algorithms require a valid ECC public key to verify the message. If the key was originally created with the ECC class the PEM encoded PublicKey may be used directly with the certificate property. An example PEM encoded public certificate created by the ECC class:

-----BEGIN PUBLIC KEY-----
MIIBMjCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////wAAAAEAAAAAAAAAAAAA
AAD///////////////8wRAQg/////wAAAAEAAAAAAAAAAAAAAAD///////////////wEIFrG
NdiqOpPns+u9VXaYhrxlHQawzFOw9jvOPD4n0mBLBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt
6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA
//////////+85vqtpxeehPO5ysL8YyVRAgEBA0EEIC5rbLp11Mnz6cBXLLriaDIov3rm8RAY
x/OR0bOKiff0cQy+sLVaxjseqFk/+Xvl4ORSv5Z6HdHv5GyEpA0UoA==
-----END PUBLIC KEY-----


Jws jws = new Jws();
jws.Certificate = new Certificate(CertStoreTypes.cstPublicKeyFile, pubKey, "", "*");
jws.InputMessage = signedData;
jws.Verify();

string verifiedPayload = jws.OutputMessage;

To use an ECC public key created by other means the ECC class may be used to import the key parameters. Populate the Rx and Ry of the ECC class first to obtain the PEM formatted public key. For instance:


//Import an existing ECC public key
Ecc ecc = new Ecc();

byte[] x_bytes = new byte[] { 171, 170, 196, 151, 94, 196, 231, 12, 128, 232, 17, 61, 45, 105, 41, 209, 192, 187, 112, 242, 110, 178, 95, 240, 36, 55, 83, 171, 190, 176, 78, 13 };
byte[] y_bytes = new byte[] { 197, 75, 134, 245, 245, 28, 199, 9, 7, 117, 1, 54, 49, 178, 135, 252, 62, 89, 35, 180, 117, 80, 231, 23, 110, 250, 28, 124, 219, 253, 224, 156 };

ecc.Key.RxB = x_bytes;
ecc.Key.RyB = y_bytes;

string pubKey = ecc.Key.PublicKey;

Jws jws = new Jws();
jws.Certificate = new Certificate(CertStoreTypes.cstPublicKeyFile, pubKey, "", "*");
jws.InputMessage = signedData;
jws.Verify();

string verifiedPayload = jws.OutputMessage;

Notes for Unsecured (none)

To parse a JWS token without any security call the sign method without setting key or certificate.


Jws jws = new Jws();
jws.InputMessage = signedData;
jws.Verify();

string unsecuredPayload = jws.OutputMessage;

Other Functionality

In addition to standard signing and verifying the class also supports a variety of other features including:

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

algorithmThe algorithm used when signing.
cert_encodedThe certificate (PEM/base64 encoded).
cert_storeThe name of the certificate store for the client certificate.
cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
cert_store_typeThe type of certificate store for this certificate.
cert_subjectThe subject of the certificate used for client authentication.
header_param_countThe number of records in the HeaderParam arrays.
header_param_data_typeThe data type of the header parameter.
header_param_nameThe header parameter name.
header_param_valueThe header parameter value.
input_fileThe file to process.
input_messageThe message to process.
keyThe secret key for the hash algorithm.
key_idThe Id of the key used to sign the message.
output_fileThe output file when encrypting or decrypting.
output_messageThe output message after processing.
overwriteIndicates whether or not the class should overwrite files.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

add_header_paramAdds additional header parameters.
configSets or retrieves a configuration setting.
parseParses the compact serialized JWS string.
resetResets the class.
signSigns the payload with the specified algorithm.
verifyVerifies the signature of the JWS token.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_errorInformation about errors during data delivery.
on_header_paramFires once for each JOSE header parameter.
on_signer_infoFires with information about the signature.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AllowedSigningAlgorithmsAllowed signing algorithms when StrictValidation is set to True.
IncludeCertificateFormatThe certificate values to include in the signed message (if any).
IssuerCertsA collection of issuer certificates used with IncludeCertificateFormat.
KeyEncodingThe encoding of the Key value.
RawHeaderHolds the raw JOSE header.
SerializationTypeDetermines the serialization type to use when reading and writing JWS content.
StrictValidationRequires a specific algorithm when verifying signatures.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks Encrypt 2020 Python Edition - Version 20.0 [Build 8155]