?? 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 + -