17c234522dc071de3b1d543904c94e0c64a57f78
[crypto_lab3.git] / src / RsaStd.cpp
1 #include "RsaStd.h"
2
3 using namespace std;
4
5 #include "Rand.h"
6 #include "Utils.h"
7
8 pair<Rsa::KeyPub, RsaStd::KeyPriv> RsaStd::generateRSAKeys(uint exponent, uint keySizeBits)
9 {
10 mpz_class p, q, phi;
11 Rsa::KeyPub kPub;
12 KeyPriv kPriv;
13
14 do
15 {
16 kPub.e = exponent;
17 p = Rand::randPrime(keySizeBits / 2);
18 q = Rand::randPrime(keySizeBits / 2);
19
20 kPriv.n = kPub.n = p * q;
21 phi = (p - 1) * (q - 1);
22
23 } while (mpz_invert(kPriv.d.get_mpz_t(), kPub.e.get_mpz_t(), phi.get_mpz_t()) == 0); // If 'd' is not invertible we try another primes.
24
25 // For debugging purpose.
26 // Utils::print("p", p);
27 // Utils::print("q", q);
28 // Utils::print("n", kPub.n);
29 // Utils::print("phi", phi);
30 // Utils::print("d", kPriv.d);
31
32 return make_pair(kPub, kPriv);
33 }
34
35 mpz_class RsaStd::sign(const mpz_class& m, const KeyPriv& kPriv)
36 {
37 mpz_class result;
38 mpz_powm_sec(result.get_mpz_t(), m.get_mpz_t(), kPriv.d.get_mpz_t(), kPriv.n.get_mpz_t());
39 return result;
40 }