0

更具体地说,我在 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;

}
4

1 回答 1

1

要成为“C 字符串”,它必须以零 ( '\0') 结尾。如果movingFactor是 1,那么最后一个字符将是0x01,并且第一个(以及每隔一个字节)由于移位而为零。这使第一个字符为零,这使字符串“空”。

于 2012-07-28T05:41:49.230 回答