您的位置:首页 > 其它

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

2016-09-10 14:49 405 查看
来源于我的博客

非常简单的消息编码方式,仅仅是将字母后移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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: