Openssl中的大数取小整数取模

pip*_*low 4 c openssl

我想知道Openssl中的大数是否可以对小整数取模?

假设我产生两个大质数:

BN_generate_prime(p,512,0,0,0,0,0);
BN_generate_prime(q,512,0,0,0,0,0);
Run Code Online (Sandbox Code Playgroud)

并计算乘积N

BN_mul(N,p,q,ctx);
Run Code Online (Sandbox Code Playgroud)

我想测试是否N为“ Blum整数”(N mod 4 == 3),但是由于函数BN_mod仅支持大数,因此我无法弄清楚该怎么做。

ind*_*div 5

是的,有可能。

jww的答案给出了最佳和有效的方法,即调用BN_mod_word()

一种效率较低的方法是先转换一个小整数来实现BIGNUM。这很麻烦,但并不困难。我会告诉你两种方式创建BIGNUM通过计算小号11 mod 3BN_mod。首先,为您的号码声明一个BIGNUM。

BIGNUM *N = BN_new();
BIGNUM *M = BN_new();
Run Code Online (Sandbox Code Playgroud)

方法1:将您的数字转换为字符串,然后将该字符串转换为BIGNUM。

#include <sstream>
int n = 11;
std::ostringstream num_str;
num_str << n;
BN_dec2bn( &N, num_str.str().c_str() );
Run Code Online (Sandbox Code Playgroud)

(在C中,您可以做char buf[12]; sprintf(buf, "%d", n); BN_dec2bn(&N, buf);

方法2:将您的数字提供为字节数组,但是请注意,OpenSSL希望您的字节为大端字节格式,并且始终将您的字节解释为正数。

#include <arpa/inet.h>   // For htonl to make the integer big endian
int m = 3;
m = htonl(m);
BN_bin2bn( (unsigned char *) &m, sizeof(m), M);
Run Code Online (Sandbox Code Playgroud)

然后只需正常使用OpenSSL函数即可。

BN_mod(rem, N, M, ctx);
BN_print_fp(stdout, rem);  // (Using N=11 and M=3 above, this line prints 2)
Run Code Online (Sandbox Code Playgroud)

并释放您BIGNUM的。

BN_free(N);
BN_free(M);
Run Code Online (Sandbox Code Playgroud)