更具体地说,我在
NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding];
调用函数后在代码中放置了一个断点secret= @"12345678901234567890"
,movingFactor = 1
我注意到在断点处,signStr
是一个空字符串,代码中是否还有其他明显的错误?谢谢
-(NSString*) generateOTP:(NSString*) secret with:(uint64_t) movingFactor
{
NSString* result;
const int DIGITS = 6;
const int SIX_DIGITS = 1000000;
char text[8];
for (int i = 7; i >= 0; i--) {
text[i] = movingFactor & 0xff;
movingFactor >>= 8;
}
NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding];
NSString* hash = [self sha1UseKey:secret toSign:signStr];
int offset = [hash characterAtIndex:[hash length] - 1] & 0xf;
int binary = (([hash characterAtIndex:offset] & 0x7f) << 24) |
(([hash characterAtIndex:offset+1] & 0xff) << 16) |
(([hash characterAtIndex:offset+2] & 0xff) << 8) | ([hash characterAtIndex:offset+3] & 0xff);
int otp = binary % SIX_DIGITS;
result = [NSString stringWithFormat:@"%d", otp];
NSString* zero = @"0";
while ([result length] < DIGITS) {
result = [zero stringByAppendingString:result];
}
return result;
}