All Collections
HackEDU Lesson Help
Using OpenSSL BN Library in C
Using OpenSSL BN Library in C

Overview on using the big numbers library OpenSSL provides for C

T
Written by Tyler Cooper
Updated over a week ago

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.

Official Documentation linked below:


  1. Use BN_new() to allocate and initialize a BIGNUM structure. This will return a pointer to the BIGNUM initialized to the value 0. If this fails, it will return NULL and set an error code that can be retrieved with ERR_get_error().
    โ€‹

  2. Use BN_CTX_new() to allocate and initialize a BN_CTX structure. A BN_CTX is a structure that holds BIGNUM temporary variables used by some of the library functions. This is because dynamic memory allocation to create BIGNUMs can be expensive when used with repeated subroutine calls. The solution is to use a BN_CTX structure. Handle error-checking the same as step 1.

  3. BN_zero(BIGNUM *a) and BN_set_word(BIGNUM *a) set a to the values 0, and w respectively. BN_zero() and BN_set_word() return 1 on success and 0 otherwise.

  4. 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.

  5. Free the unused structures using BN_free().

  6. Free the BN_CTX structure using BN_CTX_free().

  7. To export result into a string, declare an empty string and use strncpy to copy the contents of BN_bn2dec(result) into the new string. Free the result structure once finished. (There are more export options linked below the example)


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));


Did this answer your question?