Path: blob/master/libs/tomcrypt/src/pk/ecc/ecc_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/* Implements ECC over Z/pZ for curve y^2 = x^3 - 3x + b10*11* All curves taken from NIST recommendation paper of July 199912* Available at http://csrc.nist.gov/cryptval/dss.htm13*/14#include "tomcrypt.h"1516/**17@file ecc_shared_secret.c18ECC Crypto, Tom St Denis19*/2021#ifdef LTC_MECC2223/**24Create an ECC shared secret between two keys25@param private_key The private ECC key26@param public_key The public key27@param out [out] Destination of the shared secret (Conforms to EC-DH from ANSI X9.63)28@param outlen [in/out] The max size and resulting size of the shared secret29@return CRYPT_OK if successful30*/31int ecc_shared_secret(ecc_key *private_key, ecc_key *public_key,32unsigned char *out, unsigned long *outlen)33{34unsigned long x;35ecc_point *result;36void *prime;37int err;3839LTC_ARGCHK(private_key != NULL);40LTC_ARGCHK(public_key != NULL);41LTC_ARGCHK(out != NULL);42LTC_ARGCHK(outlen != NULL);4344/* type valid? */45if (private_key->type != PK_PRIVATE) {46return CRYPT_PK_NOT_PRIVATE;47}4849if (ltc_ecc_is_valid_idx(private_key->idx) == 0 || ltc_ecc_is_valid_idx(public_key->idx) == 0) {50return CRYPT_INVALID_ARG;51}5253if (XSTRCMP(private_key->dp->name, public_key->dp->name) != 0) {54return CRYPT_PK_TYPE_MISMATCH;55}5657/* make new point */58result = ltc_ecc_new_point();59if (result == NULL) {60return CRYPT_MEM;61}6263if ((err = mp_init(&prime)) != CRYPT_OK) {64ltc_ecc_del_point(result);65return err;66}6768if ((err = mp_read_radix(prime, (char *)private_key->dp->prime, 16)) != CRYPT_OK) { goto done; }69if ((err = ltc_mp.ecc_ptmul(private_key->k, &public_key->pubkey, result, prime, 1)) != CRYPT_OK) { goto done; }7071x = (unsigned long)mp_unsigned_bin_size(prime);72if (*outlen < x) {73*outlen = x;74err = CRYPT_BUFFER_OVERFLOW;75goto done;76}77zeromem(out, x);78if ((err = mp_to_unsigned_bin(result->x, out + (x - mp_unsigned_bin_size(result->x)))) != CRYPT_OK) { goto done; }7980err = CRYPT_OK;81*outlen = x;82done:83mp_clear(prime);84ltc_ecc_del_point(result);85return err;86}8788#endif899091