Using OpenSSL BN Library in C
Overview on using the big numbers library OpenSSL provides for C.
Using OpenSSL BN Library in C
It's strongly advised to utilize a big number library in this example to avoid concerns about the size of the operations. The following is a brief overview of the OpenSSL big number library to help you with implementation. To integrate this effectively into your code, replace all arithmetic operations and operators with BN structures and corresponding functions.
Offical Documentation found here: OpenSSL BN Docs
- Use
BN_new()to allocate and initialize aBIGNUMstructure. This will return a pointer to theBIGNUMinitialized to the value 0. If this fails, it will return NULL and set an error code that can be retrieved withERR_get_error(). - Use
BN_CTX_new()to allocate and initialize aBN_CTXstructure. ABN_CTXis a structure that holdsBIGNUMtemporary variables used by some of the library functions. This is because dynamic memory allocation to createBIGNUMs can be expensive when used with repeated subroutine calls. The solution is to use aBN_CTXstructure. Handle error-checking the same as step 1. BN_zero(BIGNUM *a)andBN_set_word(BIGNUM *a)set a to the values 0, and w respectively.BN_zero()andBN_set_word()return 1 on success and 0 otherwise.- To raise a base to a power, use:
BN_exp(BIGNUM *res, BIGNUM *base, BIGNUM *pow, BN_CTX *ctx)For all arithmetic functions, 1 is returned for success and 0 otherwise. - Free the unused structures using
BN_free().Free theBN_CTXstructure usingBN_CTX_free(). - To export result into a string, declare an empty string and use
strncpyto copy thecontents ofBN_bn2dec(result)into the new string. Free the result structure once finished.
There are more export options linked below:
Example showing exponentiation:
BIGNUM *base = BN_new();
if (base == NULL) {
/* handle error */
}
BIGNUM *power = BN_new();
if (power == NULL) {
/* handle error */
}
BIGNUM *result = BN_new();
if (result == NULL) {
/* handle error */
}
BN_CTX *ctx = BN_CTX_new();
if (ctx == NULL) {
/* handle error */
}
if ((BN_zero(result)) == 1) {
/* handle error */
}
if ((BN_set_word(base, 10)) == 1) {
/* handle error */
}
if ((BN_set_word(power, 22)) == 1) {
/* handle error */
}
if ((BN_exp(result, (const BIGNUM *) power,
(const BIGNUM *) base, ctx)) == 1) {
/* handle error */
}
BN_free(power);
BN_free(base);
BN_CTX_free(ctx);
/* Result is stored in 'result' object, exporting that into a string
is shown below. For more export options please visit 'export options'
button linked below example. */
char result_str[STRSIZE];
strncpy(result_str, BN_bn2dec(result), sizeof(result_str));