SwiftMatt
SwiftMatt

Reputation: 1029

How do obtain the NSString equivalent for an array of chars in Objective-C?

More specifically, I put a breakpoint in my code after NSString *signStr = [NSString stringWithCString:text encoding:NSASCIIStringEncoding]; I am calling the function with secret= @"12345678901234567890" and movingFactor = 1 I noticed that at the breakpoint, signStr is an empty string, also are there any other noticeable errors in the code? Thanks

-(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;

}

Upvotes: 0

Views: 215

Answers (1)

Kevin Grant
Kevin Grant

Reputation: 5431

To be a "C string" it has to be terminated by a zero ('\0'). If movingFactor is 1 then the last character will be 0x01, and the first (and every other byte) is zero due to shifting. This makes the first character zero, which makes the string "empty".

Upvotes: 1

Related Questions