#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;
}