Sample code for 30+ languages & platforms
Objective-C

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 Objective-C Downloads

Objective-C
#import <CkoJws.h>
#import <NSString.h>
#import <CkoPublicKey.h>

BOOL success = NO;

CkoJws *jws = [[CkoJws alloc] init];

//  Load the JWS compact serialization.
NSString *jwsCompact = @"eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>";
success = [jws LoadJws: jwsCompact];
if (success == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

//  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.
CkoPublicKey *pubKey = [[CkoPublicKey alloc] init];
success = [pubKey LoadFromFile: @"qa_data/signer_pubkey.pem"];
if (success == NO) {
    NSLog(@"%@",pubKey.LastErrorText);
    return;
}

success = [jws SetPublicKey: [NSNumber numberWithInt: 0] pubKey: pubKey];
if (success == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

//  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
int v = [[jws Validate: [NSNumber numberWithInt: 0]] intValue];
if (v < 0) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

if (v != 1) {
    NSLog(@"%@",@"The signature is not valid.");
    return;
}

NSLog(@"%@",@"The signature is valid.");