RSA数字签名C++代码
时间: 2023-07-11 16:20:41 浏览: 101
以下是一个简单的RSA数字签名C++代码示例:
```c++
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 10000;
int p, q, n, f, d, e;
int prime[MAXN], vis[MAXN], cnt = 0;
void create_prime() {
memset(vis, 0, sizeof(vis));
for (int i = 2; i < MAXN; i++) {
if (!vis[i]) prime[++cnt] = i;
for (int j = 1; j <= cnt && i * prime[j] < MAXN; j++) {
vis[i * prime[j]] = 1;
if (i % prime[j] == 0) break;
}
}
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1, y = 0;
return a;
}
int gcd = exgcd(b, a % b, y, x);
y -= a / b * x;
return gcd;
}
int quick_pow(int a, int b, int mod) {
int res = 1;
while (b) {
if (b & 1) res = (long long) res * a % mod;
a = (long long) a * a % mod;
b >>= 1;
}
return res;
}
void generate_key() {
create_prime();
srand(time(NULL));
p = prime[rand() % cnt + 1];
q = prime[rand() % cnt + 1];
n = p * q;
f = (p - 1) * (q - 1);
do {
e = rand() % f + 1;
} while (gcd(e, f) != 1);
exgcd(e, f, d, d);
d = (d % f + f) % f;
}
int rsa_encrypt(int plain_text, int e, int n) {
return quick_pow(plain_text, e, n);
}
int rsa_decrypt(int cipher_text, int d, int n) {
return quick_pow(cipher_text, d, n);
}
int main() {
generate_key();
int plain_text = 123456;
int cipher_text = rsa_encrypt(plain_text, e, n);
int decrypted_text = rsa_decrypt(cipher_text, d, n);
cout << "Plain Text: " << plain_text << endl;
cout << "Cipher Text: " << cipher_text << endl;
cout << "Decrypted Text: " << decrypted_text << endl;
return 0;
}
```
这段代码使用了RSA算法进行数字签名,先通过生成私钥和公钥,然后使用私钥加密明文,再使用公钥解密密文,得到原始的明文。需要注意,为了保证安全性,实际应用中需要使用更复杂的加密算法,并使用更长的密钥长度。
阅读全文