]>
Commit | Line | Data |
---|---|---|
25af7a5d | 1 | /* |
4f22f405 | 2 | * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. |
25af7a5d | 3 | * |
4f22f405 RS |
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 | |
25af7a5d DSH |
8 | */ |
9 | ||
25af7a5d | 10 | #include <string.h> |
768c53e1 | 11 | #include <openssl/ec.h> |
25af7a5d DSH |
12 | #include <openssl/evp.h> |
13 | ||
25af7a5d | 14 | /* Key derivation function from X9.62/SECG */ |
579a7590 | 15 | /* Way more than we will ever need */ |
0f113f3e | 16 | #define ECDH_KDF_MAX (1 << 30) |
25af7a5d | 17 | |
0f113f3e MC |
18 | int ECDH_KDF_X9_62(unsigned char *out, size_t outlen, |
19 | const unsigned char *Z, size_t Zlen, | |
20 | const unsigned char *sinfo, size_t sinfolen, | |
21 | const EVP_MD *md) | |
22 | { | |
6e59a892 | 23 | EVP_MD_CTX *mctx = NULL; |
0f113f3e MC |
24 | int rv = 0; |
25 | unsigned int i; | |
26 | size_t mdlen; | |
27 | unsigned char ctr[4]; | |
28 | if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX | |
29 | || Zlen > ECDH_KDF_MAX) | |
30 | return 0; | |
bfb0641f | 31 | mctx = EVP_MD_CTX_new(); |
6e59a892 RL |
32 | if (mctx == NULL) |
33 | return 0; | |
0f113f3e | 34 | mdlen = EVP_MD_size(md); |
0f113f3e MC |
35 | for (i = 1;; i++) { |
36 | unsigned char mtmp[EVP_MAX_MD_SIZE]; | |
6e59a892 | 37 | EVP_DigestInit_ex(mctx, md, NULL); |
0f113f3e MC |
38 | ctr[3] = i & 0xFF; |
39 | ctr[2] = (i >> 8) & 0xFF; | |
40 | ctr[1] = (i >> 16) & 0xFF; | |
41 | ctr[0] = (i >> 24) & 0xFF; | |
6e59a892 | 42 | if (!EVP_DigestUpdate(mctx, Z, Zlen)) |
0f113f3e | 43 | goto err; |
6e59a892 | 44 | if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr))) |
0f113f3e | 45 | goto err; |
6e59a892 | 46 | if (!EVP_DigestUpdate(mctx, sinfo, sinfolen)) |
0f113f3e MC |
47 | goto err; |
48 | if (outlen >= mdlen) { | |
6e59a892 | 49 | if (!EVP_DigestFinal(mctx, out, NULL)) |
0f113f3e MC |
50 | goto err; |
51 | outlen -= mdlen; | |
52 | if (outlen == 0) | |
53 | break; | |
54 | out += mdlen; | |
55 | } else { | |
6e59a892 | 56 | if (!EVP_DigestFinal(mctx, mtmp, NULL)) |
0f113f3e MC |
57 | goto err; |
58 | memcpy(out, mtmp, outlen); | |
59 | OPENSSL_cleanse(mtmp, mdlen); | |
60 | break; | |
61 | } | |
62 | } | |
63 | rv = 1; | |
64 | err: | |
bfb0641f | 65 | EVP_MD_CTX_free(mctx); |
0f113f3e MC |
66 | return rv; |
67 | } |