PKCS#5 padding for AES encryption in C/C++

被刻印的时光 ゝ 提交于 2020-01-15 05:30:11

问题


I did AES/ECB/PKCS5Padding encryption in JAVA. Now I am looking for equivalent method in C/C++. I did manage to encrypt in C using the following code :

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;
}

回答1:


When using padding it must always be added, even if the input is a multiple of the block size.

Incorrect, this is a common mistake:

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

Correct:

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

See PKCS#7 padding.



来源:https://stackoverflow.com/questions/37145563/pkcs5-padding-for-aes-encryption-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!