代码见下面,编译之后就可以用;建议放在bash下,或者添加环境变量。
使用方法:encrypt <文件名>。两次输入密码。加密密码与解密密码不一致解码后就不是原文件了!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int decrypt(FILE *in,FILE *out);
int encrypt(FILE *in,FILE *out);
int passlen;
char pass[105],passa[105];
int main(int argc,char **argv)
{
if(argc != 2)
{
printf("\n请输入文件名进行加密或者解密!\n");
printf(" encrypt <inputfile>\n\n");
exit(0);
}
while(1)
{
printf("Enter password:");
system("stty -icanon");
system("stty -echo");
scanf("%s",pass);
system("stty icanon");
system("stty echo");
printf("\nEnter password again:");
system("stty -icanon");
system("stty -echo");
scanf("%s",passa);
system("stty icanon");
system("stty echo");
if(strcmp(pass,passa)==0) break;
printf("\nPassword is inconsistent\n");
}
printf("\n");
FILE *in = fopen(argv[1],"rb");
FILE *out = fopen("encrypt-tmp","w");
passlen=strlen(pass);
char code=0xAA;
for(int i=0;i<passlen;i++) pass[i]=pass[i]^code;
if(in == NULL || out == NULL)
{
fprintf(stderr,"%s\n","open file error!");
exit(1);
}
encrypt(in,out);
fclose(in);
fclose(out);
remove(argv[1]);
rename("encrypt-tmp",argv[1]);
return 0;
}
int encrypt(FILE *in,FILE *out)
{
if(in == NULL || out == NULL)
{
fprintf(stderr,"%s\n","file error!\n");
return -1;
}
char hex;
int i=0;
while(fread(&hex,1,1,in))
{
char s=pass[i];
hex = hex^s;
fwrite(&hex,1,1,out);
i++;
i%=passlen;
}
return 0;
}