Search code examples
copenssldivisionbignumlibcrypto

LibCrypt what is the use of the `ctx` parameter on BN_div?


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 ?


Solution

  • 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