Google Authenticator For Objective C


I am developing an app that used Google Authenticator. For this scenario, The web application generate QRCode via Google Authenticator. And than i read this QRCode to generate OTP via Google Authentication in mobile app. I use below code to create OTP. When i check this created OTP is always wrong. I use Google Authenticator mobile app to check my OTP is correct or wrong.

Any one can help me?

- (NSString *)generateOTPWithCounter:(uint64_t)counter {
CCHmacAlgorithm alg;
NSUInteger hashLength = 0;
alg = kCCHmacAlgSHA256;
hashLength = CC_SHA256_DIGEST_LENGTH;

NSMutableData *hash = [NSMutableData dataWithLength:hashLength];

counter = NSSwapHostLongLongToBig(counter);
NSData *counterData = [NSData dataWithBytes:&counter
CCHmacContext ctx;
CCHmacInit(&ctx, alg, [self.secret bytes], [self.secret length]);
CCHmacUpdate(&ctx, [counterData bytes], [counterData length]);
CCHmacFinal(&ctx, [hash mutableBytes]);

const char *ptr = [hash bytes];
unsigned char offset = ptr[hashLength-1] & 0x0f;
uint32_t truncatedHash =
NSSwapBigIntToHost(*((uint32_t *)&ptr[offset])) & 0x7fffffff;
uint32_t pinValue = truncatedHash % kPinModTable[8];

return [NSString stringWithFormat:@"%0*u", 8, pinValue];


EDIT : i figure out this problem. Now it's working properly. i use below code for NSData

-(NSData *)base32Decode:(NSString *)string {
GTMStringEncoding *coder =
[GTMStringEncoding stringEncodingWithString:kBase32Charset];
[coder addDecodeSynonyms:kBase32Synonyms];
[coder ignoreCharacters:kBase32Sep];
return [coder decode:string error:nil];


asked on Stack Overflow Apr 10, 2017 by Emre Gürses • edited Sep 10, 2018 by Emre Gürses

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0