在 OpenSSL 中定义常量 BIGNUM
Define a constant BIGNUM in OpenSSL
有没有办法在 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);
是也不是。
在 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 */
}
有没有办法在 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);
是也不是。
在 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 */
}