3

我正在尝试使用英特尔的特殊指令集 (AES-NI) 制作 AES 256 位(CBC 模式)加密功能。

到目前为止,这是我的代码:

int Nb = 4;
int Nk = 8;
int Nr = 14;

unsigned int BLOCK_SIZE = 16;

void block_encryption_special(unsigned char input[], unsigned char result[], __m256i *key)
{

    __m256i block = _mm256_loadu_si256((__m256i *) input);

    block = _mm256_xor_si256(block, key[0]);

    for (int i = 1; i < Nr; i++)
    {
        block = _mm256_aesenc_epi128(block, key[i]);
    }

    block = _mm256_aesenclast_epi128(block, key[Nr]);

    _mm256_storeu_si256((__m256i *) result, block);

}

unsigned char* encrypt(unsigned char input[], unsigned int input_length, unsigned  char key[], unsigned char *iv, bool special)
{
    unsigned int i = 0;
    unsigned int total_lenght;
    unsigned int length_padded = (input_length / BLOCK_SIZE);

    if(input_length % BLOCK_SIZE)
    {
        length_padded++;
    }

    length_padded *=  BLOCK_SIZE;

    total_lenght = length_padded;

    unsigned char *align  = null_padding(input, input_length, total_lenght);
    unsigned char *result = new unsigned char[total_lenght];
    unsigned char *block = new unsigned char[BLOCK_SIZE];

    memcpy(block, iv, BLOCK_SIZE);

    for (i = 0; i < total_lenght; i += BLOCK_SIZE)
    {
        block_encryption_special(block, result + i, (__m256i *)key);
        memcpy(block, result + i, BLOCK_SIZE);
    }

    delete[] block;
    delete[] align;

    return result;
}

我想,我做错了什么,因为我得到了空输出。请问我有什么想念的吗?

4

1 回答 1

2

请阅读 memcpy 的文档。第一个参数必须是目标缓冲区。在您的代码中,您将数据复制到块,然后将其删除。在 for 循环中使用 memcpy 也是错误的。您应该增加目标缓冲区指针。

于 2019-11-06T21:23:19.817 回答