AES对称加密(AES/ECB/PKCS5Padding)
AES简介
PKCS5Padding
AES源码
做项目要用到AES加密,选择这个开源AES包,其BlockSize是16字节(每16字节数据进行加密)。
PKCS5Padding:以八字节为处理单位,padding的值是:1-7,如果数据的长度为8的整数倍,则还要在待加密的数据后再加八字节的0x08。
aes.c
//aes.c 里的改动
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
{
// The next function call encrypts the PlainText with the Key using AES algorithm.
uintptr_t i;
uint8_t cpbuf[16];
size_t padding;
int num = 0;
num = length%8;
padding = 8-(length%8);
for(i = 0; i < length/16; i++){
Cipher((state_t*)buf, ctx->RoundKey);
buf += AES_BLOCKLEN;
}
if(num != 0)
{
memcpy(cpbuf, buf, length%16);
memset(cpbuf+length%16, padding, 16-length%16);
Cipher((state_t*)cpbuf, ctx->RoundKey);
memcpy(buf, cpbuf, AES_BLOCKLEN);
}
else if(num == 0)
{
if(length %16 != 0)
{
memcpy(cpbuf, buf, 8);
memset(cpbuf+8, 0x08, 8);
Cipher((state_t*)cpbuf, ctx->RoundKey);
memcpy(buf, cpbuf, AES_BLOCKLEN);
}
else
{
memset(cpbuf, 0x08, 8);
Cipher((state_t*)cpbuf, ctx->RoundKey);
memcpy(buf, cpbuf, AES_BLOCKLEN);
}
}
}
//有些问题,但是可以用,解密长度没有计算,接收的数据全解密,大小不一定是接收到的数据大小,
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf, uint32_t length)
{
// The next function call decrypts the PlainText with the Key using AES algorithm.
uintptr_t i;
int num = 0;
num = length%8;
for(i = 0; i < length/16; i++)
{
InvCipher((state_t*)buf, ctx->RoundKey);
buf += AES_BLOCKLEN;
}
InvCipher((state_t*)buf, ctx->RoundKey);
}
main.c
int i;
struct AES_ctx ctx;
int datalen = 17;
int endatalen;//加、解密输出的大小
uint8_t key[] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b , 0x2e};
uint8_t in31[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e};
if(datalen%8)
{
endatalen = 8*(datalen/8+1);
}
else
{
endatalen = datalen+8;
}
printf("\n加密开始\n");
printf("原数据");
for(i = 0; i < datalen; i++)
{
printf("%x ",in[i]);
}
printf("\n");
AES_init_ctx(&ctx, key);
AES_ECB_encrypt(&ctx, in, datalen);
printf("加密后");
for(i = 0; i < endatalen; i++)
{
printf("%x ",in[i]);
}
printf("\n");
AES_ECB_decrypt(&ctx, in, datalen);
printf("解密后");
for(i = 0; i < endatalen; i++)
{
printf("%x ",in[i]);
}
printf("\n");
printf("\n解密结束\n");
具体用法可参考源代码的test.c