/src/openssl111/crypto/ec/ecdh_kdf.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. |
3 | | * |
4 | | * Licensed under the OpenSSL license (the "License"). You may not use |
5 | | * this file except in compliance with the License. You can obtain a copy |
6 | | * in the file LICENSE in the source distribution or at |
7 | | * https://www.openssl.org/source/license.html |
8 | | */ |
9 | | |
10 | | #include <string.h> |
11 | | #include <openssl/ec.h> |
12 | | #include <openssl/evp.h> |
13 | | #include "ec_local.h" |
14 | | |
15 | | /* Key derivation function from X9.63/SECG */ |
16 | | /* Way more than we will ever need */ |
17 | 0 | #define ECDH_KDF_MAX (1 << 30) |
18 | | |
19 | | int ecdh_KDF_X9_63(unsigned char *out, size_t outlen, |
20 | | const unsigned char *Z, size_t Zlen, |
21 | | const unsigned char *sinfo, size_t sinfolen, |
22 | | const EVP_MD *md) |
23 | 0 | { |
24 | 0 | EVP_MD_CTX *mctx = NULL; |
25 | 0 | int rv = 0; |
26 | 0 | unsigned int i; |
27 | 0 | size_t mdlen; |
28 | 0 | unsigned char ctr[4]; |
29 | 0 | if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX |
30 | 0 | || Zlen > ECDH_KDF_MAX) |
31 | 0 | return 0; |
32 | 0 | mctx = EVP_MD_CTX_new(); |
33 | 0 | if (mctx == NULL) |
34 | 0 | return 0; |
35 | 0 | mdlen = EVP_MD_size(md); |
36 | 0 | for (i = 1;; i++) { |
37 | 0 | unsigned char mtmp[EVP_MAX_MD_SIZE]; |
38 | 0 | if (!EVP_DigestInit_ex(mctx, md, NULL)) |
39 | 0 | goto err; |
40 | 0 | ctr[3] = i & 0xFF; |
41 | 0 | ctr[2] = (i >> 8) & 0xFF; |
42 | 0 | ctr[1] = (i >> 16) & 0xFF; |
43 | 0 | ctr[0] = (i >> 24) & 0xFF; |
44 | 0 | if (!EVP_DigestUpdate(mctx, Z, Zlen)) |
45 | 0 | goto err; |
46 | 0 | if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr))) |
47 | 0 | goto err; |
48 | 0 | if (!EVP_DigestUpdate(mctx, sinfo, sinfolen)) |
49 | 0 | goto err; |
50 | 0 | if (outlen >= mdlen) { |
51 | 0 | if (!EVP_DigestFinal(mctx, out, NULL)) |
52 | 0 | goto err; |
53 | 0 | outlen -= mdlen; |
54 | 0 | if (outlen == 0) |
55 | 0 | break; |
56 | 0 | out += mdlen; |
57 | 0 | } else { |
58 | 0 | if (!EVP_DigestFinal(mctx, mtmp, NULL)) |
59 | 0 | goto err; |
60 | 0 | memcpy(out, mtmp, outlen); |
61 | 0 | OPENSSL_cleanse(mtmp, mdlen); |
62 | 0 | break; |
63 | 0 | } |
64 | 0 | } |
65 | 0 | rv = 1; |
66 | 0 | err: |
67 | 0 | EVP_MD_CTX_free(mctx); |
68 | 0 | return rv; |
69 | 0 | } |
70 | | |
71 | | /*- |
72 | | * The old name for ecdh_KDF_X9_63 |
73 | | * Retained for ABI compatibility |
74 | | */ |
75 | | int ECDH_KDF_X9_62(unsigned char *out, size_t outlen, |
76 | | const unsigned char *Z, size_t Zlen, |
77 | | const unsigned char *sinfo, size_t sinfolen, |
78 | | const EVP_MD *md) |
79 | 0 | { |
80 | 0 | return ecdh_KDF_X9_63(out, outlen, Z, Zlen, sinfo, sinfolen, md); |
81 | 0 | } |