The previous blog post (reprinted Nanyi) has already talked about the basic principles of the RSA algorithm. A long time ago, Bowen has involved in the power algorithm, today can finally debut, the first review of the modular Power Algorithm program bar:
#include <iostream>
using namespace std;
Return value: A's B-second side, then modulo
int getmod (int a, int b, int n)
{
int i, r = 1;
for (i = 1; I <= b; i++)
{
R = (r% n) * (a% n))% n;
}
return r;
}
int main ()
{
int a = 3;
int b = 4;
int n = 5;
cout << Getmod (A, B, n) << Endl; 3 * 3 * 3 * 3% 5 = 1
a =;
b = Rule;
n =;
cout << Getmod (A, B, n) << Endl; 103 * 103 *...* 103% 105 = 46, fully consistent with the results calculated by Windows own calculator return
0;
}
OK, now suppose Bob wants to communicate with Alice, and Alice first comes up with the secret key pair, which is the following:
Alice chooses to satisfy the condition P = 3233, q = 53, calculates n =% (n) = (p-1) * (q-1) = q = 3120, Alice chooses to satisfy the condition of e 17, calculates E for F (n) The modulo inverse element d = 2753,
So far, Alice has the RSA encrypted public key (N, e) and the private key (n, D), Alice tells Bob the public key (N, E), and Bob can use the public key (N, e) to encrypt the information, so that the message that Bob wants to send to Alice is 65, So Bob's encryption method is:
#include <iostream>
using namespace std;
Return value: A's B-second side, then modulo
int getmod (int a, int b, int n)
{
int i, r = 1;
for (i = 1; I <= b; i++)
{
R = (r% n) * (a% n))% n;
}
return r;
}
int rsa_encrypt (int m, int n, int e)
{
int c = Getmod (M, E, N);
return c;
}
int main ()
{
int m =;
int n = 3233;
int e =;
cout << Rsa_encrypt (M, N, e) << Endl; 2790 return
0;
}
Bob sent 2790 to Alice, Alice received 2790, using the private key to decrypt 2790, the decryption process is:
#include <iostream>
using namespace std;
Return value: A's B-second side, then modulo
int getmod (int a, int b, int n)
{
int i, r = 1;
for (i = 1; I <= b; i++)
{
R = (r% n) * (a% n))% n;
}
return r;
}
int rsa_decrypt (int c, int n, int d)
{
int m = Getmod (c, D, N);
return m;
}
int main ()
{
int c = 2790;
int n = 3233;
int d = 2753;
cout << Rsa_decrypt (c, N, D) << Endl;
0;
Visible, Alice correctly decrypts the information that Bob sent.
Of course, in real application, the data is much larger than the above example, at this time, the above program is invalid, need to adopt new large number mapping and operation method, OpenSSL in this respect to do very well.