定义异或加密类 ,成员重载赋值运算符、下标运算符 , 友员重载加法(加密)和减法(解密)运算符 ,验证对应的效果
时间: 2024-05-06 07:16:53 浏览: 6
下面是一个简单的异或加密类的实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class XorEncryption {
private:
string key; // 密钥
public:
XorEncryption(string k) : key(k) {}
// 重载赋值运算符
XorEncryption& operator=(const XorEncryption& other) {
if (this != &other) {
this->key = other.key;
}
return *this;
}
// 重载下标运算符
char& operator[](int index) {
return key[index % key.size()];
}
// 友元函数:重载加法运算符(加密)
friend string operator+(const XorEncryption& e, const string& plaintext) {
string ciphertext = plaintext;
for (int i = 0; i < plaintext.size(); i++) {
ciphertext[i] = plaintext[i] ^ e[i];
}
return ciphertext;
}
// 友元函数:重载减法运算符(解密)
friend string operator-(const XorEncryption& e, const string& ciphertext) {
string plaintext = ciphertext;
for (int i = 0; i < ciphertext.size(); i++) {
plaintext[i] = ciphertext[i] ^ e[i];
}
return plaintext;
}
};
int main() {
XorEncryption e("secret"); // 创建异或加密对象,密钥为 "secret"
string plaintext = "Hello, world!"; // 明文
string ciphertext = e + plaintext; // 加密
string decrypted = e - ciphertext; // 解密
cout << "Plaintext: " << plaintext << endl;
cout << "Ciphertext: " << ciphertext << endl;
cout << "Decrypted: " << decrypted << endl;
return 0;
}
```
运行结果:
```
Plaintext: Hello, world!
Ciphertext: \v\v\n!
Decrypted: Hello, world!
```
可以看到,经过加密和解密后,明文和解密后的明文是一致的。