poly1305-donna算法如何工作

时间:2016-06-15 16:26:45

标签: c algorithm authentication encryption

我一直在考虑在C中实现poly1305算法,我遇到了这个github项目here

我从未真正做过的一件事(但我需要做的是实现这个算法)是对大数字进行数学运算。上面的链接实现了这个大数学数学,但我似乎无法弄清楚它是如何工作的。

第一步是钳位r(清除特定位)但我不知道为什么r(16字节值)存储在长度为5的32位数字数组中,也不知道如何在此代码中完成钳位。 (U8TO32只是一个小端加载函数)

/* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
st->r[0] = (U8TO32(&key[ 0])     ) & 0x3ffffff;
st->r[1] = (U8TO32(&key[ 3]) >> 2) & 0x3ffff03;
st->r[2] = (U8TO32(&key[ 6]) >> 4) & 0x3ffc0ff;
st->r[3] = (U8TO32(&key[ 9]) >> 6) & 0x3f03fff;
st->r[4] = (U8TO32(&key[12]) >> 8) & 0x00fffff;

这里是乘法,加法和mod步骤。 h只是一个累加器,最初将以全零开始。而且......那之后我就完全迷失了。

s1 = r1 * 5;
s2 = r2 * 5;
s3 = r3 * 5;
s4 = r4 * 5;

/* h += m[i] */
    h0 += (U8TO32(m+ 0)     ) & 0x3ffffff;
    h1 += (U8TO32(m+ 3) >> 2) & 0x3ffffff;
    h2 += (U8TO32(m+ 6) >> 4) & 0x3ffffff;
    h3 += (U8TO32(m+ 9) >> 6) & 0x3ffffff;
    h4 += (U8TO32(m+12) >> 8) | hibit;

    /* h *= r */
    d0 = ((unsigned long long)h0 * r0) + ((unsigned long long)h1 * s4) + ((unsigned long long)h2 * s3) + ((unsigned long long)h3 * s2) + ((unsigned long long)h4 * s1);
    d1 = ((unsigned long long)h0 * r1) + ((unsigned long long)h1 * r0) + ((unsigned long long)h2 * s4) + ((unsigned long long)h3 * s3) + ((unsigned long long)h4 * s2);
    d2 = ((unsigned long long)h0 * r2) + ((unsigned long long)h1 * r1) + ((unsigned long long)h2 * r0) + ((unsigned long long)h3 * s4) + ((unsigned long long)h4 * s3);
    d3 = ((unsigned long long)h0 * r3) + ((unsigned long long)h1 * r2) + ((unsigned long long)h2 * r1) + ((unsigned long long)h3 * r0) + ((unsigned long long)h4 * s4);
    d4 = ((unsigned long long)h0 * r4) + ((unsigned long long)h1 * r3) + ((unsigned long long)h2 * r2) + ((unsigned long long)h3 * r1) + ((unsigned long long)h4 * r0);

    /* (partial) h %= p */
                  c = (unsigned long)(d0 >> 26); h0 = (unsigned long)d0 & 0x3ffffff;
    d1 += c;      c = (unsigned long)(d1 >> 26); h1 = (unsigned long)d1 & 0x3ffffff;
    d2 += c;      c = (unsigned long)(d2 >> 26); h2 = (unsigned long)d2 & 0x3ffffff;
    d3 += c;      c = (unsigned long)(d3 >> 26); h3 = (unsigned long)d3 & 0x3ffffff;
    d4 += c;      c = (unsigned long)(d4 >> 26); h4 = (unsigned long)d4 & 0x3ffffff;
    h0 += c * 5;  c =                (h0 >> 26); h0 =                h0 & 0x3ffffff;
    h1 += c;

0 个答案:

没有答案