字符串加密解密(带密码)

字符串加密解密

/**
 * 原理 a = 1111;//二进制(需加密的数据)
 *     b = 1010;//二进制(密码)
 * # 加密
 * 加密运算:a = a ^ b;
 * 		 a = 1111 ^ 1010
 * 加密后:a = 0101
 * # 解密
 * 解密运算:a = a ^ b;
 * 		a = 0101 ^ 1010
 * 解密后的:a = 1111
 */
#include <stdio.h>
#include <string.h>
/**
 * src : helloworldhelloworld
 * 加密: AccowoAccowoAccowoAc
 */
/**
 * @brief 加密数据and解密数据
 * @param 
 * 		@src			要加密的数据
 * 		@srclen			数据的长度	
 * 		@passworld		加密的密码
 * 		@passwordLen	密码的长度
 * @note 传入长度而不用内部strlen的原因是防止加密后的数据出现'\0'的情况,导致strlen计算长度错误
 * @retval 加密后的字符串
 */
char* encryptData(char *src, int srcLen, const char *password, int passwordLen)
{
	int i;
	int j;
	for (j = 0; j < srcLen / passwordLen; j++)
	{
		for (i = 0; i < passwordLen; i++)
		{
			//密码加密到src上
			src[j * passwordLen + i] ^= password[i];
		}
	}
	// src的长度不是密码长度整数倍的情况,处理剩余的数据
	if ((j = srcLen/passwordLen * passwordLen) != srcLen)
	{
		for (i = j; i < srcLen; i++)
		{
			src[i] ^= password[i - j];
		}
	}
	return src;
}

void test(const char *testName, char *src, int srcLen, const char *password, int passwordLen){
	printf("=========%s=========\n", testName);
	printf("src:\n%s\n", src);
	//加密
	encryptData(src, srcLen, password, passwordLen); 				
	printf("encrypt src:\n%s\n", src);
	//解密
	encryptData(src, srcLen, password, passwordLen);		
	printf("After decryption---src:\n%s\n", src);
}

int main(){
	char src[] = "hello world";
	char password[] = "accowo";
	test("数据长度大于密码长度",src, sizeof(src) / sizeof(*src) - 1, 
				password,  sizeof(password) / sizeof(*password) - 1);

	strcpy(src, "hell6");
	test("数据长度等于密码长度",src, sizeof(src) / sizeof(*src) - 1, 
				password,  sizeof(password) / sizeof(*password) - 1);

	strcpy(src, "he");
	test("数据长度小于密码长度",src, sizeof(src) / sizeof(*src) - 1, 
				password,  sizeof(password) / sizeof(*password) - 1);
	return 0;
}

执行结果

=========数据长度大于密码长度=========
src:
hello world
encrypt src:
        ═╚O
           ╚
After decryption---src:
hello world
=========数据长度等于密码长度=========
src:
hell6
encrypt src:
        ═╚Ao
            ╚
After decryption---src:
hell6
=========数据长度小于密码长度=========
src:
he
encrypt src:
        ═c╚Ao
             ╚
After decryption---src:
he
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值