C ++中AES NI加密的正确方法

问题描述 投票:1回答:1

我正在尝试使用来自英特尔的特殊指令集(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;
}

我认为,我做错了,因为我从中得到空的输出。我想念什么吗?

c++ encryption aes intel aes-ni
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.