使用C和Gcrypt实现TOTP

时间:2015-08-19 13:31:38

标签: c otp libgcrypt

我正在尝试使用C和libgcrypt实现一个简单的TOTP客户端 我已经阅读了RFC 6238RFC 4226,但我仍然遇到了一些问题。

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <gcrypt.h>

int DIGITS_POWER[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000};

int Truncate (unsigned char *hmac, int N)
{
    // uint64_t O = least_four_significant_bits_hmac;
    int O = (hmac[19] & 0x0f);
    int bin_code = ((hmac[O] & 0x7f) << 24) | ((hmac[O+1] & 0xff) << 16) | ((hmac[O+2] & 0xff) << 8) | ((hmac[O+3] & 0xff));
    printf("%d\n", bin_code);
    int token = bin_code % DIGITS_POWER[N];
    return token;
}

unsigned char *HMAC (char *K, long C)
{
    // K is the key, C is the message
    unsigned char *buffer = (unsigned char *)&C;
    gcry_md_hd_t hd;
    gcry_md_open (&hd, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
    gcry_md_setkey (hd, K, strlen(K));
    gcry_md_write (hd, buffer, 4); // 4 because C is (in hex) 0273EF07
    gcry_md_final (hd);
    unsigned char *hmac =  gcry_md_read (hd, GCRY_MD_SHA1);
    return hmac;
}


int HOTP (char *K, long C, int N)
{
    unsigned char *hmac = HMAC(K, C);
    int token = Truncate (hmac, N);
    return token;
}


int TOTP (char *K, int N)
{
    long TC = 1234567890/30;// ((uint64_t) time (NULL))/30;
    return HOTP(K, TC, N);
}

int main (void)
{
    printf ("%d\n", TOTP("12345678901234567890", 6));
    return 0;
}

根据Appendix-B中编写的测试向量,如果我使用TC=1234567890/30secret_key="12345678901234567890",我应该收到89005924作为TOTP值,但相反,我会收到{{} 1}}。
我的代码出了什么问题? : - /
感谢

0 个答案:

没有答案