我在AES/ECB/PKCS5Padding中做了JAVA加密。现在,我正在C/C++中寻找等效的方法。我确实使用以下代码在C中进行了加密:

const unsigned char *key = (unsigned char *)"A2XTXFEQFOPZFAKXFOPZFAK5";
unsigned char input[] = {"Hello World"};
int iLen = strlen((char*)input);
int len = 0;
if(iLen % 16 == 0){
   len = iLen;
}
else{
   len = (iLen/16)*16 + 16;
}
unsigned char output[len]; //next 16bit

AES_KEY enc_key;
AES_set_encrypt_key(key, strlen((char*)key)*8, &enc_key);
int position = 0;
while(position < iLen){
    AES_ecb_encrypt(input+position,output+position,&enc_key,AES_ENCRYPT);
    position += 16;
}

最佳答案

使用填充时,即使输入是块大小的倍数,也必须始终添加

错误,这是一个常见错误:

if(iLen % 16 == 0){
    len = iLen;
}

正确:
int blockSize = 16;
int len = iLen + blockSize - (iLen % blockSize);

参见PKCS#7 padding

09-26 17:05