AESUnwrap纯C函数

C/C++代码 blackfeather


有缘人拿去。。。RFC 3394,AESUnwrap。。。某些情况下使用的。


uint8_t AES_unwrap(uint8_t *kek, uint16_t key_len, uint8_t *cipher_text, uint16_t cipher_len, uint8_t *output)
{
    uint8_t a[8], b[16];
    uint8_t *r;
    uint8_t *c;
    uint16_t i, j, n;
    AES_KEY ctx;

    if (! kek || cipher_len < 16 || ! cipher_text || ! output)
    {
        /* We don't do anything with the return value */
        return 1;
    }

    /* Initialize variables */

    n = (cipher_len/8)-1;  /* the algorithm works on 64-bits at a time */
    memcpy(a, cipher_text, 8);
    r = output;
    c = cipher_text;
    memcpy(r, c+8, cipher_len - 8);

    /* Compute intermediate values */
    for (j=5; j >= 0; --j)
    {
        r = output + (n - 1) * 8;
        /* DEBUG_DUMP("r1", (r-8), 8); */
        /* DEBUG_DUMP("r2", r, 8); */
        for (i = n; i >= 1; --i)
        {
            uint16_t t = (n*j) + i;
            /* DEBUG_DUMP("a", a, 8); */
            memcpy(b, a, 8);
            b[7] ^= t;
            /* DEBUG_DUMP("a plus t", b, 8); */
            memcpy(b+8, r, 8);
            AES_set_decrypt_key(kek, 128, &ctx);
            AES_decrypt(b, b, &ctx);  /* NOTE: we are using the same src and dst buffer. It's ok. */
            /* DEBUG_DUMP("aes decrypt", b, 16) */
            memcpy(a,b,8);
            memcpy(r, b+8, 8);
            r -= 8;
        }
    }

    /* DEBUG_DUMP("a", a, 8); */
    /* DEBUG_DUMP("output", output, cipher_len - 8); */

    return 0;
}


评论列表:

发表评论: