我刚刚完成了与您的问题类似的事情。我需要使用 JWT 将数据发布到 GCP IoT。这是我使用 RSAWithSHA256 所做的:
使用库MIHCrypto(在 Podfile pod "MIHCrypto", "~> 0.4.1" 中)
#import "MIHAESKeyFactory.h"
#import "MIHRSAPrivateKey.h"
(void) createJWT {
NSMutableDictionary *headerDict = [NSMutableDictionary new];
headerDict[@"alg"] = @"RS256";
headerDict[@"typ"] = @"JWT";
NSMutableDictionary *payloadDict = [NSMutableDictionary new];
payloadDict[@"aud"] = @"my project";
NSDate *now = [NSDate new];
payloadDict[@"iat"] = [NSNumber numberWithInt:[now timeIntervalSince1970]];
payloadDict[@"exp"] = [NSNumber numberWithInt:[now timeIntervalSince1970] + 20 * 60];
NSError *error;
NSData *headerData = [NSJSONSerialization dataWithJSONObject:headerDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSData *payloadData = [NSJSONSerialization dataWithJSONObject:payloadDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *base64UrlMessage = [NSString stringWithFormat:@"%@.%@", [self base64UrlforData:headerData ], [self base64UrlforData:payloadData]];
NSData *privateKeyData = [[self pemKeyStringFromFileWithName:@"myPrivateKey" extension:@"pem"] dataUsingEncoding:NSUTF8StringEncoding];
MIHRSAPrivateKey *privateKey = [[MIHRSAPrivateKey alloc] initWithData:privateKeyData];
NSError *signingError = nil;
NSData *signedData = [privateKey signWithSHA256:[base64UrlMessage dataUsingEncoding:NSUTF8StringEncoding] error:&signingError];
NSString *signedBase64UrlMessage = [self base64UrlforData: signedData];
NSString *jwt = [NSString stringWithFormat:@"%@.%@", base64UrlMessage, signedBase64UrlMessage];
NSLog(@"jwt = %@", jwt);
}
(NSString*)base64UrlforData:(NSData*)data {
// base64 to base64URL
// 1 - remove all '='
// 2 - replace all '+' by '-'
// 3 - replace all '/' by '_'
NSString *base64 = [data base64EncodedStringWithOptions:0];
NSString *base64_1 = [base64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
NSString *base64_2 = [base64_1 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
NSString *base64_3 = [base64_2 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return base64_3;
}
(NSString *)pemKeyStringFromFileWithName:(NSString *)name extension: (NSString*) extension {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *fileURL = [bundle URLForResource:name withExtension:extension];
NSError *error = nil;
NSString *fileContent = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"%@ error: %@", self.debugDescription, error);
return nil;
}
return fileContent;
}