Topic: [SOLVED] Diffie-Helman Key agreement "wc_DhAgree" returns error (-243)

Hi everyone

I appreciate any hint in advanced.
Diffie-Helman Key agreement "wc_DhAgree" returns error (-243): "DH Check Public Key failure".

I tried to have both sides 'A' and 'B' in a same program and then establish a key using both private and public keys. I used 'p' and 'g' in cert_test.h  to generate public and private keys on side A. and also used 'dh_key_der_1024' in cert_test.h  to decode public and private keys for side B.

Side A:

DhKey keyA;
int ret;
const byte* pA= dh_p; // initialize with prime };
const  byte* gA= dh_g; // initialize with base };
byte privA[256];
byte pubA[256];
byte agree[256];
word32 agreeSz;
word32 privSzA, pubSzA;
wc_InitDhKey(&keyA); // initialize key
WC_RNG rng;
wc_InitRng(&rng); // initialize rng
ret = wc_DhSetKey(&keyA, pA, sizeof(pA), gA, sizeof(gA));
ret = wc_DhGenerateKeyPair(&keyA, &rng, privA, &privSzA, pubA, &pubSzA);

Side B:

DhKey keyB;    
byte privB[256];
byte pubB[256];    
word32 privSzB, pubSzB;
const unsigned char* tmpB = dh_key_der_1024;
word32 idxB = 0;
wc_InitDhKey(&keyB); // initialize key
ret = wc_DhKeyDecode(tmpB, &idxB, &keyB, sizeof_client_keypub_der_1024);
ret = wc_DhGenerateKeyPair(&keyB, &rng, privB, &privSzB, pubB, &pubSzB);

and finally

ret = wc_DhAgree(&keyA,agree, &agreeSz, privA, sizeof(privA), pubB, pubSzB);
printf("\r\nwc_DhAgree Error: (%d): %s",ret,errorString);


This will return error (-243): "DH Check Public Key failure". 
Any clue?!


Re: [SOLVED] Diffie-Helman Key agreement "wc_DhAgree" returns error (-243)

You are loading the domain parameters dh_p and dh_g into keyA and then making the keypair {pubA,privA}. Then you load dh_key_der_1024 into keyB and using that as the domain parameters for making the keypair {pubB,privB}. For key agreement, both A and B need to be using the same domain parameters.

3 (edited by alex.abrahamson 2018-08-31 14:01:36)

Re: [SOLVED] Diffie-Helman Key agreement "wc_DhAgree" returns error (-243)

Hi ehsan.aerabi,

In addition to John's suggestion, another thing I would point out is that you are passing the size of the pA pointer and the size of the gA pointer to wc_DhSetKey, not the actual size of the data. I would instead change that call to use these variables:

int pASz = sizeof(dh_p);
int gASz = sizeof(dh_g);

and then pass those variables in place of the previous sizeof calls (below)

ret = wc_DhSetKey(&keyA, pA, pASz, gA, gASz);


Re: [SOLVED] Diffie-Helman Key agreement "wc_DhAgree" returns error (-243)

john & alex.abrahamson

Thanks for your replies.
Clearly, as John has answered,  the root and modulo pair of parameters should be the same on both sides.

I missed this obvious point.