Sample code for 30+ languages & platforms
Objective-C

Sign a JWS with an HMAC Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetMacKey, which sets the symmetric MAC key for a signature. The key bytes are supplied in a named encoding such as hex or base64.

Background. HMAC-based JWS (for example HS256) authenticates the payload with a shared symmetric key that both signer and verifier possess.

Chilkat Objective-C Downloads

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

BOOL success = NO;

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

//  Protected header specifying HMAC-SHA256.
CkoJsonObject *header = [[CkoJsonObject alloc] init];
[header UpdateString: @"alg" value: @"HS256"];
success = [jws SetProtectedHeader: [NSNumber numberWithInt: 0] json: header];
if (success == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

BOOL bIncludeBom = NO;
success = [jws SetPayload: @"This is the content to sign." charset: @"utf-8" includeBom: bIncludeBom];
if (success == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

//  Set the symmetric MAC key for signature 0.  The key bytes are provided in the named encoding (here
//  base64).  In production, obtain the key from a secure source rather than hard-coding it.
NSString *base64Key = @"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
success = [jws SetMacKey: [NSNumber numberWithInt: 0] key: base64Key encoding: @"base64"];
if (success == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

NSString *jwsCompact = [jws CreateJws];
if (jws.LastMethodSuccess == NO) {
    NSLog(@"%@",jws.LastErrorText);
    return;
}

NSLog(@"%@",jwsCompact);