compute the remainder of the BIGNUM divided by any integer modulo

Advertisements

given some string, let assume , hello world. I know that the string in bits is: 01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100. so the value of the bits is 126207244316550804821666916. I was able to create code that give my the value of the bits. now I want to compute the remainder of the BIGNUM divided by any integer modulus, let assume 1024. I expect to get number between 0 to 1023. but when i trying to apply the modulo , i get error: Segmentation fault (core dumped)

this is the code that I using:

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


int main() {

    unsigned char message[] = "hello world"; //message
    //hello world = 01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
    //the value of bits is 126207244316550804821666916
    int length = strlen((char *)message);
    int i,j;

    BIGNUM *bn = BN_new();
    BN_zero(bn);

    for (i = 0; i < length; i++) {
        for(int j=0; j<8; j++){
            if (message[i] >> (7-j) & 1) {
                BN_lshift(bn, bn, 1);
                BN_add_word(bn, 1);
            }
            else {
                BN_lshift(bn, bn, 1);
            }
        }

    }

    BIGNUM *modolus = BN_new();
    BN_set_word(modolus, 1024);

    BN_mod(bn, bn, modolus, NULL);
    
    char *dec = BN_bn2dec(bn);
    printf("%s\n", dec);

    OPENSSL_free(dec);
    BN_free(bn);
    BN_free(modolus);

    return 0;

}


I’m new to C, i not sure what is exactly wrong here. after the loop i expect to get in bn the value 126207244316550804821666916, and its seems right. but when make module with 1024, i got error.

>Solution :

You can’t pass a null pointer as the context argument. It needs a pointer to a valid BN_CTX object.

For example,

BN_CTX *ctx = BN_CTX_new();
BN_mod(bn, bn, modolus, ctx);
BN_CTX_free(ctx);

In real code you’ll want to allocate the context object ahead of time and re-use it for subsequent computations instead of freeing it right away, of course.

Leave a ReplyCancel reply