Path: blob/master/libs/tomcrypt/src/pk/dh/dh_shared_secret.c
4396 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/89#include "tomcrypt.h"1011#ifdef LTC_MDH1213/**14Create a DH shared secret.15@param private_key The private DH key in the pair16@param public_key The public DH key in the pair17@param out [out] The destination of the shared data18@param outlen [in/out] The max size and resulting size of the shared data.19@return CRYPT_OK if successful20*/21int dh_shared_secret(dh_key *private_key, dh_key *public_key,22unsigned char *out, unsigned long *outlen)23{24void *tmp;25unsigned long x;26int err;2728LTC_ARGCHK(private_key != NULL);29LTC_ARGCHK(public_key != NULL);30LTC_ARGCHK(out != NULL);31LTC_ARGCHK(outlen != NULL);3233/* types valid? */34if (private_key->type != PK_PRIVATE) {35return CRYPT_PK_NOT_PRIVATE;36}3738/* same DH group? */39if (mp_cmp(private_key->prime, public_key->prime) != LTC_MP_EQ) { return CRYPT_PK_TYPE_MISMATCH; }40if (mp_cmp(private_key->base, public_key->base) != LTC_MP_EQ) { return CRYPT_PK_TYPE_MISMATCH; }4142/* init big numbers */43if ((err = mp_init(&tmp)) != CRYPT_OK) {44return err;45}4647/* check public key */48if ((err = dh_check_pubkey(public_key)) != CRYPT_OK) {49goto error;50}5152/* compute tmp = y^x mod p */53if ((err = mp_exptmod(public_key->y, private_key->x, private_key->prime, tmp)) != CRYPT_OK) {54goto error;55}5657/* enough space for output? */58x = (unsigned long)mp_unsigned_bin_size(tmp);59if (*outlen < x) {60*outlen = x;61err = CRYPT_BUFFER_OVERFLOW;62goto error;63}64if ((err = mp_to_unsigned_bin(tmp, out)) != CRYPT_OK) {65goto error;66}67*outlen = x;68err = CRYPT_OK;6970error:71mp_clear(tmp);72return err;73}7475#endif /* LTC_MDH */767778