RSA加密算法

本文介绍了一个简单的RSA加密算法实现过程,包括生成素数、计算欧拉函数、选取公钥、计算私钥等步骤,并演示了如何使用这些密钥进行数据的加密与解密。
#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);


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值