【问题标题】:Define a constant BIGNUM in OpenSSL在 OpenSSL 中定义一个常量 BIGNUM
【发布时间】:2016-11-01 20:26:42
【问题描述】:

有没有办法在 C 中定义一个 BIGNUM* 类型和值 2^512 的常量,这相当于 Java:

private static final BigInteger THRESHOLD = BigInteger.valueOf(2).pow(512);

在本地范围内,我通过执行以下操作来实现此目的:

BN_CTX *ctx = BN_CTX_new();

BIGNUM *two = BN_new();
BN_set_word(two, 2);

BIGNUM *pow = BN_new();
BN_set_word(pow, 512);

BIGNUM * threshold = BN_new();
BN_exp(threshold, two, pow, ctx);

【问题讨论】:

    标签: c openssl bignum


    【解决方案1】:

    是和不是。

    在 OpenSSL 1.0.2/1.0.1 中这是可能的(警告:代码完全未经测试!)

    /*
     * I made up the numbers...too lazy to figure out what the real ones are!
     * Note that, the BN_ULONG values here are in little endian form,
     * so this represents:
     * D3FBF564FEB008A3
     */
    #if BN_BITS2 == 64
    static const BN_ULONG data[] = {
        0xA308B0FE64F5FBD3ULL
    };
    #else
    static const BN_ULONG data[] = {
        0x64F5FBD3, 0xA308B0FE
    };
    #endif
    
    static const BIGNUM threshold = {
        (BN_ULONG *) data,
        sizeof(data)/sizeof(BN_ULONG),
        sizeof(data)/sizeof(BN_ULONG),
        0,
        BN_FLG_STATIC_DATA
    };
    

    在 OpenSSL 1.1.0(尚未发布)中,事情并不那么容易。出于很好的原因,BIGNUM 结构已设为不透明,因此您无法再静态初始化数据。

    可以做这样的事情:

    static CRYPTO_ONCE threshold_once = CRYPTO_ONCE_STATIC_INIT;
    static BIGNUM *threshold = NULL;
    
    static void thresholdcleanup(void)
    {
        BN_free(threshold);
    }
    static void thresholdinit(void)
    {
        threshold = BN_new();
        /* Do stuff to set threshold to the right value */
        OPENSSL_atexit(thresholdcleanup);
    }
    
    static void my_func(void)
    {
        CRYPTO_THREAD_run_once(&threshold_once, threshholdinit);
    
        /* Use threshold here */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多