C++实现简单的RSA加密

#include 
#include 
using namespace std;

int primeNum(int num);//判断素数
int coprime(int a, int b);//判断互素
int candp(int a, int b, int c);  //计算密文

int key();//生成密钥
int encryption();//加密
int decode();//解密


int main()
{
	cout << "RSA加密算法"<> i;
		switch (i)
		{
			case 1:
				key();
				break;
			case 2:
				encryption();
				break;
			case 3:
				decode();
				break;
			case 4:
				exit(0);
			default:
				cout << "输入错误" << endl;
		}			 
	}
	return 0;
}

//判断是否是素数
int primeNum(int num)
{
	int i, flag = 0;

	for (i = 2; i <= num / 2; ++i)
	{
		// 符合该条件不是素数
		if (num % i == 0)
		{
			flag = 1;
			break;
		}
	}
	//flag为1,不是素数;为0,是素数
	return flag;
}
//判断两个数是否互素
int coprime(int a, int b)
{
	int t;
	if (a < b)
	{
		t = a; a = b; b = t;
	}
	while (a % b)
	{
		t = b;
		b = a % b;
		a = t;
	}
	//返回值为1,则a,b互素
	return b;
}
//计算密文
int candp(int a, int b, int c) //a--明文或密文   b--指数(e/d)    c--模数
{
	int r = 1;
	b = b + 1;
	while (b != 1)
	{
		r = r * a;
		r = r % c;
		b--;
	}
	return r;
}
//生成密钥
int key()
{
	int p, q, m, n, e, d;
	cout<<"请输入 p,q: "<> p >> q;
	if (primeNum(p) != 0 || primeNum(q) != 0)
	{
		cout << "输入的p或q不是素数" << endl;
		return 0;
	}
	n = p * q;
	
	//m为n的欧拉函数
	m = (p - 1) * (q - 1);
	
	cout<<"请输入私钥d: "<> d;
	e = 1;
	//求d的乘法逆
	while (((e * d) % m) != 1) e++;

	cout<<"n = p * q = "<> e >> n;
	cout<<"请输入明文: (明文需小于"<> x;

	y = candp(x, e, n);
	cout<<"密文为:"<> d >> n;
	cout << "请输入密文: ";  //计算密文
	cin >> y;

	x = candp(y, d, n);
	cout << "明文为:" << x << endl;
	return 0;
}

 

你可能感兴趣的:(密码学)