DooDoo
DooDoo

Reputation: 13467

Convert hashed value to a number for Time Based One Time Password (TOTP)

I've read this Github documentation: Otp.NET

In a section there are these codes:

protected internal long CalculateOtp(byte[] data, OtpHashMode mode)
{
    byte[] hmacComputedHash = this.secretKey.ComputeHmac(mode, data);

    // The RFC has a hard coded index 19 in this value.
    // This is the same thing but also accomodates SHA256 and SHA512
    // hmacComputedHash[19] => hmacComputedHash[hmacComputedHash.Length - 1]

    int offset = hmacComputedHash[hmacComputedHash.Length - 1] & 0x0F;
    return (hmacComputedHash[offset] & 0x7f) << 24
            | (hmacComputedHash[offset + 1] & 0xff) << 16
            | (hmacComputedHash[offset + 2] & 0xff) << 8
            | (hmacComputedHash[offset + 3] & 0xff) % 1000000;
    }

I think the last part of above method is convert hashed value to a number but I don't understand the philosophy and the algorithm of it.

1)What is the offset?

2)Why some bytes AND with 0x0f or 0xff?

3)Why in hast line it get Remain for 1000000?

Thanks

Upvotes: 0

Views: 452

Answers (1)

bk2204
bk2204

Reputation: 76864

RFC 4226 specifies how the data is to be calculated from the HMAC value.

First, the bottom four bits of the last byte are used to determine a starting offset into the HMAC value. This was done so that even if an attacker found a weakness in some fixed portion of the HMAC output, it would be hard to leverage that directly into an attack.

Then, four bytes, big-endian, are read from the HMAC output starting at that offset. The top bit is cleared, to prevent any problems with negative numbers being mishandled, since some languages (e.g., Java) don't provide native unsigned numbers. Finally, the lower N digits are taken (which is typically 6, but sometimes 7 or 8). In this case, the implementation is hard-coded to 6, hence the modulo operation.

Note that due to operator precedence, the bitwise-ors bind more tightly than the modulo operation. This implementer has decided that they'd like to be clever and have not helped us out by adding an explicit pair of parentheses, but in the real world, it's nice to help the reader.

Upvotes: 1

Related Questions