【Linux】C语言实现对文件的加密算法

异或加密

解密方式是进行第二次加密后自动解密

#define BUF_SIZE (16384)    //16k
/**************************************************************
功能描述: 加密实现
输入参数: 
---------------------------------------------------------------
修改作者: 
修改日期: 
修改说明:新增
***************************************************************/
void log_encrypt(char *data, int dataLen, const char *key)
{
    int n = 0;
    //对data的每一个字符和key进行按位异或
    for(n = 0; n < dataLen; n++)
    {
        *data = *data ^ 0x09;
        data++;
    }
}

/**************************************************************
功能描述: log文件加密
输入参数: 
---------------------------------------------------------------
修改作者: 
修改日期: 
修改说明:新增
***************************************************************/
unsigned int log_encryptFile(char *srcFileName)
{
    char *key = "google";
    int  srcFd = -1;
    int  dstFd = -1;
    char *tmpBuf = NULL;
    int  tmpLen = 0;
    int  writLen = 0;

    log_printf("start: CountFile build date: %s, [%s, %d]\n", __DATE__, __FUNCTION__, __LINE__);

    if (!srcFileName)
    {
        log_printf("srcFileName err![%s, %d]\n", __FUNCTION__, __LINE__);
        return EXIT_FAILURE;
    }

    srcFd = open(srcFileName, O_RDWR);
    log_printf("srcFileName:[%s] fd:[%d]\n", srcFileName, srcFd);
    if (srcFd < 0)
    {
        log_printf("open src file failed! [err:%d:%s]\n", errno, strerror(errno));
        return EXIT_FAILURE;
    }

    log_printf("file size:[%d]\n", lseek(srcFd, 0, SEEK_END));
    lseek(srcFd, 0, SEEK_SET);

    tmpBuf = (char *)malloc(BUF_SIZE);
    if (!tmpBuf)
    {
        log_printf("malloc buf failed! [err:%d:%s]\n", errno, strerror(errno));
        close(srcFd);
        return EXIT_FAILURE;
    }

    while((tmpLen = read(srcFd, tmpBuf, BUF_SIZE)) > 0)
    {
        //加密数据
        log_encrypt(tmpBuf, tmpLen, key);
        //指针会到此包开始处
        lseek(srcFd, -tmpLen, SEEK_CUR);
        //写文件
        writLen = write(srcFd, tmpBuf, tmpLen);
        if (writLen < 0)
        {
            log_printf("write err,Error: %s\n", strerror(errno));
        }
    }

    close(srcFd);
    free(tmpBuf);

    log_printf("end: ok: [%s, %d]\n", __FUNCTION__, __LINE__);

    return EXIT_SUCCESS;
}

AES加密

AES的算法时间复杂度最低,256K时间如下:
在这里插入图片描述
在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>

#define BLOCK_SIZE 16
#define KEY_BIT 256
#define IV_SIZE BLOCK_SIZE
#define KEY_SIZE (KEY_BIT/8)
#define JIEMI_SWITCH		1	//解密开关
// Generate IV
unsigned char iv[IV_SIZE] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};

void file_encrypt(char* filename) {
    FILE* fp = fopen(filename, "rb");
    FILE* outfp = fopen("encrypted.tmp", "wb");
    if(fp == NULL) {
        printf("Can't open file.\n");
        return;
    }

    // Generate key
    unsigned char key[KEY_SIZE];
    SHA256((unsigned char*)"google", strlen("google"), key);

    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    if(EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
        printf("Failed to initialize encryption.\n");
        return;
    }

    unsigned char data_block[BLOCK_SIZE];
    unsigned char encrypt_block[BLOCK_SIZE + EVP_MAX_BLOCK_LENGTH];
    int out_len;

    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    unsigned char* buffer = (unsigned char*)malloc(file_size + EVP_MAX_BLOCK_LENGTH);
    fread(buffer, 1, file_size, fp);

    for(long i = 0; i < file_size; i += BLOCK_SIZE) {
        memcpy(data_block, buffer + i, BLOCK_SIZE);
        if(i + BLOCK_SIZE > file_size) {
            for(int j = file_size % BLOCK_SIZE; j < BLOCK_SIZE; ++j)
                data_block[j] = BLOCK_SIZE - (file_size % BLOCK_SIZE);
        }
        if(EVP_EncryptUpdate(ctx, encrypt_block, &out_len, data_block, BLOCK_SIZE) != 1) {
            printf("Failed to encrypt block.\n");
            return;
        }
        fwrite(encrypt_block, 1, out_len, outfp);
    }

    if(EVP_EncryptFinal_ex(ctx, encrypt_block, &out_len) != 1) {
        printf("Failed to finish encryption.\n");
        return;
    }
    fwrite(encrypt_block, 1, out_len, outfp);

    free(buffer);
    fclose(fp);
    fclose(outfp);
    rename("encrypted.tmp", filename);
    EVP_CIPHER_CTX_free(ctx);
}

void file_decrypt(char* filename) {
    FILE* fp = fopen(filename, "rb");
    FILE* outfp = fopen("decrypted.tmp", "wb");
    if(fp == NULL) {
        printf("Can't open file.\n");
        return;
    }

    // Generate key
    unsigned char key[KEY_SIZE];
    SHA256((unsigned char*)"google", strlen("google"), key);

    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    if(EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
        printf("Failed to initialize decryption.\n");
        return;
    }

    unsigned char data_block[BLOCK_SIZE];
    unsigned char decrypt_block[BLOCK_SIZE + EVP_MAX_BLOCK_LENGTH];
    int out_len;

    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    unsigned char* buffer = (unsigned char*)malloc(file_size + EVP_MAX_BLOCK_LENGTH);
    fread(buffer, 1, file_size, fp);

    for(long i = 0; i < file_size; i += BLOCK_SIZE) {
        memcpy(data_block, buffer + i, BLOCK_SIZE);
        if(EVP_DecryptUpdate(ctx, decrypt_block, &out_len, data_block, BLOCK_SIZE) != 1) {
            printf("Failed to decrypt block.\n");
            return;
        }
        fwrite(decrypt_block, 1, out_len, outfp);
    }

    if(EVP_DecryptFinal_ex(ctx, decrypt_block, &out_len) != 1) {
        printf("Failed to finish decryption.\n");
        return;
    }
    fwrite(decrypt_block, 1, out_len, outfp);

    free(buffer);
    fclose(fp);
    fclose(outfp);
    rename("decrypted.tmp", filename);
    EVP_CIPHER_CTX_free(ctx);
}

int main(int argc, char **argv) {
    if(argc != 2) {
        printf("Usage: %s <file>\n", argv[0]);
        return 1;
    }

    char *srcFileName = argv[1];
#if JIEMI_SWITCH
    file_encrypt(srcFileName);
    printf("加密成功\n");
#else
    file_decrypt(srcFileName);
    printf("解密成功\n");
#endif
    return 0;
}

简单加密

它只是对输入文件进行简单的异或加密操作,使用一个字符串作为密钥
时间复杂度较高,对257K的文件加密,要33s
在这里插入图片描述

/**************************************************************
修改作者:wangjj
修改日期:9/25/2023
修改说明:新增
***************************************************************/
unsigned int log_encryptFile(char *srcFileName)
{
    char *key = "hualaixiaofang";
    int keyLen = strlen(key);
    int ch;
    int i = 0;

    log_printf("encrytFile begin [%s,%d\n]", __FUNCTION__, __LINE__);

    if (!srcFileName || !key)
    {
        log_printf("param err! error:%s [%s,%d]\n", strerror(errno), __FUNCTION__, __LINE__);
        return EXIT_FAILURE;
    }	

    FILE *file = fopen(srcFileName, "rb+");
    if (file == NULL)
    {
        log_printf("open file failed!!, error:%s [%s,%d]\n", strerror(errno), __FUNCTION__, __LINE__);
        return EXIT_FAILURE;
    }

    while ((ch = fgetc(file)) != EOF)
    {
        // 对每个字符和key的对应字符进行加密操作
        ch = ch + key[i];
        
        // 将加密后的字符写回文件
        fseek(file, -1, SEEK_CUR);
        fputc(ch, file);
        
        // 更新key的位置
        i = (i + 1) % keyLen;
    }
    log_printf("encrytFile end [%s,%d\n]", __FUNCTION__, __LINE__);
    fclose(file);
}

编译方式

gcc -o decrypt_program_jiemi AES_encrypt.c -lcrypto

mbedtls加密


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mbedtls/aes.h"

#define KEY_SIZE 32 // 256位密钥
#define BLOCK_SIZE 16 // 128位分组

int log_encryptFile(const char* input_file) {
    
    // 打开输入文件
    FILE* input = fopen(input_file, "rb");
    if (input == NULL) {
        printf("无法打开输入文件\n");
        return -1;
    }
    const unsigned char key[KEY_SIZE] = "wjj";
    // 计算输入文件大小
    fseek(input, 0, SEEK_END);
    long input_size = ftell(input);
    fseek(input, 0, SEEK_SET);

    // 创建输出缓冲区
    unsigned char* output = (unsigned char*)malloc(input_size);
    if (output == NULL) {
        printf("内存分配失败\n");
        fclose(input);
        return -1;
    }

    // 初始化加密上下文
    mbedtls_aes_context ctx;
    mbedtls_aes_init(&ctx);
    mbedtls_aes_setkey_enc(&ctx, key, KEY_SIZE * 8);

    // 加密文件内容
    unsigned char input_block[BLOCK_SIZE];
    unsigned char output_block[BLOCK_SIZE];
    size_t offset = 0;
    size_t read_bytes;
    while ((read_bytes = fread(input_block, 1, BLOCK_SIZE, input)) > 0) {
        mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, input_block, output_block);
        memcpy(output + offset, output_block, read_bytes);
        offset += read_bytes;
    }

    // 关闭文件和释放资源
    fclose(input);
    mbedtls_aes_free(&ctx);

    // 打开输入文件,以写入方式覆盖原内容
    input = fopen(input_file, "wb");
    if (input == NULL) {
        printf("无法打开输入文件\n");
        free(output);
        return -1;
    }

    // 将加密后的内容写入输入文件
    fwrite(output, 1, input_size, input);

    // 关闭文件和释放资源
    fclose(input);
    free(output);

    printf("文件加密完成\n");

    return 0;
}

int log_decryptFile(const char* input_file) {
    // 打开输入文件
    FILE* input = fopen(input_file, "rb");
    if (input == NULL) {
        printf("无法打开输入文件\n");
        return -1;
    }
    const unsigned char key[KEY_SIZE] = "wjj";
    // 计算输入文件大小
    fseek(input, 0, SEEK_END);
    long input_size = ftell(input);
    fseek(input, 0, SEEK_SET);

    // 创建输出缓冲区
    unsigned char* output = (unsigned char*)malloc(input_size);
    if (output == NULL) {
        printf("内存分配失败\n");
        fclose(input);
        return -1;
    }

    // 初始化解密上下文
    mbedtls_aes_context ctx;
    mbedtls_aes_init(&ctx);
    mbedtls_aes_setkey_dec(&ctx, key, KEY_SIZE * 8);

    // 解密文件内容
    unsigned char input_block[BLOCK_SIZE];
    unsigned char output_block[BLOCK_SIZE];
    size_t offset = 0;
    size_t read_bytes;
    while ((read_bytes = fread(input_block, 1, BLOCK_SIZE, input)) > 0) {
        mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_DECRYPT, input_block, output_block);
        memcpy(output + offset, output_block, read_bytes);
        offset += read_bytes;
    }

    // 关闭文件和释放资源
    fclose(input);
    mbedtls_aes_free(&ctx);

    // 打开输入文件,以写入方式覆盖原内容
    input = fopen(input_file, "wb");
    if (input == NULL) {
        printf("无法打开输入文件\n");
        free(output);
        return -1;
    }

    // 将解密后的内容写入输入文件
    fwrite(output, 1, input_size, input);

    // 关闭文件和释放资源
    fclose(input);
    free(output);

    printf("文件解密完成\n");

    return 0;
}
// 编译方式:gcc -o decrypt-jiami AES_encrypt.c -lmbedtls -lmbedcrypto -lmbedx509
int main(int argc, char **argv) {
    if(argc != 2) {
        printf("Usage: %s <file>\n", argv[0]);
        return 1;
    }

    char *srcFileName = argv[1];

    if (log_encryptFile(srcFileName) != 0) {
        printf("加密文件失败\n");
        return -1;
    }
    printf("文件加密完成\n");
 

#if 0
    if (log_decryptFile(srcFileName) != 0) {
        printf("解密文件失败\n");
        return -1;
    }

   printf("解密成功\n");
#endif 
    return 0;
}

编译方式

gcc -o decrypt-jiami AES_encrypt.c -lmbedtls -lmbedcrypto -lmbedx509
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
混沌图像加密算法是一种利用混沌系统的特性对图像进行加密和解密的算法。混沌系统的特点是具有无法预测性、灵敏依赖于初值的特点,可以产生看似随机的序列。 在C语言实现混沌图像加密算法,可以采用以下步骤: 1. 读取需要加密的图像文件,并将图像数据保存到内存中。 2. 选择合适的混沌系统模型作为密钥生成器。例如,可以选择Logistic Map(逻辑映射)或Henon Map(Henon映射)等模型。 3. 设计混沌系统参数以及初始值,并进行迭代计算。根据模型的不同,可以设置不同的迭代次数和初始值。 4. 将生成的混沌序列作为密钥,对图像进行像素级加密。可以使用异或运算或置换等方式进行加密处理。 5. 对加密后的图像数据进行存储,生成加密后的图像文件。 6. 若要解密图像,需要按照相同的密钥生成器和参数设置,提取出密钥序列。 7. 使用提取的密钥序列对加密的图像数据进行解密操作。同样可以采用异或运算或置换等方式进行解密处理。 8. 对解密后的图像数据进行存储,生成解密后的图像文件。 需要注意的是,混沌图像加密算法虽然具有一定的安全性,但并不是绝对安全的加密算法,可能在某些情况下被攻破。因此,在实际应用中,还需要考虑其他方法来增强图像的安全性,如结合其他加密算法或者对混沌系统进行改进等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值