0

In my attempt to implement the Burmester-Desmedt key agreement using pure C I need to divide 2 public keys thus I thought the BN_div should do the job.

int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *a, const BIGNUM *d,BN_CTX *ctx);

But when I read the documentation:

divides a by d and places the result in dv and the remainder in rem (dv=a/d, rem=a%d). Either of dv and rem may be NULL, in which case the respective value is not returned. The result is rounded towards zero; thus if a is negative, the remainder will be zero or negative. For division by powers of 2, use BN_rshift(3).

I cannot understand what the parameter ctx is used for, so far what I understood that does is:

rem=a%d
dv=a/d

The ctx in this operation what is used for is parameter used for some sort of recursion and should be set as NULL ?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164

2 Answers2

3

For all functions, ctx is a previously allocated BN_CTX used for temporary variables; see BN_CTX_new.

so you have to do

BN_CTX *ctx = BN_CTX_new();
BIGNUM dv;
BIGNUM rem;
BIGNUM a = ...;
BIGNUM d = ...;

if (!BN_div(&dv, &rem, &a, &d, ctx))
  ...error case
else
  ...ok case

if you have other BN_xx to call you can reuse the same ctx, this is the goal

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
bruno
  • 32,421
  • 7
  • 25
  • 37
2

Verbatim from the docs:

A BN_CTX is a structure that holds BIGNUM temporary variables used by library functions. Since dynamic memory allocation to create BIGNUMs is rather expensive when used in conjunction with repeated subroutine calls, the BN_CTX structure is used.

Use BN_CTX_new() to create a context. Call BN_CTX_free() when done.

alk
  • 69,737
  • 10
  • 105
  • 255