如何为openssl bignum编写通用函数模板?

时间:2018-04-26 04:22:03

标签: c openssl cryptography bignum

我正在寻找为openssl创建一个简单的通用函数模板 bignum图书馆。我希望它具有所有biolerplate包括和已经存在的其他东西,它应该遵循与其他bignum功能相同的模式。它应该像:

#include <openssl/bn.h>    

int Big_Func(BIGNUM* RESULT, BIGNUM *X, BIGNUM *Y){
     //biolerplate bignum stuff

    //your code goes here

   // more biolerplate
}

我留下了一个基于bn_gcd找到的答案,但似乎有点矫枉过正。

1 个答案:

答案 0 :(得分:0)

include <openssl/bn.h>
include <stdio.h>

/ * 这个函数假设它被调用在另一个函数中,比如 main,它有bn_ctx变量传递给func  * /

int BN_func(BIGNUM *R, BIGNUM *in_a,BIGNUM *in_b, BN_CTX *ctx)
{
 BIGNUM *a, *b, *t;//declare ptrs of type BIGNUM
 int ret = 0;//return code

bn_check_top(in_a);//checktop does makes sure the
                 // internal array is nonempty
bn_check_top(in_b);

BN_CTX_start(ctx);//BigNum context usedto obtain temp BN vars from
// a BN_CTX which have already been created by using BN_CTX_new
a = BN_CTX_get(ctx);//gets ptr from ctx
b = BN_CTX_get(ctx);//
if (a == NULL || b == NULL) //checks if ptr is NULL; 
                    //if so, exits immediately.
    goto err;

if (BN_copy(a, in_a) == NULL)//copy the func params to local ctx vars
  goto err;        //check if null as above
if (BN_copy(b, in_b) == NULL)
 goto err;
a->neg = 0;// sets neg to 0 indicating positive qty.
b->neg = 0;
/*after all that we can calculate with the 'a' and 'b' params safely*/

//your code here

   /*on error go here*/
 err:
   BN_CTX_end(ctx);
   bn_check_top(R);
   return (ret);
}