zyterence
5/6/2015 - 3:29 AM

random & hmacsha1

random & hmacsha1

- (NSString*)random:(int)length
{
    NSMutableData* data = [NSMutableData dataWithLength:16];
    SecRandomCopyBytes(kSecRandomDefault, 16, data.mutableBytes);
    NSData* base64Result = [data base64EncodedDataWithOptions:0];
    NSString *output = [[NSString alloc] initWithData:base64Result encoding:NSASCIIStringEncoding];
    NSLog(@"%@", output);
    return output;
}

- (NSString *)hmacsha1:(NSString *)text key:(NSString *)secret {
    NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[20];
    CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);

    char base64Result[32];
    size_t theResultLength = 32;
    Base64EncodeData(result, 20, base64Result, &theResultLength);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];

    NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];

    NSLog(@"%@", base64EncodedResult);
    return base64EncodedResult;
}