异或以及循环移位进行文件的加密解密

利用异或^实现文件的加密解密:

按位异或:格式: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;
}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值