[古典密码]: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;
}


发布了49 篇原创文章 · 获赞 15 · 访问量 8万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章