[古典密码]:Caesar cipher(凯撒密码)

来源于我的博客

非常简单的消息编码方式,仅仅是将字母后移3位,而X Y Z右移就回到A B C.

加密的话就是简单的加三取模即可;解密就是其反过程。

C++实现如下:

#include#include#includeusing namespace std;
string nencrypted = { "Things are not always what they see" };
string ncrypted;
void encrypt(string &unencrypted,string &encrypted) {
	encrypted.resize(unencrypted.size());
	for (int i = 0;i < unencrypted.size();i++) {
		if ((int)unencrypted[i]>64 && (int)unencrypted[i] < 91) {
			encrypted[i] = (char)((((int)unencrypted[i] - 65 + 3) % 26) + 65);//减去65+3取模可得到后移三位的ascii(大写)
		}
		else if ((int)unencrypted[i] > 96 && (int)unencrypted[i] < 123) {
			encrypted[i] = (char)((((int)unencrypted[i] - 97 + 3) % 26) + 97);//减去97+3取模可得到后移三位的ascii(小写)
		}
		else {
			encrypted[i] = unencrypted[i];
		}
	}
	
}
void decrypt(string &encrypted, string &decrypted) {
	decrypted.resize(encrypted.size());
	for (int i = 0;i < encrypted.size();i++) {
		if ((int)encrypted[i]>64 && (int)encrypted[i] < 91) {
			decrypted[i] = (char)((((int)encrypted[i] - 65 - 3 + 26) % 26) + 65);//减去65-3取模可得到前移三位的ascii(大写) //加26使其非负
		}
		else if ((int)encrypted[i] > 96 && (int)encrypted[i] < 123) {
			decrypted[i] = (char)((((int)encrypted[i] - 97 - 3 + 26) % 26) + 97);//减去97-3取模可得到前移三位的ascii(小写)//加26使其非负
		}
		else {
			decrypted[i] = encrypted[i];
		}
	}
}
int main() {
	encrypt(nencrypted, ncrypted);
	cout << ncrypted << endl;
	decrypt(ncrypted, nencrypted);
	cout << nencrypted << endl;
	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值