dh.c
Go to the documentation of this file.
1 /**
2  * @file dh.c
3  * @brief Diffie-Hellman key exchange
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneCRYPTO Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @section Description
28  *
29  * The Diffie-Hellman key agreement protocol allows two users to exchange a
30  * secret key over an insecure medium without any prior secrets. Refer to
31  * PKCS #3 (Diffie-Hellman Key-Agreement Standard)
32  *
33  * @author Oryx Embedded SARL (www.oryx-embedded.com)
34  * @version 2.4.0
35  **/
36 
37 //Switch to the appropriate trace level
38 #define TRACE_LEVEL CRYPTO_TRACE_LEVEL
39 
40 //Dependencies
41 #include "core/crypto.h"
42 #include "pkc/dh.h"
43 #include "debug.h"
44 
45 //Check crypto library configuration
46 #if (DH_SUPPORT == ENABLED)
47 
48 
49 /**
50  * @brief Initialize Diffie-Hellman context
51  * @param[in] context Pointer to the Diffie-Hellman context
52  **/
53 
54 void dhInit(DhContext *context)
55 {
56  //Initialize Diffie-Hellman parameters
57  dhInitParameters(&context->params);
58 
59  //Initialize private and public values
60  mpiInit(&context->xa);
61  mpiInit(&context->ya);
62  mpiInit(&context->yb);
63 }
64 
65 
66 /**
67  * @brief Release Diffie-Hellman context
68  * @param[in] context Pointer to the Diffie-Hellman context
69  **/
70 
71 void dhFree(DhContext *context)
72 {
73  //Release Diffie-Hellman parameters
74  dhFreeParameters(&context->params);
75 
76  //Release private and public values
77  mpiFree(&context->xa);
78  mpiFree(&context->ya);
79  mpiFree(&context->yb);
80 }
81 
82 
83 /**
84  * @brief Initialize Diffie-Hellman parameters
85  * @param[in] params Pointer to the Diffie-Hellman parameters
86  **/
87 
89 {
90  //Initialize prime modulus
91  mpiInit(&params->p);
92  //Initialize generator
93  mpiInit(&params->g);
94 }
95 
96 
97 /**
98  * @brief Release Diffie-Hellman parameters
99  * @param[in] params Pointer to the Diffie-Hellman parameters
100  **/
101 
103 {
104  //Release prime modulus
105  mpiFree(&params->p);
106  //Release generator
107  mpiFree(&params->g);
108 }
109 
110 
111 /**
112  * @brief Diffie-Hellman key pair generation
113  * @param[in] context Pointer to the Diffie-Hellman context
114  * @param[in] prngAlgo PRNG algorithm
115  * @param[in] prngContext Pointer to the PRNG context
116  * @return Error code
117  **/
118 
119 error_t dhGenerateKeyPair(DhContext *context, const PrngAlgo *prngAlgo,
120  void *prngContext)
121 {
122  error_t error;
123  uint_t k;
124 
125  //Debug message
126  TRACE_DEBUG("Generating Diffie-Hellman key pair...\r\n");
127 
128  //Get the length in bits of the prime p
129  k = mpiGetBitLength(&context->params.p);
130  //Ensure the length is valid
131  if(k == 0)
133 
134  //The private value shall be randomly generated
135  error = mpiRand(&context->xa, k, prngAlgo, prngContext);
136  //Any error to report?
137  if(error)
138  return error;
139 
140  //The private value shall be less than p
141  if(mpiComp(&context->xa, &context->params.p) >= 0)
142  {
143  //Shift value to the right
144  error = mpiShiftRight(&context->xa, 1);
145  //Any error to report?
146  if(error)
147  return error;
148  }
149 
150  //Debug message
151  TRACE_DEBUG(" Private value:\r\n");
152  TRACE_DEBUG_MPI(" ", &context->xa);
153 
154  //Calculate the corresponding public value (ya = g ^ xa mod p)
155  error = mpiExpModRegular(&context->ya, &context->params.g, &context->xa,
156  &context->params.p);
157  //Any error to report?
158  if(error)
159  return error;
160 
161  //Debug message
162  TRACE_DEBUG(" Public value:\r\n");
163  TRACE_DEBUG_MPI(" ", &context->ya);
164 
165  //Check public value
166  error = dhCheckPublicKey(&context->params, &context->ya);
167  //Weak public value?
168  if(error)
169  return error;
170 
171  //Public value successfully generated
172  return NO_ERROR;
173 }
174 
175 
176 /**
177  * @brief Check Diffie-Hellman public value
178  * @param[in] params Pointer to the Diffie-Hellman parameters
179  * @param[in] publicKey Public value to be checked
180  * @return Error code
181  **/
182 
183 error_t dhCheckPublicKey(DhParameters *params, const Mpi *publicKey)
184 {
185  error_t error;
186  Mpi a;
187 
188  //Initialize multiple precision integer
189  mpiInit(&a);
190  //Precompute p - 1
191  error = mpiSubInt(&a, &params->p, 1);
192 
193  //Check status
194  if(!error)
195  {
196  //Reject weak public values 1 and p - 1
197  if(mpiCompInt(publicKey, 1) <= 0)
198  {
199  error = ERROR_ILLEGAL_PARAMETER;
200  }
201  else if(mpiComp(publicKey, &a) >= 0)
202  {
203  error = ERROR_ILLEGAL_PARAMETER;
204  }
205  }
206 
207  //Free previously allocated resources
208  mpiFree(&a);
209  //Return status code
210  return error;
211 }
212 
213 
214 /**
215  * @brief Compute Diffie-Hellman shared secret
216  * @param[in] context Pointer to the Diffie-Hellman context
217  * @param[out] output Buffer where to store the shared secret
218  * @param[in] outputSize Size of the buffer in bytes
219  * @param[out] outputLen Length of the resulting shared secret
220  * @return Error code
221  **/
222 
223 error_t dhComputeSharedSecret(DhContext *context, uint8_t *output,
224  size_t outputSize, size_t *outputLen)
225 {
226  error_t error;
227  size_t k;
228  Mpi z;
229 
230  //Debug message
231  TRACE_DEBUG("Computing Diffie-Hellman shared secret...\r\n");
232 
233  //Get the length in octets of the prime modulus
234  k = mpiGetByteLength(&context->params.p);
235 
236  //Make sure that the output buffer is large enough
237  if(outputSize < k)
238  return ERROR_INVALID_LENGTH;
239 
240  //The multiple precision integer must be initialized before it can be used
241  mpiInit(&z);
242 
243  //Start of exception handling block
244  do
245  {
246  //Calculate the shared secret key (k = yb ^ xa mod p)
247  error = mpiExpModRegular(&z, &context->yb, &context->xa,
248  &context->params.p);
249  //Any error to report?
250  if(error)
251  break;
252 
253  //Convert the resulting integer to an octet string
254  error = mpiWriteRaw(&z, output, k);
255  //Conversion failed?
256  if(error)
257  break;
258 
259  //Length of the resulting shared secret
260  *outputLen = k;
261 
262  //Debug message
263  TRACE_DEBUG(" Shared secret (%" PRIuSIZE " bytes):\r\n", *outputLen);
264  TRACE_DEBUG_ARRAY(" ", output, *outputLen);
265 
266  //End of exception handling block
267  } while(0);
268 
269  //Release previously allocated resources
270  mpiFree(&z);
271  //Return status code
272  return error;
273 }
274 
275 #endif
unsigned int uint_t
Definition: compiler_port.h:50
#define PRIuSIZE
General definitions for cryptographic algorithms.
#define PrngAlgo
Definition: crypto.h:917
#define mpiWriteRaw(a, data, length)
Definition: crypto_legacy.h:36
Debugging facilities.
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:108
#define TRACE_DEBUG(...)
Definition: debug.h:107
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:110
error_t dhGenerateKeyPair(DhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
Diffie-Hellman key pair generation.
Definition: dh.c:119
void dhFreeParameters(DhParameters *params)
Release Diffie-Hellman parameters.
Definition: dh.c:102
void dhInitParameters(DhParameters *params)
Initialize Diffie-Hellman parameters.
Definition: dh.c:88
void dhInit(DhContext *context)
Initialize Diffie-Hellman context.
Definition: dh.c:54
error_t dhComputeSharedSecret(DhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute Diffie-Hellman shared secret.
Definition: dh.c:223
error_t dhCheckPublicKey(DhParameters *params, const Mpi *publicKey)
Check Diffie-Hellman public value.
Definition: dh.c:183
void dhFree(DhContext *context)
Release Diffie-Hellman context.
Definition: dh.c:71
Diffie-Hellman key exchange.
uint8_t z
Definition: dns_common.h:191
error_t
Error codes.
Definition: error.h:43
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:242
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_LENGTH
Definition: error.h:111
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:234
int_t mpiCompInt(const Mpi *a, int_t b)
Compare a multiple precision integer with an integer.
Definition: mpi.c:382
int_t mpiComp(const Mpi *a, const Mpi *b)
Compare two multiple precision integers.
Definition: mpi.c:338
error_t mpiShiftRight(Mpi *r, uint_t n)
Right shift operation.
Definition: mpi.c:1178
void mpiInit(Mpi *r)
Initialize a multiple precision integer.
Definition: mpi.c:48
error_t mpiSubInt(Mpi *r, const Mpi *a, int_t b)
Subtract an integer from a multiple precision integer.
Definition: mpi.c:913
uint_t mpiGetByteLength(const Mpi *a)
Get the actual length in bytes.
Definition: mpi.c:195
error_t mpiRand(Mpi *r, uint_t length, const PrngAlgo *prngAlgo, void *prngContext)
Generate a random value.
Definition: mpi.c:515
void mpiFree(Mpi *r)
Release a multiple precision integer.
Definition: mpi.c:64
uint8_t a
Definition: ndp.h:411
error_t mpiExpModRegular(Mpi *r, const Mpi *a, const Mpi *e, const Mpi *p)
Modular exponentiation (regular calculation)
Diffie-Hellman context.
Definition: dh.h:60
Mpi yb
Peer's public value.
Definition: dh.h:64
Mpi xa
One's own private value.
Definition: dh.h:62
Mpi ya
One's own public value.
Definition: dh.h:63
DhParameters params
Definition: dh.h:61
Diffie-Hellman parameters.
Definition: dh.h:49
Mpi p
Prime modulus.
Definition: dh.h:50
Mpi g
Generator.
Definition: dh.h:51
Arbitrary precision integer.
Definition: mpi.h:80