On 20 January 2014 15:34, khan wahid <rr...@yahoo.com> wrote:
> 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));

You should check the return values of these calls to check that they
have worked! However I will assume that this is not your problem (see
below)...

>         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);

You should not use strlen to find the length of binary data. This
could potentially cause a seg fault.

You have not said what version of openssl you are running, so I have
checked the standard default behaviour of Openssl 1.0.1f. DH_new does
not allocate the BIGNUMs for p and g. They are set to NULL. The call
to BN_bin2bn will check the value of its 3rd argument. If it is null
it will allocate a BIGNUM and return it. Therefore this is what is
happening to your code. The values of p and g will remain as NULL, and
the allocated BIGNUMs are being ignored by your code.

>
>         DH_generate_key(dhPar);

This is clearly going to fail (with a seg fault) because the
parameters have not been set (as noted above).

If you have not already found it, you should check this page which
gives details and code samples of working with DH:

http://wiki.openssl.org/index.php/Diffie_Hellman

Matt
______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
User Support Mailing List                    openssl-users@openssl.org
Automated List Manager                           majord...@openssl.org

Reply via email to