开发者

Big number modulo a small integer in Openssl

开发者 https://www.devze.com 2023-01-22 03:07 出处:网络
I was wondering if it is possible that a开发者_高级运维 big number modulo a small integer in Openssl?

I was wondering if it is possible that a开发者_高级运维 big number modulo a small integer in Openssl?

Say I generate two big prime numbers:

BN_generate_prime(p,512,0,0,0,0,0);
BN_generate_prime(q,512,0,0,0,0,0);

and calculate the product N:

BN_mul(N,p,q,ctx);

I would like to test if N is a "Blum integer" (N mod 4==3), however I can't figure out how to do this since function BN_mod only support big numbers.


Yes it's possible.

The best and efficient way is given in jww's answer, which is to call BN_mod_word().

A less efficient way is to do it by converting a small integer a BIGNUM first. It's cumbersome, but not difficult. I'll show you two ways to create the BIGNUMs by computing 11 mod 3 with BN_mod. First, declare a BIGNUM for your numbers.

BIGNUM *N = BN_new();
BIGNUM *M = BN_new();

Method 1: Convert your number to a string, and then the string to a BIGNUM.

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

(In C you can do char buf[12]; sprintf(buf, "%d", n); BN_dec2bn(&N, buf);)

Method 2: Give your number as an array of bytes, but beware that OpenSSL wants your bytes in big endian format, and will always interpret your bytes as a positive number.

#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);

And then just use your OpenSSL function as normal.

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

And free your BIGNUMs.

BN_free(N);
BN_free(M);


I was wondering if it is possible that a big number modulo a small integer in Openssl?

... test if N is a "Blum integer" (N mod 4==3), however I can't figure out how to do this since function BN_mod only support big numbers.

Yes, but it needs to be an unsigned integer, which you seem to have with the mod 4 equivalence class. Use BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w).

I use it for validating Diffie-Hellman parameters before using them. See, for example, Diffie-Hellman Parameter Check (when g = 2, must p mod 24 == 11?) on the Crypto Stack Exchange.

The man pages for the function is located at BN_mod_word(3).

0

精彩评论

暂无评论...
验证码 换一张
取 消