0

I'm searching for a hmac-sha1 code sample in objective-c I saw this sample and it looks clear and readable, the problem is that there is there one unclear line:

NSString *hash = [HMAC base64Encoding];

And the guy said that base64Encoding is a custom code of his...

Can you help me fill the blank and advice what i need to put there instead?

Thanks.

Community
  • 1
  • 1
Nir
  • 2,497
  • 9
  • 42
  • 71
  • Did you get this working as i am looking to create a signature for AWS SES. – mmkd Mar 22 '12 at 11:00
  • It works, but I couldn't make sure if it does the job right.. – Nir Apr 25 '12 at 11:51
  • Thank you very much. I was able to get this sorted thank you, using another method, so i can not confirm nor deny this approach. – mmkd Apr 27 '12 at 12:06

1 Answers1

1

I usually make it in a category like this:

[NSString base64forData:HMAC];

And here is the method you can use:

+ (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Artem
  • 940
  • 1
  • 7
  • 24
  • Very nice category indeed, will definitely come in useful for some! – Sebastien Peek Feb 23 '12 at 10:33
  • I tries to call this function like that: NSString *hash = [self base64Encoding:HMAC]; but it throws exception: 'NSInvalidArgumentException', reason: '-[ViewController base64Encoding:]: unrecognized selector sent to instance – Nir Feb 25 '12 at 14:48
  • If declare it in your ViewController(which is not good), use `-(NSString *)` instead of `+(NSString *)` – Artem Feb 27 '12 at 11:10