How can you generate OTP with system.security.cryptography that can be authenticated on client?

↘锁芯ラ 提交于 2019-12-04 16:53:08

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!