copensslcryptographyelgamal

Elgamal BN_exp() operation get stuck


I'm trying to implement Elgamal operations. The common first one is the multiplication between two BIGNUM. The second is the exponentiation of two BIGNUM (e.g. h:=g^x, c_1:=g^y). When I do the BN_exp(), the C program get stuck. Why? Further, any suggestion to solve the problem?

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <openssl/obj_mac.h>
#include <openssl/ec.h>
#include <openssl/rand.h>
#include <openssl/bn.h>

int main(int argc, char *argv[])
{
BN_CTX *ctx;

    BIGNUM *bn1 = BN_new();
    BIGNUM *bn2 = BN_new();
    BIGNUM *result = BN_new();
    BIGNUM *r = BN_new();
    BN_CTX *bn_ctx = BN_CTX_new();

    static const char rnd_seed[] = "string to make the random number generator think it has entropy";
    RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime_ex may fail */
    BN_generate_prime_ex(r, 1024, 0, NULL, NULL, NULL);

    BN_rand_range(bn1, r);
    BN_rand_range(bn2, r);

    BN_mul(result, bn2, bn1, bn_ctx);
    
    BN_exp(result, bn2, bn1, bn_ctx); // here get stuck!
    
    return 0;
}

Solution

  • As @Topaco suggested in the comment, ElGamal requires (the better performing) modulo operations, i.e. BN_mod_mul(), BN_mod_exp() and BN_mod_inverse().