-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsakeygenerator.cpp
More file actions
83 lines (76 loc) · 2.25 KB
/
rsakeygenerator.cpp
File metadata and controls
83 lines (76 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <vector>
#include <random>
#include <cmath>
#include <cstdint>
#include <windows.h>
#include "lib.h"
#include <fstream>
using namespace std;
int main()
{
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
cout << "RSA Key Generator" << endl;
cout << "素数の桁数を入力してください (1〜18): ";
int digits;
cin >> digits;
if (digits <= 0 || digits > 18)
{
cout << "エラー: 桁数は1〜18の範囲で入力してください。" << endl;
return 1;
}
// 指定桁数の範囲 [lower, upper]
long long lower = (digits == 1) ? 2 : (long long)pow(10.0, digits - 1);
long long upper = (long long)pow(10.0, digits) - 1;
random_device rd;
mt19937_64 gen(rd());
uniform_int_distribution<long long> dis(lower, upper);
vector<long long> primes;
while (primes.size() < 2)
{
long long candidate = dis(gen);
// 奇数にする (2を除く偶数は素数でない)
if (candidate != 2 && candidate % 2 == 0)
candidate++;
if (candidate > upper)
continue;
if (isPrime(candidate))
{
// 重複チェック
bool dup = false;
for (long long p : primes)
if (p == candidate)
{
dup = true;
break;
}
if (!dup)
primes.push_back(candidate);
}
}
ofstream out("keys.txt");
out << "生成された素数 p: " << primes[0] << endl;
out << "生成された素数 q: " << primes[1] << endl;
out << "n = p * q = " << primes[0] * primes[1] << endl;
const int n = primes[0] * primes[1];
cout << "n = p * q: " << n << endl;
const int phi = lcm(primes[0] - 1, primes[1] - 1);
out << "φ(n) = lcm(p-1, q-1) = " << phi << endl;
const int E = 17; // 公開指数
cout << "公開指数 e: " << E << endl;
out << "公開指数 e: " << E << endl;
// 秘密指数 d を求める (d * E ≡ 1 (mod φ))
int d = 0;
for (int i = 1; i < phi; i++)
{
if ((E * i) % phi == 1)
{
d = i;
break;
}
}
out << "秘密指数 d: " << d << endl;
out.close();
return 0;
}