OpenSSL测试-大数
20201331 黄文刚
0. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
- 基于OpenSSL的大数库计算1000内的素数的乘积(5‘)
- 基于OpenSSL的大数库计算你以及后面15位同学的8位学号(数字)的乘积(5‘)
- 用Python或bc命令验证计算的正确性(5’)
- 提交代码(或代码链接)和运行结果截图
一、基于OpenSSL的大数库计算1000内的素数的乘积
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>
int is_prime(int num)
{
if (num < 2)
return 0;
else if (num == 2)
return 1;
else if (num % 2 == 0)
return 0;
else
{
int i;
for (i = 3; i <= num / 2; i += 2)
{
if (num % i == 0)
return 0;
}
return 1;
}
}
int main()
{
BIGNUM *result = BN_new();
BIGNUM *num = BN_new();
BN_CTX *r = BN_CTX_new();
int i;
BN_set_word(result, 1);
for (i = 2; i < 1000; i++)
{
if (is_prime(i))
{
BN_set_word(num, i);
BN_mul(result, result, num, r);
}
}
char *result_str = BN_bn2dec(result);
printf("%s\n", result_str);
BN_free(result);
BN_free(num);
BN_CTX_free(r);
OPENSSL_free(result_str);
return 0;
}
二、基于OpenSSL的大数库计算你以及后面15位同学的8位学号(数字)的乘积
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>
int main()
{
BN_CTX *r[16];
BIGNUM *bn[12];
int i;
const char s[16][9] = {"20201331", "20201332", "20201301", "20201302", "20201303", "20201304", "20201305", "20201306", "20201307", "20201308", "20201309","20201310","20201311","20201312","20201313","20201314"};
char *out;
char t[2] = "1";
for (i = 0; i < 16; i++)
{
bn[i] = BN_new();
BN_dec2bn(&bn[i], s[i]);
r[i] = BN_CTX_new();
}
bn[11] = BN_new();
BN_dec2bn(&bn[16], t);
for (i = 0; i < 16; i++)
{
BN_mul(bn[16], bn[16], bn[i], r[i]);
}
out = BN_bn2dec(bn[16]);
puts(out); //打印出字符串
for (i = 0; i < 16; i++)
{
BN_free(bn[i]);
BN_CTX_free(r[i]);
}
BN_free(bn[i]);
free(out);
return 0;
}
三、用Python或bc命令验证计算的正确性
标签:16,bn,大数,OpenSSL,测试,include,BN From: https://www.cnblogs.com/killerqueen4/p/17386907.html