#include <iostream>;
#include <time.h>
using namespace std;
void getPrimeNumber(int &x,int &y);//生成x,y两个素数(小的)
bool checkIsPrime(int x);//检查是否为素数
int gcd(int x, int y);//最大公约数函数
int ectgcd(int c, int d);//乘法逆元函数,求模反元素
int Power(int a, int m, int n);//求幂
bool conPrime(int x,int y);
int main() {
srand((unsigned)time(NULL));
int p, q;
//得到两个
getPrimeNumber(p,q);
cout << "素数p:" << p << " 素数q:" << q << endl;
//计算p和q的乘积n
int n = p*q;
cout << "乘积n:" << n << endl;
//计算n的欧拉函数φ(n)
int phi = (p-1)*(q-1);
//随机选择一个整数e,条件是1< e < φ(n),且e与φ(n) 互质。
cout << "欧拉函数phi:" << phi << endl;
int e;
e = rand()*phi;
while (!conPrime(e, phi)) {
e = rand()%phi;
}
cout << "公钥e:" << e << endl;
//计算e对于φ(n)的模反元素d。
int d = ectgcd(e,phi);
cout << "模反元素d,也就是密钥:" << d << endl;
//将n和e封装成公钥,n和d封装成私钥
//公钥负责加密,私钥负责解密;私钥负责签名,公钥负责验证
cout << "公钥n=" << n << ",e=" << e << endl;
cout << "私钥n=" << n << ",d=" << d << endl;
int clearText = 99;
int result;
cout << "加密前" << clearText << endl;
int cipher;
//加密
cipher = Power(clearText,e,n);
cout << "加密后" << cipher << endl;
//解密
result= Power(cipher, d, n);
cout << "解密后:" << result << endl;
}
void getPrimeNumber(int & x, int & y)
{
x = rand() % 1000;
y =rand() % 1000;
while (!checkIsPrime(x)) {
x = rand() % 1000;
}
while (!checkIsPrime(y)) {
y = rand() % 1000;
while (y == x) {
y = rand() % 1000;
}
}
}
bool checkIsPrime(int x)
{
int i, j;
for (i = 2, j = int(sqrt(x)); i <= j; i++)
if (x%i == 0) return false;
return true;
}
int ectgcd(int c, int d)
{
int r0, r1, y, s, t, s0, s1, t0, t1, q, r;
r0 = d;
r1 = c%d;
if (r1 == 1)
{
y = 1;
}
else
{
s0 = 1;
s1 = 0;
t0 = 0;
t1 = 1;
while (r0%r1 != 0)
{
q = r0 / r1;
r = r0%r1;
r0 = r1;
r1 = r;
s = s0 - q*s1;
s0 = s1;
s1 = s;
t = t0 - q*t1;
t0 = t1;
t1 = t;
if (r == 1)
{
if (t>0)
{
y = t;
}
else if (t<0)
{
y = t + d;
}
}
}
}
return y;
}
int Power(int a, int m, int n)
{
if (m == 1) return a%n;
if (m == 2) return a*a%n;
if (m % 2 == 1) {
int temp = Power(a, m / 2, n) % n;
temp = temp*temp%n;
temp = temp*a%n;
return temp;
}
else {
int temp = Power(a, m / 2, n) % n;
temp = temp*temp%n;
return temp;
}
}
bool conPrime(int x, int y)
{
//判断互为质数只需要检查最大公约数是否为1即可。
if (gcd(x, y) == 1)return true;
else return false;
}
int gcd(int x, int y)
{
int m;
while (y != 0)
{
m = x%y;
x = y;
y = m;
}
return (x);
}
RSA加密算法
最新推荐文章于 2021-12-28 10:21:05 发布
