[古典密碼]: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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章