使用C++实现仿射变换加密和解密的代码
时间: 2024-01-22 19:18:01 浏览: 90
以下是使用C++实现仿射变换加密和解密的代码,仅供参考:
```c++
#include <iostream>
#include <string>
using namespace std;
string affineEncrypt(string plainText, int a, int b) {
string cipherText = "";
for (int i = 0; i < plainText.length(); i++) {
if (isalpha(plainText[i])) {
char c = toupper(plainText[i]);
cipherText += (char)((a * (c - 'A') + b) % 26 + 'A');
}
}
return cipherText;
}
string affineDecrypt(string cipherText, int a, int b) {
string plainText = "";
int a_inv = 0;
for (int i = 0; i < 26; i++) {
if ((a * i) % 26 == 1) {
a_inv = i;
break;
}
}
for (int i = 0; i < cipherText.length(); i++) {
if (isalpha(cipherText[i])) {
char c = toupper(cipherText[i]);
plainText += (char)(a_inv * (c - 'A' - b + 26) % 26 + 'A');
}
}
return plainText;
}
int main() {
string plainText = "HELLO WORLD";
int a = 5;
int b = 8;
string cipherText = affineEncrypt(plainText, a, b);
cout << "Cipher Text: " << cipherText << endl;
string decryptedText = affineDecrypt(cipherText, a, b);
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}
```
说明:
- `affineEncrypt(string plainText, int a, int b)`函数实现仿射变换加密,其中`plainText`为明文,`a`和`b`为密钥参数。
- `affineDecrypt(string cipherText, int a, int b)`函数实现仿射变换解密,其中`cipherText`为密文,`a`和`b`为密钥参数。
- `main()`函数中示例了如何使用上述两个函数进行仿射变换加密和解密。
阅读全文