LibCrypt BN_div 上的 `ctx` 参数有什么用?

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

在我尝试实施时,Burmester-Desmedt key agreement using pure C I need to divide 2 public keys thus I thought the BN_div 应该可以完成这项工作。但是当我阅读文档时:

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).

我无法理解参数 ctx 的用途,到目前为止我理解的是:

rem=a%d
dv=a/d

此操作中的ctx是用于某种递归的参数,应设置为NULL ?

来自 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.

使用BN_CTX_new()创建上下文。完成后调用 BN_CTX_free()

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

所以你必须做

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

如果您有其他 BN_xx 可以调用,您可以重复使用相同的 ctx,这就是目标