移位变换加密解密c++实现
时间: 2024-06-01 15:05:16 浏览: 21
移位变换加密解密是一种简单的加密算法,也被称为凯撒密码。其基本思想是将明文中的每个字符按照一定规则进行移位后,得到密文。移位规则可以通过一个密钥来确定,密钥是一个整数,表示明文中每个字符向右移动的位数。
下面是移位变换加密解密的c++实现:
```c++
#include <iostream>
#include <string>
using namespace std;
// 加密函数
string encrypt(string text, int key)
{
string result = "";
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i]))
result += char(int(text[i] + key - 65) % 26 + 65);
else
result += char(int(text[i] + key - 97) % 26 + 97);
}
return result;
}
// 解密函数
string decrypt(string text, int key)
{
string result = "";
for (int i = 0; i < text.length(); i++)
{
if (isupper(text[i]))
result += char(int(text[i] - key - 65 + 26) % 26 + 65);
else
result += char(int(text[i] - key - 97 + 26) % 26 + 97);
}
return result;
}
int main()
{
string text;
int key;
cout << "请输入明文:";
getline(cin, text);
cout << "请输入密钥:";
cin >> key;
string encryptedText = encrypt(text, key);
string decryptedText = decrypt(encryptedText, key);
cout << "加密后的密文为:" << encryptedText << endl;
cout << "解密后的明文为:" << decryptedText << endl;
return 0;
}
```