简易的c++汉字字符串加密程序

本人新手一枚,闲得无聊写的聊天加密程序,解密程序稍后发。

/*
	版权声明:
	本文为CSDN博主「Xia Yanze」的原创文章,
	遵循CC 4.0 BY-SA版权协议,
	转载请附上原文出处链接及本声明。 
	
	使用说明: 
	此为简易字符串加密程序, 
	仅用于日常使用,
	不能用于涉密文件!
*/
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string s;
int x;
int main()
{
	printf("下面开始字符串加密程序\n");
	cin >> s;
	for(int i = 0; i < s.size(); i++)
	{
		x = (int)s[i];
		x = ~x + 1;
		if(x < 32)
			printf("%d ", x);
		else
			printf("%c ", x);
	}
	return 0;
}

以下是用C语言实现字符串异或加密和解密的代码,可以参考: ```c #include <stdio.h> #include <string.h> void encrypt(char *text, char key) { int len = strlen(text); for (int i = 0; i < len; i++) { text[i] ^= key; } } void decrypt(char *text, char key) { encrypt(text, key); } int main() { char text[20]; char key; printf("Enter a string (not more than 20 characters): "); scanf("%s", text); printf("Enter a character as the key: "); scanf(" %c", &key); printf("\nOriginal text: %s", text); encrypt(text, key); printf("\nEncrypted text: %s", text); decrypt(text, key); printf("\nDecrypted text: %s", text); return 0; } ``` 如果你输入字符串为"hello",密钥为'a',则程序的输出如下: ``` Enter a string (not more than 20 characters): hello Enter a character as the key: a Original text: hello Encrypted text: \n]]a` Decrypted text: hello ``` 第二个问题是:lua closure factory 完整代码 下面是一个Lua闭包工厂函数的示例,它返回一个新的闭包函数,可以累加传入的数字: ```lua function make_counter() local count = 0 return function () count = count + 1 return count end end -- Usage example: local counter1 = make_counter() print(counter1()) -- Output: 1 print(counter1()) -- Output: 2 local counter2 = make_counter() print(counter2()) -- Output: 1 ``` 这个示例中,`make_counter()` 函数返回一个新的匿名函数,这个函数会累加内部的 `count` 变量,返回累加后的结果。每次调用 `make_counter()` 都会返回一个新的闭包(也就是说,内部的 `count` 变量是独立的)。当你调用闭包函数时,它会返回累加后的计数值。这个例子展示了Lua闭包的基本用法。 第三个问题是:中文加密。 对于中文字符串加密,可以采用类似的方法:使用异或运算符对每个字符进行加密和解密。不过需要注意的是,中文字符通常占用两个字节,如果直接对一个字符用异或会导致编码错误,需要对两个字节一起进行加密和解密。下面是一个简单的示例: ```python def encrypt(text, key): result = "" for c in text: # 将字符转换为整数,然后拆分为两个字节 b1, b2 = divmod(ord(c), 256) # 分别对两个字节进行异或加密 b1 ^= key b2 ^= key # 将加密后的两个字节合并为一个整数,并转换回字符 result += chr(b1 * 256 + b2) return result def decrypt(text, key): return encrypt(text, key) ``` 这个示例中,`encrypt` 和 `decrypt` 函数分别对传入的字符串进行加密和解密。对于每个中文字符,它们将被拆分为两个字节,然后分别进行异或运算。最后将加密后的两个字节合并为一个整数,并转换回字符。注意Python中文字符串的编码方式通常为UTF-8,需要使用 `ord` 函数获取它的Unicode编码。此外,由于Python中字符类型为Unicode,所以不需要考虑字符集的问题。当然,如果需要更加高效的加密算法,可以考虑使用AES等成熟的加密算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值