Google Authenticator For Objective C

2019-07-27 05:58发布

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
                                     length:sizeof(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];

}

0条回答
登录 后发表回答