rsa_gmp
Posted to7str
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rsa_gmp相关的知识,希望对你有一定的参考价值。
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "gmp.h" #define MILLER_RABIN_TEST_NUM 5 #define PRIME_BIT 512 #define CLOCKS_PER_SEC 1 typedef unsigned char Bit8; typedef unsigned short Bit16; typedef unsigned int Bit32; void getRSAparam(mpz_t n, mpz_t p, mpz_t q, mpz_t e, mpz_t d); void getPrime(mpz_t n); int MillerRabin(const mpz_t n); void PowerMod(const mpz_t a, const mpz_t b, const mpz_t n, mpz_t s); int SetTestNum(const mpz_t n); int getModInverse(const mpz_t n, const mpz_t e, mpz_t d); void ChineseRemainderTheorem(const mpz_t a, const mpz_t b, const mpz_t p, const mpz_t q, mpz_t s); void MontPowerMod(const mpz_t a, const mpz_t b, const mpz_t n, mpz_t s); void MontMult(mpz_t A, mpz_t B, const mpz_t n, int n_bit, const mpz_t IN); void RSA_CMP(mpz_t n, mpz_t p, mpz_t q, mpz_t e, mpz_t d); //获取RSA算法的5个参数 void getRSAparam(mpz_t n, mpz_t p, mpz_t q, mpz_t e, mpz_t d) { double long start, end; //获取前三个参数n,p,q do { getPrime(p); getPrime(q); } while (!mpz_cmp(p, q)); //p!=q gmp_printf("find p q done "); mpz_mul(n, p, q); //获取d,e mpz_t p_1, q_1, n_1; //分别代表φ(p), φ(q), φ(n) mpz_inits(p_1, q_1, n_1, NULL); //初始化 mpz_sub_ui(p_1, p, 1); //φ(p)=p-1 mpz_sub_ui(q_1, q, 1); //φ(q)=q-1 mpz_mul(n_1, p_1, q_1); //φ(n)=(p-1)(q-1) gmp_randstate_t state; gmp_randinit_default(state);//对state进行初始化 gmp_randseed_ui(state, /*time(NULL)*/rand());//对state置初始种子 while (1) { mpz_urandomm(e, state, n_1); //产生随机数0=<b<=φ(n), 生成公钥 if (getModInverse(e, n_1, d)) //使用求e模φ(n)的逆d, 作为私钥 break; } mpz_clears(n_1, p_1, q_1, NULL); gmp_randclear(state); } //获取一个大整数,大小默认为512bit void getPrime(mpz_t n) { int i, random = 0; //srand(time(NULL)); char rand_num[PRIME_BIT + 1]; //用于存放512bit的随机数 rand_num[PRIME_BIT] = ‘