How can you generate OTP with system.security.cryp

2019-04-13 14:31发布

问题:

Anyone know where I could find sample code for this with system.security.cryptography namespace -- or instructions followable by a developer?

The purpose is to add two-factor authentication to an asp.net website. On website I want to ask user to enter a passcode (similar to if they got it from a keyfob). On the client side I want to provide a vb.net windows.forms program that generates the correct passcode.

I want to do this with system.security.cryptography namespace on a small scale. I was looking for sample code I don't want to mess with devices or purchase authentication server appliances.

Most of the algorithms out there require an advanced degree in math or are for other platforms such as Linux or PHP. I'm looking for the .net equivalent.

回答1:

The cryptographic parts of RFC4226 (counter-based OTP) or draft-mraihi-totp-timebased (time-based OTP) are relatively simple:

  1. Generate a HMAC based on the shared-key and the counter/time
  2. Truncate it in a secure way

It is usually the user-management and the static/dynamic synchronization that makes it complicated.

Something like this should work:

public static int CalculateHotp(byte[] key, byte[] counter)
{
    var hmacsha1 = new HMACSHA1(key);
    byte[] hmac_result = hmacsha1.ComputeHash(counter);
    int offset = hmac_result[19] & 0x0f;
    int bin_code = (hmac_result[offset]  & 0x7f) << 24
                   | (hmac_result[offset+1] & 0xff) << 16
                   | (hmac_result[offset+2] & 0xff) <<  8
                   | (hmac_result[offset+3] & 0xff);
    int hotp = bin_code % 1000000;
    return hotp;
}