【加密解密】对字符串的加密解密

</pre><pre code_snippet_id="1666199" snippet_file_name="blog_20160429_2_7838133" name="code" class="cpp"><span style="font-size:24px;">字符串 加密解密的入门练习,</span>
#include<stdio.h>
#include<stdlib.h>

//按照密码加密
//文件加密
//字符串加密

char *stringEncrypt(char *password, char *string);
char *stringDecode(char *password, char *string);


#include "passw.h"

//异或的加密解密函数是一样的
//字符串加密
char *stringEncrypt(char *password, char *string)
{
	int passLength = strlen(password);//获取加密长度
	int stringLength = strlen(string);//获取字符串长度

	if (stringLength%passLength == 0)//字符串长度是密码长度的整数倍
	{
		int times = stringLength/passLength;
		for (int i = 0; i < times; i++)
		{
			for (int j = 0; j < passLength; j++)
			{
				string[i*passLength+j] ^= password[j];
				//这里的下标计算画图很容易理解
			}
		}
	}
	else
	{
		int times = stringLength / passLength;
		for (int i = 0; i < times; i++)
		{
			for (int j = 0; j < passLength; j++)
			{
				string[i*passLength + j] ^= password[j];
			}
		}
		int lastLength = stringLength%passLength;
		//不能整除的,也就是余数长度
		for (int i = 0; i < lastLength; i++)
		{
			string[passLength*(stringLength / passLength) + i] ^= password[i];
			//这里的解密要从前边已经整除完成的后一个位置开始,
			//假如说stringLength = 10,passLength = 4;那么除不尽的加密就从下标8开始,
			//(10 / 4)*4 = 8.
		}
	}
	return string;
}
//字符串解密
char *stringDecode(char *password, char *string)
{
	int passLength = strlen(password);//获取加密长度
	int stringLength = strlen(string);//获取字符串长度

	if (stringLength % passLength == 0)//字符串长度是密码长度的整数倍
	{
		int times = stringLength/passLength;
		for (int i = 0; i < times; i++)
		{
			for (int j = 0; j < passLength; j++)
			{
				string[i*passLength + j] ^= password[j];
			}
		}
	}
	else
	{
		int times = stringLength / passLength;
		for (int i = 0; i < times; i++)
		{
			for (int j = 0; j < passLength; j++)
			{
				string[i*passLength + j] ^= password[j];
			}
		}
		int lastLength = stringLength%passLength;
		//不能整除的,也就是余数长度
		for (int i = 0; i < lastLength; i++)
		{
			string[passLength*(stringLength / passLength) + i] ^= password[i];
			//这里的解密要从前边已经整除完成的后一个位置开始,
			//假如说stringLength = 10,passLength = 4;那么除不尽的加密就从下标8开始,
			//(10 / 4)*4 = 8.
		}
	}
	return string;
}

//测试代码
#include<stdio.h>
#include<stdlib.h>
#include "passw.h"

void main()
{
	char str[20] = "abcdefghijk";
	char *password = "123";

	printf("%s\n", stringEncrypt(password, str));
	printf("%s\n", stringDecode(password, str));


	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值