rsa加密解密实验c++实现代码
时间: 2024-10-10 14:09:51 浏览: 39
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,常用于数据传输的安全保护。在C++中实现RSA加密和解密实验,首先需要生成一对公钥和私钥,然后分别用于加密和解密。
以下是一个简单的C++实现示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
// RSA模块素分解函数
std::pair<std::vector<int>, bool> primeFactorization(int n) {
std::vector<int> factors;
for (int i = 2; i * i <= n; ++i) {
while (n % i == 0) {
factors.push_back(i);
n /= i;
}
}
if (n > 1) {
factors.push_back(n);
}
return {factors, n == 1};
}
// 获取最大公约数
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
// 计算欧拉函数
int phi(int n) {
int result = n;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
result -= result / i;
while (n % i == 0) {
n /= i;
}
}
}
if (n > 1) {
result -= result / n;
}
return result;
}
// 选择e值(欧拉函数逆元)
int modularInverse(int e, int m) {
int phi_m = phi(m);
int x = e, y = 1, u = 0, v = 1;
while (phi_m != 0) {
int q = x / phi_m;
int t = phi_m;
phi_m = x % phi_m;
x = t;
t = y;
y = u - q * y;
u = t;
t = v;
v = u - q * v;
u = t;
}
// 返回结果并取模
return y >= 0 ? y : y + m;
}
// RSA加密
std::string encrypt(const std::string& message, const int publicKeyModulus, const int publicKeyExponent) {
std::vector<int> messageBytes(message.length());
for (size_t i = 0; i < message.length(); ++i)
messageBytes[i] = static_cast<int>(message[i]);
int encryptedMessage = 1;
for (auto byte : messageBytes) {
encryptedMessage = (encryptedMessage * publicKeyExponent) % publicKeyModulus;
}
return std::to_string(encryptedMessage);
}
// RSA解密
std::string decrypt(const std::string& ciphertext, const int privateKeyModulus, const int privateKeyExponent) {
int decryptedMessage = std::stoi(ciphertext);
int decryptedByte = 1;
while (decryptedMessage > 0 && decryptedMessage <= privateKeyModulus) {
decryptedByte = decryptedMessage;
decryptedMessage = (decryptedMessage * privateKeyExponent) % privateKeyModulus;
if (decryptedByte != 0) {
break;
}
}
std::string decryptedText(decryptedByte, 1);
return decryptedText;
}
int main() {
// 这里只是一个示例,你需要实际生成合适的密钥对
int modulus = ...; // 公钥和私钥的模
int exponent = ...; // 公钥的指数
std::string plaintext = "Hello, World!";
std::string ciphertext = encrypt(plaintext, modulus, exponent);
std::string decryptedText = decrypt(ciphertext, modulus, modularInverse(exponent, modulus));
std::cout << "Original text: " << plaintext << "\n";
std::cout << "Encrypted text: " << ciphertext << "\n";
std::cout << "Decrypted text: " << decryptedText << "\n";
return 0;
}
```
这个例子中省略了密钥生成的部分,实际应用中你需要通过大数乘法、素因数分解等算法生成适合的模和指数。注意RSA加密不适合加密大块数据,因为它会变得非常慢。此外,此示例没有处理错误边界情况,如输入非法字符等。
阅读全文