引用GMP大数库里的开篇陈词,请注意此文仅供学习与参考,谢绝其它用途。
GNU MP Copying ConditionsThis library is free; this means that everyone is free to use it and free to redistribute it on a freebasis. The library is not in the public domain; it is copyrighted and there are restrictions on itsdistribution, but these restrictions are designed to permit everything that a good cooperatingcitizen would want to do. What is not allowed is to try to prevent others from further sharingany version of this library that they might get from you.Specifically, we want to make sure that you have the right to give away copies of the library,that you receive source code or else can get it if you want it, that you can change this libraryor use pieces of it in new free programs, and that you know you can do these things.To make sure that everyone has such rights, we have to forbid you to deprive anyone else ofthese rights. For example, if you distribute copies of the GNU MP library, you must give therecipients all the rights that you have. You must make sure that they, too, receive or can getthe source code. And you must tell them their rights.Also, for our own protection, we must make certain that everyone finds out that there is nowarranty for the GNU MP library. If it is modified by someone else and passed on, we wanttheir recipients to know that what they have is not what we distributed, so that any problemsintroduced by others will not reflect on our reputation.The precise conditions of the license for the GNU MP library are found in the Lesser GeneralPublic License version 2.1 that accompanies the source code, see ‘COPYING.LIB’. Certain demon-stration programs are provided under the terms of the plain General Public License version 2,see ‘COPYING’.
由于对RSA加密的特性并非十分清楚,故不可保证通过所用到的函数就能达到较强的安全性能,并再次声明,仅供学习与参考。此文仅为学习笔记。
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<assert.h>
#include<time.h>
#include<gmp.h>
#pragma comment(lib,"gmpDebug.lib")
using namespace std;
1、随机素数产生(方法较笨,完全通过对随机数的检验实现)
mpz_t p;
time_t seed;
gmp_randstate_t state;
time(&seed);
mpz_init(p);
gmp_randinit_default(state);
gmp_randseed_ui(state, long(seed));
do{
mpz_urandomb(p, state, pSIZE);//pSIZE为所要求p的最大规模
}while(0 == mpz_probab_prime_p(p, safeNum));
2、各种杂事
mpz_mul(n, p, q);//n = p * q
mpz_sub_ui(p, p, 1);//p = p - 1
mpz_sub_ui(q, q, 1);//q = q - 1
mpz_mul(eln, p, q);//eln = p * q
mpz_powm(ciphertext, message, e, n);//c = m^e mod n
mpz_powm(tmp, ciphertext, d, n);//m = c^d mod n
3、获取私钥
void getPrivateKey(mpz_t&d, const mpz_t& e, const mpz_t& eln)
{
mpz_t a, b, s, t, g;
mpz_init(s);
mpz_init(t);
mpz_init(g);
mpz_init_set(a, e);
mpz_init_set(b, eln);
mpz_gcdext(g, s, t, a, b);
mpz_set(d, s);
mpz_clear(a);
mpz_clear(b);
mpz_clear(s);
mpz_clear(t);
mpz_clear(g);
}
4、验证是否正确
if(0 == mpz_cmp(tmp, message))cout<<"解密正确!\n\n";
else cout<<"解密失败!\n\n";
5、结果