问题
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