:: krowemoh

Friday | 27 DEC 2024
Posts Links Other About Now

previous
next

Big Integer Libraries

2023-08-04

The functions I want to add to ScarletDME are the string math functions and these are really just BigInteger math. I've realized that there are specialized libraries available and that I can simply include them instead of having to write them out.

GMP - GNU Multiple Precision

The first one I looked at incorporating into ScarletDME was libgmp. On CentOS 7, I could install it by doing the following:

yum install gmp-devel

Once installed, it's a simply process to actually use it:

#include <gmp.h>
#include <stdio.h>
#include <string.h>

int main(){
     char i[1024];
     char o[1024];
        
     char *num = "12345";
     strncpy(i,num,1024);
        
     mpz_t n;
     int flag;
        
     mpz_init(n);
     mpz_set_ui(n,0);
        
     flag = mpz_set_str(n,i, 10);
    
     mpz_get_str(o,10,n);
    
     printf("Ans: %s",o);
    
     mpz_clear(n);
     return 1;
  }

This program simply takes a string number and makes into a BigInteger or a multiple precision number and turns that back into a string. Not a complex example but it gets the point across. There are various function calls to do multiplication, division, addition and subtraction.

Compiling the program is also straightforward.

gcc test-gmp.c -o test-gmp -lgmp

Now to run it:

> ./test-gmp
12345

That is a very quick example of getting started with libgmp.

gmp

gmp Tutorial

gmp Functions

OpenSSL BIGNUM

The crypto library that ScarletDME uses already has Big Integer support however so it is a better idea to switch to using that implementation as I won't need to add any extra libraries. This was something I was pointed to when posting in the ScarletDME group on google groups.

Thread

It is a very similar code snippet:

#include <stdio.h>
#include <openssl/bn.h>
#include <string.h>

int main(){
    char i[1024];
    char *num = "12345";
    strncpy(i,num,1024);
    
    BIGNUM *n = BN_new();
    BN_dec2bn(&n, i);
    
    char *o = BN_bn2dec(n);
    printf("%s",o);
    
    OPENSSL_free(o);
    BN_free(n);
    return 1;
}

This program does the same thing as the gmp one, it takes a string number, turns it into a big integer and then turns it back into a string.

To compile it:

gcc test.bn.c -o test.bn.out -lcrypto

And then to run it:

> ./test.bn.out
12345

I've also learned now that a crypto library will need Big Integer support to be able to generate the large numbers that it needs. This is very much the same reason why I wanted the string math functions as I wanted to have my hashing implementation work. This is a good learning moment as now I know that if there is a crypto library somewhere then there is also support for very large numbers as well.