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:
Use
BN_new()
to allocate and initialize aBIGNUM
structure. This will return a pointer to theBIGNUM
initialized 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_CTX
structure. ABN_CTX
is a structure that holdsBIGNUM
temporary variables used by some of the library functions. This is because dynamic memory allocation to createBIGNUM
s can be expensive when used with repeated subroutine calls. The solution is to use aBN_CTX
structure. 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 the
BN_CTX
structure usingBN_CTX_free()
.To export result into a string, declare an empty string and use
strncpy
to copy the contents ofBN_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));