C語言寫的一個簡單文件加密程序:
- #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 幫助
輸出的加密文件中的內容: