首页 > 解决方案 > OpenSSL BN_sub() 不能做有符号减法

问题描述

我正在尝试使用 OpenSSL 的BN函数执行减法。我期望有符号整数作为差异,但我得到的是无符号整数,或者整数溢出(或者如果我都没有得到想要的结果)。

我使用了错误的BN功能吗?

int big_num_subtract_example(vector<int> *arr, unsigned int mod, int seed_num) {
    BN_CTX *ctx;
    ctx = BN_CTX_new();

    BIGNUM *product = BN_new();
    BIGNUM *tmp = BN_new();
    BIGNUM *modulo = BN_new();
    BIGNUM *mod_result = BN_new();

    BN_set_word(product, seed_num);
    BN_set_word(modulo, mod);

    for (auto elem : arr) {

        BN_CTX_start(ctx);

        BN_set_word(tmp, elem);

        BN_mul(product, product, tmp, ctx);

        //Start of example
        BIGNUM *sub_one = BN_new();
        BIGNUM *sub_two = BN_new();

        BIGNUM *num_one = BN_new();
        BIGNUM *num_two = BN_new();

        BN_set_word(num_one, -7);
        BN_set_word(num_two, 11);

        BN_sub(sub_one, num_one, num_two);
        BN_sub(sub_two, num_two, num_one);

        cout << "sub_one: " << BN_get_word(sub_one) << "\n"; //18446744073709551598 expected -4
        cout << "sub_two: " << BN_get_word(sub_two) << "\n"; //18446744073709551598 expected 18

        BN_set_word(num_one, 7);
        BN_set_word(num_two, 11);

        BN_sub(sub_one, num_one, num_two);
        BN_sub(sub_two, num_two, num_one);

        cout << "sub_one: " << BN_get_word(sub_one) << "\n"; //4 expected -11
        cout << "sub_two: " << BN_get_word(sub_two) << "\n"; //4 
        //end of example


        //...
        //Code using the product from start of loop and result of subtraction...
        //...

        BN_CTX_end(ctx);

    }

    BN_clear_free(product);
    BN_clear_free(tmp);
    BN_clear_free(modulo);
    BN_clear_free(mod_result);
    BN_CTX_free(ctx);

    return 0;
}

文档状态:

BN_sub() 从 a 中减去 b 并将结果放入 r (r=ab)。r 可以是与 a 或 b 相同的 BIGNUM。

标签: c++copensslsignedbignum

解决方案


推荐阅读