上班访问外网限制,只能访问csdn,个人练习工程代码
文件读取 1k字节解密加密 256bit cbc模式 mbedtls加密 openssl解密
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <openssl/aes.h>
#include <mbedtls/aes.h>
#include <mbedtls/rsa.h>
// gcc -o test_mbedtls_256 mbedtls_aes256.c -lssl -lcrypto -lmbedtls -lmbedcrypto
#define BLOCK_SIZE 1024
#define TEST_AES_BLOCK_SIZE 32
#define VI_SET '0'
#define ENCRYP_FILE "lala_encryp.c"
#define DECRYP_FILE "lala_decryp.c"
#define AES_KEY "0123456789abcdeffedcba9876543210"
char srcBuff[BLOCK_SIZE] = {
0};
char desBuff[BLOCK_SIZE] = {
0};
int MbedtlsEncrypFile(const char *path)
{
int ret;
int temp;
int fileLen;
int readLen;
mbedtls_aes_context ctx;
unsigned char ivec[16] = {
0};
unsigned char key[TEST_AES_BLOCK_SIZE];
memset(ivec, VI_SET, sizeof(ivec));
memcpy(key, AES_KEY, sizeof(key));
FILE *sfp = fopen(path, "r");
if (sfp == NULL) {
printf("open [%s] error \n", path);
return -1;
}
FILE *dfp = fopen(ENCRYP_FILE, "a+");
if (dfp == NULL) {
printf("open [%s] error \n", ENCRYP_FILE);
return -1;
}
fseek(sfp , 0, SEEK_END);
fileLen = ftell(sfp);
fseek(sfp , 0, SEEK_SET);
printf("[%s] fileLen is %d\n", path, fileLen);
temp = fileLen;
mbedtls_aes_init(&ctx);
ret = mbedtls_aes_setkey_enc(&ctx, key, 256);
while (fileLen > 0) {
if (fileLen > BLOCK_SIZE) {
readLen = BLOCK_SIZE;
} else if ((fileLen % TEST_AES_BLOCK_SIZE) == 0) {
readLen = fileLen;
} else {
readLen = ((fileLen / TEST_AES_BLOCK_SIZE) + 1) * TEST_AES_BLOCK_SIZE;
}
fileLen -= readLen;
memset(srcBuff, 0, sizeof(srcBuff));
memset(desBuff, 0, sizeof(desBuff));
fread(srcBuff, 1, readLen, sfp);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, readLen, ivec, (unsigned char *)srcBuff, (unsigned char *)desBuff);
// 此处不能截断文件,每个字节都是加密的数据,解密需要使用,使用temp返回源文件大小
//if (fileLen < 0) {
// readLen += fileLen;
//}
fwrite(desBuff, 1, readLen, dfp);
}
fclose(sfp);
fclose(dfp);
return temp;
}
int OpensslDncrypFile(