C++程序实现凯撒密码
这是一种单字母替换密码,其中明文中的每个字母都被替换为另一个字母以形成密文。它是替换密码方案中最简单的形式。
这种密码系统通常被称为移位密码。其概念是用另一个“移位”了固定数字(0到25之间)的字母来替换每个字母。
对于这种类型的方案,发送方和接收方都商定一个用于移位字母的“秘密移位数字”。这个介于0到25之间的数字成为加密的密钥。
当使用“移位3”时,“凯撒密码”这个名称偶尔会被用来描述移位密码。
过程
为了加密明文字母,发送方将滑动标尺放在第一组明文字母下方,并将其向左滑动秘密移位的位数。
然后将明文字母加密为滑动标尺下方的密文字母。以下图示显示了商定移位3个位置的结果。在这种情况下,明文“tutorial”被加密为密文“wxwruldo”。以下是移位3的密文字母表:
收到密文后,接收方(也了解秘密移位)将他的滑动标尺放在密文字母表下方,并将其向右滑动商定的移位数,在本例中为3。
然后他用滑动标尺下方的明文字母替换密文字母。因此,密文“wxwruldo”被解密为“tutorial”。要解密使用移位3编码的消息,请使用“ -3”的移位生成明文字母表,如下所示:
以下是上述过程在C++中的实现。
步骤和伪代码
将消息和密钥作为输入:
加密
- 输入:tutorial。
- 输出:wxwruldo
解密
- 输入:wxwruldo
- 输出:tutorial
加密
Begin For i = 0 to msg[i] != '\0' ch = msg[i] //encrypt for lowercase letter If (ch >= 'a' and ch <= 'z') ch = ch + key if (ch > 'z') ch = ch - 'z' + 'a' - 1 done msg[i] = ch //encrypt for uppercase letter else if (ch >= 'A' and ch <= 'Z') ch = ch + key if (ch > 'Z') ch = ch - 'Z' + 'A' - 1 done msg[i] = ch done done Print Encrypted message End
解密
Begin For i = 0 to msg[i] != '\0' ch = msg[i] //decrypt for lowercase letter if(ch >= 'a' and ch <= 'z') ch = ch - key if (ch < 'a') ch = ch +'z' - 'a' + 1 done msg[i] = ch //decrypt for uppercase letter else if (ch >= 'A' and ch <= 'Z') ch = ch + key if (ch < 'A') ch = ch + 'Z' - 'A' + 1 done msg[i] = ch done done Print decrypted message End
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include<iostream> #include<string.h> using namespace std; int main() { cout<<"Enter the message:\n"; char msg[100]; cin.getline(msg,100); //take the message as input int i, j, length,choice,key; cout << "Enter key: "; cin >> key; //take the key as input length = strlen(msg); cout<<"Enter your choice \n1. Encryption \n2. Decryption \n"; cin>>choice; if (choice==1) //for encryption{ char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //encrypt for lowercase letter If (ch >= 'a' && ch <= 'z'){ ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } msg[i] = ch; } //encrypt for uppercase letter else if (ch >= 'A' && ch <= 'Z'){ ch = ch + key; if (ch > 'Z'){ ch = ch - 'Z' + 'A' - 1; } msg[i] = ch; } } printf("Encrypted message: %s", msg); } else if (choice == 2) { //for decryption char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //decrypt for lowercase letter if(ch >= 'a' && ch <= 'z') { ch = ch - key; if(ch < 'a'){ ch = ch + 'z' - 'a' + 1; } msg[i] = ch; } //decrypt for uppercase letter else if(ch >= 'A' && ch <= 'Z') { ch = ch - key; if(ch < 'A') { ch = ch + 'Z' - 'A' + 1; } msg[i] = ch; } } cout << "Decrypted message: " << msg; } }
输出
For encryption: Enter the message: tutorial Enter key: 3 Enter your choice 1. Encryption 2. Decryption 1 Encrypted message: wxwruldo For decryption: Enter the message: wxwruldo Enter key: 3 Enter your choice 1. Encryption 2. Decryption 2 Decrypted message: tutorial
广告