C语言写的一个简单文件加密程序

本文介绍了一个简单的文件加密和解密程序,使用C语言编写。该程序能够读取输入文件内容,通过特定算法进行加密或解密,并将结果写入输出文件。支持命令行参数指定操作类型(加密或解密)、输入文件及输出文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int decrypt(FILE *in,FILE *out);
int encrypt(FILE *in,FILE *out);
unsigned char atoh(char *hexstr);

int main(int argc,char **argv)
{
	if(argc > 1 && strcmp(argv[1],"--help") == 0)
	{
		printf("\nusage: linkrules_god [-e|-d] inputfile outputfile\n");
		printf("    -e encrypt inputfile to outputfile.\n");
		printf("    -d decrypt inputfile to outputfile.\n\n");
		exit(0);
	}
	if(argc != 4)
	{
		fprintf(stderr,"%s\n","please using --help go get help.");
		exit(-1);
	}

    
	FILE *in = fopen(argv[2],"rb");
	FILE *out = fopen(argv[3],"w");
    if(in == NULL || out == NULL)
	{
		fprintf(stderr,"%s\n","open file error!");
        exit(1);
	}

    if(argv[1][1] == 'e')
    {
        encrypt(in,out);
    }
    else if(argv[1][1] == 'd')
    {
        decrypt(in,out);
    }

    fclose(in);
    fclose(out);
	return 0;
}

int encrypt(FILE *in,FILE *out)
{
    if(in == NULL || out == NULL)
    {
        fprintf(stderr,"%s\n","file error!\n");
        return -1;
    }

    unsigned char hex;
    while(fread(&hex,1,1,in))
    {
        hex = ~hex^0x92;
        fprintf(out,"%02X",hex);
    }
    return 0;
}



int decrypt(FILE *in,FILE *out)
{
    if(in == NULL || out == NULL)
    {
        fprintf(stderr,"%s\n","file error!");
        return -1;
    }
    
    unsigned char hexstr[3];
    unsigned char hex = 0;
    int i = 0;
    while(fread(&hexstr,2,1,in))
    {
        hex = atoh(hexstr);
        hex = ~(hex ^ 0x92);
        fwrite(&hex,1,1,out);
    }

    return 0;
}


/* convert string to hex */
unsigned char atoh(char *hexstr)
{
    int hextodec[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    char chtodec[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    unsigned char hexnum = 0;
    for(int i = 0; i < sizeof(chtodec); ++i)
    {
        if(hexstr[0] == chtodec[i])
        {
            hexnum += hextodec[i]*16;
        }
    }

    for(int i = 0; i < sizeof(chtodec); ++i)
    {
        if(hexstr[1] == chtodec[i])
        {
            hexnum += hextodec[i];
        }
    }

    return hexnum;
}



encrypt -e sourcefile outputfile   加密

encrypt -d sourcefile outputfile   解密

encrypt --help    帮助


输出的加密文件中的内容:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值