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



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

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

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

最新更新