1 /* ecdh.c - ECDH public key operations used in public key glue code
2 * Copyright (C) 2010, 2011 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
32 /* A table with the default KEK parameters used by GnuPG. */
36 int openpgp_hash_id; /* KEK digest algorithm. */
37 int openpgp_cipher_id; /* KEK cipher algorithm. */
38 } kek_params_table[] =
39 /* Note: Must be sorted by ascending values for QBITS. */
41 { 256, DIGEST_ALGO_SHA256, CIPHER_ALGO_AES },
42 { 384, DIGEST_ALGO_SHA384, CIPHER_ALGO_AES256 },
44 /* Note: 528 is 521 rounded to the 8 bit boundary */
45 { 528, DIGEST_ALGO_SHA512, CIPHER_ALGO_AES256 }
50 /* Return KEK parameters as an opaque MPI The caller must free the
51 returned value. Returns NULL and sets ERRNO on error. */
53 pk_ecdh_default_params (unsigned int qbits)
58 kek_params = xtrymalloc (4);
61 kek_params[0] = 3; /* Number of bytes to follow. */
62 kek_params[1] = 1; /* Version for KDF+AESWRAP. */
64 /* Search for matching KEK parameter. Defaults to the strongest
65 possible choices. Performance is not an issue here, only
67 for (i=0; i < DIM (kek_params_table); i++)
69 if (kek_params_table[i].qbits >= qbits
70 || i+1 == DIM (kek_params_table))
72 kek_params[2] = kek_params_table[i].openpgp_hash_id;
73 kek_params[3] = kek_params_table[i].openpgp_cipher_id;
77 log_assert (i < DIM (kek_params_table));
79 log_printhex ("ECDH KEK params are", kek_params, sizeof(kek_params) );
81 return gcry_mpi_set_opaque (NULL, kek_params, 4 * 8);
85 /* Encrypts/decrypts DATA using a key derived from the ECC shared
86 point SHARED_MPI using the FIPS SP 800-56A compliant method
87 key_derivation+key_wrapping. If IS_ENCRYPT is true the function
88 encrypts; if false, it decrypts. PKEY is the public key and PK_FP
89 the fingerprint of this public key. On success the result is
90 stored at R_RESULT; on failure NULL is stored at R_RESULT and an
91 error code returned. */
93 pk_ecdh_encrypt_with_shared_point (int is_encrypt, gcry_mpi_t shared_mpi,
94 const byte pk_fp[MAX_FINGERPRINT_LEN],
95 gcry_mpi_t data, gcry_mpi_t *pkey,
102 const unsigned char *kek_params;
103 size_t kek_params_size;
106 unsigned char message[256];
111 nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
113 return gpg_error (GPG_ERR_TOO_SHORT);
118 /* Extract x component of the shared point: this is the actual
120 nbytes = (mpi_get_nbits (pkey[1] /* public point */)+7)/8;
121 secret_x = xtrymalloc_secure (nbytes);
123 return gpg_error_from_syserror ();
125 err = gcry_mpi_print (GCRYMPI_FMT_USG, secret_x, nbytes,
126 &nbytes, shared_mpi);
130 log_error ("ECDH ephemeral export of shared point failed: %s\n",
135 /* Expected size of the x component */
136 secret_x_size = (nbits+7)/8;
138 /* Extract X from the result. It must be in the format of:
143 Since it always comes with the prefix, it's larger than X. In
144 old experimental version of libgcrypt, there is a case where it
145 returns X with no prefix of 40, so, nbytes == secret_x_size
147 if (nbytes < secret_x_size)
150 return gpg_error (GPG_ERR_BAD_DATA);
153 /* Remove the prefix. */
155 memmove (secret_x, secret_x+1, secret_x_size);
157 /* Clear the rest of data. */
158 if (nbytes - secret_x_size)
159 memset (secret_x+secret_x_size, 0, nbytes-secret_x_size);
162 log_printhex ("ECDH shared secret X is:", secret_x, secret_x_size );
165 /*** We have now the shared secret bytes in secret_x. ***/
167 /* At this point we are done with PK encryption and the rest of the
168 * function uses symmetric key encryption techniques to protect the
169 * input DATA. The following two sections will simply replace
170 * current secret_x with a value derived from it. This will become
173 if (!gcry_mpi_get_flag (pkey[2], GCRYMPI_FLAG_OPAQUE))
176 return gpg_error (GPG_ERR_BUG);
178 kek_params = gcry_mpi_get_opaque (pkey[2], &nbits);
179 kek_params_size = (nbits+7)/8;
182 log_printhex ("ecdh KDF params:", kek_params, kek_params_size);
184 /* Expect 4 bytes 03 01 hash_alg symm_alg. */
185 if (kek_params_size != 4 || kek_params[0] != 3 || kek_params[1] != 1)
188 return gpg_error (GPG_ERR_BAD_PUBKEY);
191 kdf_hash_algo = kek_params[2];
192 kdf_encr_algo = kek_params[3];
195 log_debug ("ecdh KDF algorithms %s+%s with aeswrap\n",
196 openpgp_md_algo_name (kdf_hash_algo),
197 openpgp_cipher_algo_name (kdf_encr_algo));
199 if (kdf_hash_algo != GCRY_MD_SHA256
200 && kdf_hash_algo != GCRY_MD_SHA384
201 && kdf_hash_algo != GCRY_MD_SHA512)
204 return gpg_error (GPG_ERR_BAD_PUBKEY);
206 if (kdf_encr_algo != CIPHER_ALGO_AES
207 && kdf_encr_algo != CIPHER_ALGO_AES192
208 && kdf_encr_algo != CIPHER_ALGO_AES256)
211 return gpg_error (GPG_ERR_BAD_PUBKEY);
214 /* Build kdf_params. */
219 /* variable-length field 1, curve name OID */
220 err = gpg_mpi_write_nohdr (obuf, pkey[0]);
221 /* fixed-length field 2 */
222 iobuf_put (obuf, PUBKEY_ALGO_ECDH);
223 /* variable-length field 3, KDF params */
224 err = (err ? err : gpg_mpi_write_nohdr (obuf, pkey[2]));
225 /* fixed-length field 4 */
226 iobuf_write (obuf, "Anonymous Sender ", 20);
227 /* fixed-length field 5, recipient fp */
228 iobuf_write (obuf, pk_fp, 20);
230 message_size = iobuf_temp_to_buffer (obuf, message, sizeof message);
239 log_printhex ("ecdh KDF message params are:", message, message_size);
242 /* Derive a KEK (key wrapping key) using MESSAGE and SECRET_X. */
247 err = gcry_md_open (&h, kdf_hash_algo, 0);
250 log_error ("gcry_md_open failed for kdf_hash_algo %d: %s",
251 kdf_hash_algo, gpg_strerror (err));
255 gcry_md_write(h, "\x00\x00\x00\x01", 4); /* counter = 1 */
256 gcry_md_write(h, secret_x, secret_x_size); /* x of the point X */
257 gcry_md_write(h, message, message_size); /* KDF parameters */
261 log_assert( gcry_md_get_algo_dlen (kdf_hash_algo) >= 32 );
263 memcpy (secret_x, gcry_md_read (h, kdf_hash_algo),
264 gcry_md_get_algo_dlen (kdf_hash_algo));
267 old_size = secret_x_size;
268 log_assert( old_size >= gcry_cipher_get_algo_keylen( kdf_encr_algo ) );
269 secret_x_size = gcry_cipher_get_algo_keylen( kdf_encr_algo );
270 log_assert( secret_x_size <= gcry_md_get_algo_dlen (kdf_hash_algo) );
272 /* We could have allocated more, so clean the tail before returning. */
273 memset (secret_x+secret_x_size, 0, old_size - secret_x_size);
275 log_printhex ("ecdh KEK is:", secret_x, secret_x_size );
278 /* And, finally, aeswrap with key secret_x. */
288 err = gcry_cipher_open (&hd, kdf_encr_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
291 log_error ("ecdh failed to initialize AESWRAP: %s\n",
297 err = gcry_cipher_setkey (hd, secret_x, secret_x_size);
302 gcry_cipher_close (hd);
303 log_error ("ecdh failed in gcry_cipher_setkey: %s\n",
308 data_buf_size = (gcry_mpi_get_nbits(data)+7)/8;
309 if ((data_buf_size & 7) != (is_encrypt ? 0 : 1))
311 log_error ("can't use a shared secret of %d bytes for ecdh\n",
313 return gpg_error (GPG_ERR_BAD_DATA);
316 data_buf = xtrymalloc_secure( 1 + 2*data_buf_size + 8);
319 err = gpg_error_from_syserror ();
320 gcry_cipher_close (hd);
326 byte *in = data_buf+1+data_buf_size+8;
328 /* Write data MPI into the end of data_buf. data_buf is size
330 err = gcry_mpi_print (GCRYMPI_FMT_USG, in,
331 data_buf_size, &nbytes, data/*in*/);
334 log_error ("ecdh failed to export DEK: %s\n", gpg_strerror (err));
335 gcry_cipher_close (hd);
341 log_printhex ("ecdh encrypting :", in, data_buf_size );
343 err = gcry_cipher_encrypt (hd, data_buf+1, data_buf_size+8,
345 memset (in, 0, data_buf_size);
346 gcry_cipher_close (hd);
349 log_error ("ecdh failed in gcry_cipher_encrypt: %s\n",
354 data_buf[0] = data_buf_size+8;
357 log_printhex ("ecdh encrypted to:", data_buf+1, data_buf[0] );
359 result = gcry_mpi_set_opaque (NULL, data_buf, 8 * (1+data_buf[0]));
362 err = gpg_error_from_syserror ();
364 log_error ("ecdh failed to create an MPI: %s\n",
376 p = gcry_mpi_get_opaque (data, &nbits);
377 nbytes = (nbits+7)/8;
378 if (!p || nbytes > data_buf_size || !nbytes)
381 return gpg_error (GPG_ERR_BAD_MPI);
383 memcpy (data_buf, p, nbytes);
384 if (data_buf[0] != nbytes-1)
386 log_error ("ecdh inconsistent size\n");
388 return gpg_error (GPG_ERR_BAD_MPI);
390 in = data_buf+data_buf_size;
391 data_buf_size = data_buf[0];
394 log_printhex ("ecdh decrypting :", data_buf+1, data_buf_size);
396 err = gcry_cipher_decrypt (hd, in, data_buf_size, data_buf+1,
398 gcry_cipher_close (hd);
401 log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",
410 log_printhex ("ecdh decrypted to :", in, data_buf_size);
412 /* Padding is removed later. */
413 /* if (in[data_buf_size-1] > 8 ) */
415 /* log_error ("ecdh failed at decryption: invalid padding." */
416 /* " 0x%02x > 8\n", in[data_buf_size-1] ); */
417 /* return gpg_error (GPG_ERR_BAD_KEY); */
420 err = gcry_mpi_scan (&result, GCRYMPI_FMT_USG, in, data_buf_size, NULL);
424 log_error ("ecdh failed to create a plain text MPI: %s\n",
438 gen_k (unsigned nbits)
442 k = gcry_mpi_snew (nbits);
444 log_debug ("choosing a random k of %u bits\n", nbits);
446 gcry_mpi_randomize (k, nbits-1, GCRY_STRONG_RANDOM);
450 unsigned char *buffer;
451 if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, k))
453 log_debug ("ephemeral scalar MPI #0: %s\n", buffer);
461 /* Generate an ephemeral key for the public ECDH key in PKEY. On
462 success the generated key is stored at R_K; on failure NULL is
463 stored at R_K and an error code returned. */
465 pk_ecdh_generate_ephemeral_key (gcry_mpi_t *pkey, gcry_mpi_t *r_k)
472 nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
474 return gpg_error (GPG_ERR_TOO_SHORT);
485 /* Perform ECDH decryption. */
487 pk_ecdh_decrypt (gcry_mpi_t * result, const byte sk_fp[MAX_FINGERPRINT_LEN],
488 gcry_mpi_t data, gcry_mpi_t shared, gcry_mpi_t * skey)
491 return gpg_error (GPG_ERR_BAD_MPI);
492 return pk_ecdh_encrypt_with_shared_point (0 /*=decryption*/, shared,
493 sk_fp, data/*encr data as an MPI*/,