Hi,
I am trying to implement DH key exchage using openssl in the same program, so I 
generate DH parameters once, and then transfer the p and g to another DH 
object, here is my code-
 #include <stdio.h>
 #include <string.h>
 #include <openssl/dh.h>
 #include <openssl/engine.h>
 #include <time.h>
 
void hexprint(unsigned char *printBuf, int len)
    {
        int i;
        for(i = 0; i < len; i++)
        {
            printf("%x ", printBuf[i]);
        }
        printf("\n");
    }

int main(int argc, char *argv[])
    {
        DH *dhPar=DH_new();
        DH *dhPar2=DH_new();
        time_t rt;
        srand((unsigned) time(&rt));

        unsigned char *dhSec1;
        unsigned char *dhSec2;
        printf("Generate parameter \n");
        DH_generate_parameters_ex(dhPar, 1024, DH_GENERATOR_2, 0);

        unsigned char *parmp=malloc(sizeof(unsigned char *) * 
BN_num_bytes(dhPar->p));
        unsigned char *parmg=malloc(sizeof(unsigned char *) *  
BN_num_bytes(dhPar->g));
        memset(parmp, 0, BN_num_bytes(dhPar->p));
        memset(parmg, 0, BN_num_bytes(dhPar->g));

        BN_bn2bin(dhPar->p,parmp);
        BN_bn2bin(dhPar->g,parmg);

        BN_bin2bn(parmp,strlen(parmp), dhPar2->p);
        BN_bin2bn(parmg,strlen(parmg), dhPar2->g);

        DH_generate_key(dhPar);
        DH_generate_key(dhPar2);


        printf("Generate shared key in both \n");
        dhSec1 = OPENSSL_malloc(sizeof(unsigned char) * DH_size(dhPar));
        dhSec2 = OPENSSL_malloc(sizeof(unsigned char) * DH_size(dhPar2));
        memset(dhSec1, 0, DH_size(dhPar));
        memset(dhSec2, 0, DH_size(dhPar2));
        printf("Now computing key \n");
        DH_compute_key(dhSec1, dhPar2->pub_key, dhPar);
        DH_compute_key(dhSec2, dhPar->pub_key, dhPar2);



        printf("Secret Key 1: \n");
        hexprint(dhSec1, 32);
        printf("Secret Key 2: \n");
        hexprint(dhSec2, 32);

        free(dhSec1);
        free(dhSec2);
        DH_free(dhPar);
        DH_free(dhPar2);
    }



It gives me segmentation fault at  "DH_generate_key(dhPar2)", what am I doing 
wrong here?
I compiled it with "gcc dh.c -lcrypto -lssl", also individually did with 
"-lssl" and "-lcrypto", but all three compiled program gave the same result at 
the same place.
Please help.

Reply via email to