文件的加密(加密的算法可以自定义) ---文本文件
//分析算法:异或运算(^)
//假设a =5 b =6 a二进制101 b二进制110
//异或运算规则:相同为0 不同为1
//a^b:异或运算 011
int main(){
//源文件
char source_file_path[] = "C:\\Users\\Administrator\\Desktop\\test.txt";
//加密文件
char encryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_en.txt";
//打开源文件
FILE *source_p = fopen(source_file_path, "r");
//打开加密文件
FILE *encryption_p = fopen(encryption_file_path, "w");
//通过循环一个个字符读取,然后给每一个字节进行加密算法处理
int ch;
//参数一:源文件
//返回值:当前读取的位置 EOF:End of file(文件读取结束)
while ((ch = fgetc(source_p) != EOF) ){
//给单个字符进行异或运算
fputc(ch^6,encryption_p);
}
//关闭流
fclose(source_p);
fclose(encryption_p);
getchar();
return 0;
}
//异或运算(^)
//假设:a = 5 b = 6 a二进制:101 b二进制:110
//异或运算规则:相同为0 不同为1
//a^b:异或运算 011 3 c
//c^b:异或运算
//c二进制:011
//b二进制:110
//结果: 101 a还原了
int main(){
//加密文件
char encryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_en.txt";
//解密文件
char decryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_de.txt";
//打开加密文件
FILE *encryption_p = fopen(encryption_file_path, "r");
//打开解密文件
FILE *decryption_p = fopen(decryption_file_path, "w");
//通过循环一个个字符读取,然后给每一个字节进行加密算法处理
int ch;
//参数一:源文件
//返回值:当前读取的位置 EOF:End of file(文件读取结束)
while ((ch = fgetc(encryption_p) != EOF)){
//给单个字符进行异或运算
fputc(ch^6, decryption_p);
}
//关闭流
fclose(decryption_p);
fclose(encryption_p);
getchar();
return 0;
}
文件加密--二进制文件(通过密码来加密)
/*
int main(){
//源文件
char source_file_path[] = "C:\\Users\\Administrator\\Desktop\\test.txt";
//加密文件
char encryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_en.txt";
//打开源文件
FILE *source_p = fopen(source_file_path, "rb");
//打开加密文件
FILE *encryption_p = fopen(encryption_file_path, "wb");
//密码(我们要根据密码进行加密)
char pwd[] = "Davin";
int ch;
int i = 0;
//数组长度
int pwdLen = strlen(pwd);
//参数一:源文件
//返回值:当前读取的位置 EOF:End of file(文件读取结束)
while ((ch = fgetc(source_p) != EOF)){
//给单个字符进行异或运算
fputc(ch^pwd[i%pwdLen], encryption_p);
i++;
}
//关闭流
fclose(encryption_p);
fclose(source_p);
getchar();
return 0;
}
*/
文件解密--二进制文件(通过密码来解密)
int main(){
//密码(我们要根据密码进行加密)
//char pwd[] = "Davin";
char pwd[5];
printf("请输入解密密码:");
scanf("%s",pwd);
//加密文件
char encryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_en.txt";
//解密文件
char decryption_file_path[] = "C:\\Users\\Administrator\\Desktop\\test_de.txt";
//打开加密文件
FILE *encryption_p = fopen(encryption_file_path, "rb");
//打开解密文件
FILE *decryption_p = fopen(decryption_file_path, "wb");
//通过循环一个个字符读取,然后给每一个字节进行加密算法处理
int ch;
int i = 0;
//数组长度
int pwdLen = strlen(pwd);
//参数一:源文件
//返回值:当前读取的位置 EOF:End of file(文件读取结束)
while ((ch = fgetc(encryption_p) != EOF)){
fputc(ch^pwd[i%pwdLen], decryption_p);
}
//关闭流
fclose(decryption_p);
fclose(encryption_p);
getchar();
return 0;
}