📄 main.c
字号:
#include "bn.h"
#include <conio.h>
#include <stdio.h>
#define RSA_N_SIZE 1024
#define RSA_P_SIZE (((RSA_N_SIZE) + 1) >> 1)
#define RSA_Q_SIZE ((RSA_N_SIZE) - (RSA_P_SIZE))
#define RSA_EN_SIZE RSA_N_SIZE
#define RSA_D_SIZE RSA_EN_SIZE
#define BYTENUM(a) (((a) & 7)? (((a) >> 3) + 1): ((a) >> 3))
typedef int S32;
typedef unsigned int U32;
typedef unsigned char U8;
int
random_number(unsigned char *dst, int len, void *dat);
S32
main(void)
{
S32 err, i, t;
U8 p[BYTENUM(RSA_P_SIZE)];
U8 q[BYTENUM(RSA_Q_SIZE)];
U8 n[BYTENUM(RSA_N_SIZE)];
U8 e[3]={1, 0, 1};
U8 d[BYTENUM(RSA_D_SIZE)];
U8 en[BYTENUM(RSA_EN_SIZE)];
mp_int _p, _q, _n, _e, _d, _en;
if((err = mp_init_multi(&_p, &_q, &_n, &_e, &_d, &_en, NULL)) != MP_OKAY)
{
goto LIF;
}
//获得素数P的审判次数
t=mp_prime_rabin_miller_trials(RSA_P_SIZE);
//生成大素数P
if((err = mp_prime_random_ex(&_p, t, RSA_P_SIZE, LTM_PRIME_2MSB_ON, random_number, NULL)) != MP_OKAY)
{
goto LBL;
}
dump_mp_int_to_char (&_p, BYTENUM(RSA_P_SIZE), (char *)p);
printf("p:\n");
for (i = 0; i < BYTENUM(RSA_P_SIZE); ++i)
{
printf("0x%02X, ", p[i]);
if (7 == (i & 7))
{
printf("\n");
}
}
//获得素数Q的审判次数
t=mp_prime_rabin_miller_trials(RSA_Q_SIZE);
//生成大素数P
if((err = mp_prime_random_ex(&_q, t, RSA_Q_SIZE, LTM_PRIME_2MSB_ON, random_number, NULL)) != MP_OKAY)
{
goto LBL;
}
dump_mp_int_to_char (&_q, BYTENUM(RSA_P_SIZE), (char *)q);
printf("\nq:\n");
for (i = 0; i < BYTENUM(RSA_P_SIZE); ++i)
{
printf("0x%02X, ", q[i]);
if (7 == (i & 7))
{
printf("\n");
}
}
//计算n=p*q
if ((err = mp_mul(&_p, &_q, &_n)) != MP_OKAY)
{
goto LBL;
}
dump_mp_int_to_char (&_n, BYTENUM(RSA_N_SIZE), (char *)n);
printf("\nn:\n");
for (i = 0; i < BYTENUM(RSA_N_SIZE); ++i)
{
printf("0x%02X, ", n[i]);
if (7 == (i & 7))
{
printf("\n");
}
}
//计算p-1
if ((err = mp_sub_d (&_p, 1, &_p)) != MP_OKAY)
{
goto LBL;
}
//计算q-1
if ((err = mp_sub_d (&_q, 1, &_q)) != MP_OKAY)
{
goto LBL;
}
//计算(p-1)*(q-1)
if ((err = mp_mul (&_p, &_q, &_en)) != MP_OKAY)
{
goto LBL;
}
dump_mp_int_to_char (&_en, BYTENUM(RSA_EN_SIZE), (char *)en);
printf("\nen:\n");
for (i = 0; i < BYTENUM(RSA_EN_SIZE); ++i)
{
printf("0x%02X, ", en[i]);
if (7 == (i & 7))
{
printf("\n");
}
}
if ((err = mp_read_unsigned_bin(&_e, e, 3)) != MP_OKAY)
{
goto LBL;
}
//计算d=e^-1 mod (p-1)*(q-1)
if ((err = mp_invmod(&_e, &_en, &_d)) != MP_OKAY)
{
goto LBL;
}
dump_mp_int_to_char (&_d, BYTENUM(RSA_D_SIZE), (char *)d);
printf("\nd:\n");
for (i = 0; i < BYTENUM(RSA_D_SIZE); ++i)
{
printf("0x%02X, ", d[i]);
if (7 == (i & 7))
{
printf("\n");
}
}
LBL:mp_clear_multi(&_p, &_q, &_n, &_e, &_d, &_en, NULL);
LIF:
printf("Press any key to continue");
getch();
return err;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -