以下是使用 C++ 实现凯撒密码的示例代码:
- #include <iostream>
- #include <string>
- using namespace std;
- string encrypt(string plaintext, int shift) {
- string ciphertext = "";
- for (int i = 0; i < plaintext.length(); i++) {
- char c = plaintext[i];
- if (isalpha(c)) {
- c = toupper(c);
- c = ((c - 'A' + shift) % 26) + 'A';
- }
- ciphertext += c;
- }
- return ciphertext;
- }
- string decrypt(string ciphertext, int shift) {
- string plaintext = "";
- for (int i = 0; i < ciphertext.length(); i++) {
- char c = ciphertext[i];
- if (isalpha(c)) {
- c = toupper(c);
- c = ((c - 'A' - shift + 26) % 26) + 'A';
- }
- plaintext += c;
- }
- return plaintext;
- }
- int main() {
- string plaintext, ciphertext, decrypted_text;
- int shift;
- cout << "Enter plaintext: ";
- getline(cin, plaintext);
- cout << "Enter shift: ";
- cin >> shift;
- ciphertext = encrypt(plaintext, shift);
- cout << "Encrypted text: " << ciphertext << endl;
- decrypted_text = decrypt(ciphertext, shift);
- cout << "Decrypted text: " << decrypted_text << endl;
- return 0;
- }
在这个示例代码中,我们首先定义了两个函数 encrypt 和 decrypt,用于加密和解密凯撒密码。在 encrypt 函数中,我们遍历明文字符串中的每个字符,如果是字母则将其转换为大写字母,然后将其 ASCII 码值加上移位值,再对 26 取模得到加密后的字符。在 decrypt 函数中,我们同样遍历密文字符串中的每个字符,如果是字母则将其转换为大写字母,然后将其 ASCII 码值减去移位值,再对 26 取模得到解密后的字符。最后,我们在 main 函数中获取用户输入的明文和移位值,调用 encrypt 函数加密明文得到密文,再调用 decrypt 函数解密密文得到解密后的明文。
好的,以下是继续编写的C++凯撒密码代码:
- #include <iostream>
- #include <string>
- using namespace std;
- string encrypt(string plaintext, int shift) {
- string ciphertext = "";
- for (int i = 0; i < plaintext.length(); i++) {
- char c = plaintext[i];
- if (isalpha(c)) {
- c = toupper(c);
- c = ((c - 'A' + shift) % 26) + 'A';
- }
- ciphertext += c;
- }
- return ciphertext;
- }
- string decrypt(string ciphertext, int shift) {
- string plaintext = "";
- for (int i = 0; i < ciphertext.length(); i++) {
- char c = ciphertext[i];
- if (isalpha(c)) {
- c = toupper(c);
- c = ((c - 'A' - shift + 26) % 26) + 'A';
- }
- plaintext += c;
- }
- return plaintext;
- }
- int main() {
- string plaintext, ciphertext, decrypted_text;
- int shift;
- cout << "Enter plaintext: ";
- getline(cin, plaintext);
- cout << "Enter shift: ";
- cin >> shift;
- ciphertext = encrypt(plaintext, shift);
- cout << "Encrypted text: " << ciphertext << endl;
- decrypted_text = decrypt(ciphertext, shift);
- cout << "Decrypted text: " << decrypted_text << endl;
- return 0;
- }
这段代码的功能与之前的代码相同,只是在输出结果时将解密后的文本也输出了。用户可以通过输入明文和移位值来加密和解密凯撒密码。