第二周作业

#include <_dbdao.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>


long n = 0;
long t = 0;
long e = 0; 
long d = 0;

bool isPrime(long a);
long CreateRandomInteger(int n);
long CreateRandomPrime(int n);
void CreatePublicKey(int p,int q);
int CreateMutualPrime(long N);
void CreatePrivateKey(void);
int RSA_encrypting(int m);
int Unlock_RSA_Encryption(int secret);

int main(void){
	CreatePublicKey(7,13);

	CreatePrivateKey();

	int secret = RSA_encrypting(22);

	Unlock_RSA_Encryption(secret);

	return 0;
}

//判断是否是素数
bool isPrime(long a){
	double max = sqrt(a);

	int index = 2;
	bool condition = (index <= max);
	do
	{
		if(a % index == 0){
			return false;
		}
		else
			index += 1;
	}while(condition == true);
	return true;
 
}

// 随机生成长整数
long CreateRandomInteger(int n){

	int max_result =  pow(2,n);
	int min_result =  pow(2,n-1);
	
	srand((unsigned)time(NULL));

	long result = rand()%(max_result-min_result) + min_result;
	return result;
}

 //2.3 随机生成一个长质数
long CreateRandomPrime(int n){
 
	//得出2的(n-1)次方的范围,-1是为了后面+1防止结果为0

	int max_result = (int) CreateRandomInteger(n-1) - 1;
	srand((unsigned)time(NULL));

	//check代表判断是否是质数,result是随机数r*2-1产生的值
	int check = 0;
	int result = 0;
	
	//如果result不是质数,则不断循环
	do{
	int r =	rand() % max_result + 1;
	result = (r * 2) - 1;
	}while(isPrime(result));

	return result;
}
 
//2.4公开密钥生成算法
void CreatePublicKey(int p,int q){
	n = p*q;

	t = (p-1)*(q-1);

	e = CreateMutualPrime(t);

	printf("公钥< %d, %d> \n",n,e);
}

//生成互质数

int CreateMutualPrime(long N){

	srand((unsigned)time(NULL));
	int e = 0;
	
	do{
		e = rand() % (N-1);
		e += 1;

		double max = sqrt(e);
		int index = 2;
		bool condition = index <= max;
		while(condition == true)
		{
			bool inner_condition = (N % index) == 0;
			if(inner_condition == true){
				return e;
			}
			index += 1;
		}
	}while(true);

}

//保密钥匙生成算法
void CreatePrivateKey(void){

	bool condition = ( (d * e) % t ) != 1;
	while(condition == true){
		d += 1;
	}

	printf("私钥<%d, %d>", n, e);
}

//RSA加密
int RSA_encrypting(int m){
	int secret = pow(m, e) % n;

	printf("加密信息是: %d \n",secret);

	return secret;
}

//RSA解密
int Unlock_RSA_Encryption(int secret){
	int content = pow(secret, d) % n;
	printf("解密信息是:", content);
	return content;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值