利用异或^实现文件的加密解密:
按位异或:格式:xy规则:对应相同时0,不同时则为1。
例如:39=1000111001
^1010
=10
参考用途:相同者归零,相异者或。在某些位保持不变的情况下,将其余位取反,自身异或则清零。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void encode(char *buf,char *px)
{
int lenth=strlen(buf);
int n=strlen(px);
int j=0;
for(int i=0;i<lenth;i++)
{
buf[i]^=px[j++];
if(j==n)
j=0;
}
}
void decode(char *buf,char *pf)
{
int lenth=strlen(buf);
int n=strlen(pf);
int j=0;
for(int i=0;i<lenth;i++)
{
buf[i]^=pf[j++];
if(j==n)
j=0;
}
}
int main()
{
char buf[]="Zhong ShengQing";
char xx[]="2001";//密码
printf("%s\n",buf);//显示加密前的文件
encode(buf,xx);
printf("加密后内容:%s\n",buf);
char buf2[1024];
printf("Put your password\n");
scanf("%s",buf2);
decode(buf,buf2);
printf("密码匹配成功\n%s\n",buf);
return 0;
}
文件照片的加密解密
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//1000 0001
//0000 000
void encode(char *buf,char n)
{
for(int i=0;i<n;i++)
{
unsigned char ch=buf[i];
buf[i]=(ch<<1)|(ch>>7);
}
}
void decode(char *buf,char n)
{
for(int i=0;i<n;i++)
{
unsigned char ch=buf[i];
buf[i]=(ch<<7)|(ch>>1);
}
}
int main()
{
FILE *pr=fopen("01.png","rb+");
if(pr==NULL) exit(-1);
FILE *ps=fopen("02.png","wb+");
if(ps==NULL) exit(-1);
char buf[1024];
int n;
while((n=fread(buf,1,1024,ps))>0)
{
encode(buf,n);//照片加密处理
fwrite(buf,1,n,ps);
}
// while((n=fread(buf,1,1024,ps))>0)
// {
// decode(buf,n);
// fwrite(buf,1,n,ps);
// }
fclose(pr);
fclose(ps);
return 0;
}