AES128-ECB对文件进行加密解密验证
Posted 旧年不在cd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES128-ECB对文件进行加密解密验证相关的知识,希望对你有一定的参考价值。
AES128-ECB对文件进行加密解密验证
一、源码函数讲解
#ifndef __AES_H__
#define __AES_H__
#include <stdint.h>
/* generate expanded key */
参数:key 128bit的密钥
ekey 扩展后的密钥(11*16byte)
void AES_KeySchedule(uint8_t *key, uint8_t *ekey); //扩展密钥
/* perform encryption */
参数:ekey 扩展后的密钥(11*16byte)
state 要加密的128bit数据,加密后的数据也存放在这里
void AES_Encrypt(uint8_t *ekey, uint8_t *state); //加密
/* perform decryption */
参数:ekey 扩展后的密钥(11*16byte)
state 要解密的128bit数据,解密后的数据也存放在这里
void AES_Decrypt(uint8_t *ekey, uint8_t *state); //解密
#endif
二、demo验证
#include "stdio.h"
#include "unistd.h"
#include "fcntl.h"
#include "aes.h"
#include "string.h"
//密钥,随机生成即可
uint8_t key[16] = 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88;
uint8_t buff[16] = 0;
char *input_file = "./IAP_Pile.bin"; //要加密文件路径
char *enc_file = "./enc.bin"; //加密后的文件路径
char *dec_file = "./dec.bin"; //解密后的文件路径
int main(void)
//存放扩展密钥的数组
uint8_t ekey[176] = 0;
FILE *input_fp = NULL;
FILE *enc_fp = NULL;
FILE *dec_fp = NULL;
int Ret = 0;
//根据密钥生成扩展密钥
AES_KeySchedule(key, ekey);
input_fp = fopen(input_file, "rb");
if (NULL == input_fp)
perror("fail to fopen!\\r\\n");
return -1;
enc_fp = fopen(enc_file, "wb+");
if (NULL == enc_fp)
perror("fail to fopen!\\r\\n");
return -1;
dec_fp = fopen(dec_file, "wb+");
if (NULL == dec_fp)
perror("fail to fopen!\\r\\n");
return -1;
printf("加密文件...\\r\\n");
while (1)
memset(buff, 0, sizeof(buff));
Ret = fread(buff, 1, sizeof(buff), input_fp);
// printf("Ret = %d\\r\\n", Ret);
if (Ret <= 0)
break;
//加密
AES_Encrypt(ekey, buff);
fwrite(buff, 1, 16, enc_fp);
printf("文件加密成功,输出文件为:%s\\r\\n", enc_file);
fseek(enc_fp, 0, SEEK_SET);
printf("解密文件...\\r\\n");
while (1)
memset(buff, 0, sizeof(buff));
Ret = fread(buff, 1, sizeof(buff), enc_fp);
// printf("Ret = %d\\r\\n", Ret);
if (Ret <= 0)
break;
//解密
AES_Decrypt(ekey, buff);
fwrite(buff, 1, 16, dec_fp);
printf("文件解密成功,输出文件为:%s\\r\\n", dec_file);
fclose(input_fp);
fclose(enc_fp);
fclose(dec_fp);
return 0;
以上是关于AES128-ECB对文件进行加密解密验证的主要内容,如果未能解决你的问题,请参考以下文章