2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/crypto_rsa.c
23 * @brief public key cryptography (RSA) with libgcrypt
24 * @author Christian Grothoff
26 * Note that the code locks often needlessly on the gcrypt-locking api.
27 * One would think that simple MPI operations should not require locking
28 * (since only global operations on the random pool must be locked,
29 * strictly speaking). But libgcrypt does sometimes require locking in
30 * unexpected places, so the safe solution is to always lock even if it
31 * is not required. The performance impact is minimal anyway.
36 #include "gnunet_common.h"
37 #include "gnunet_crypto_lib.h"
38 #include "gnunet_disk_lib.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
47 * The private information of an RSA key pair.
48 * NOTE: this must match the definition in crypto_ksk.c
50 struct GNUNET_CRYPTO_RsaPrivateKey
57 * GNUnet mandates a certain format for the encoding
58 * of private RSA key information that is provided
59 * by the RSA implementations. This format is used
60 * to serialize a private RSA key (typically when
61 * writing it to disk).
63 struct RsaPrivateKeyBinaryEncoded
66 * Total size of the structure, in bytes, in big-endian!
68 uint16_t len GNUNET_PACKED;
69 uint16_t sizen GNUNET_PACKED; /* in big-endian! */
70 uint16_t sizee GNUNET_PACKED; /* in big-endian! */
71 uint16_t sized GNUNET_PACKED; /* in big-endian! */
72 uint16_t sizep GNUNET_PACKED; /* in big-endian! */
73 uint16_t sizeq GNUNET_PACKED; /* in big-endian! */
74 uint16_t sizedmp1 GNUNET_PACKED; /* in big-endian! */
75 uint16_t sizedmq1 GNUNET_PACKED; /* in big-endian! */
76 /* followed by the actual values */
80 #define HOSTKEY_LEN 2048
82 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
86 * Log an error message at log-level 'level' that indicates
87 * a failure of the command 'cmd' with the message given
88 * by gcry_strerror(rc).
90 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
93 * If target != size, move target bytes to the
94 * end of the size-sized buffer and zero out the
95 * first target-size bytes.
98 adjust (unsigned char *buf, size_t size, size_t target)
102 memmove (&buf[target - size], buf, size);
103 memset (buf, 0, target - size);
108 * This HostKey implementation uses RSA.
110 struct GNUNET_CRYPTO_RsaPrivateKey *
111 GNUNET_CRYPTO_rsa_key_create ()
113 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
115 gcry_sexp_t s_keyparam;
118 gcry_sexp_build (&s_keyparam, NULL,
119 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
121 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
122 gcry_sexp_release (s_keyparam);
124 GNUNET_assert (0 == gcry_pk_testkey (s_key));
126 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
132 * Free memory occupied by hostkey
135 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
137 gcry_sexp_release (hostkey->sexp);
138 GNUNET_free (hostkey);
142 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
145 gcry_sexp_t list, l2;
149 list = gcry_sexp_find_token (sexp, topname, 0);
154 l2 = gcry_sexp_cadr (list);
155 gcry_sexp_release (list);
163 for (s = elems; *s; s++, idx++)
165 l2 = gcry_sexp_find_token (list, s, 1);
168 for (i = 0; i < idx; i++)
170 gcry_free (array[i]);
173 gcry_sexp_release (list);
174 return 3; /* required parameter not found */
176 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
177 gcry_sexp_release (l2);
180 for (i = 0; i < idx; i++)
182 gcry_free (array[i]);
185 gcry_sexp_release (list);
186 return 4; /* required parameter is invalid */
189 gcry_sexp_release (list);
194 * Extract the public key of the host.
195 * @param priv the private key
196 * @param pub where to write the public key
199 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
201 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
208 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
210 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
212 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
213 GNUNET_assert (0 == rc);
215 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
216 sizeof (pub->padding));
217 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
219 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
221 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
223 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
224 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
226 gcry_mpi_print (GCRYMPI_FMT_USG,
228 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
230 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
231 GNUNET_CRYPTO_RSA_KEY_LENGTH -
232 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
233 gcry_mpi_release (skey[0]);
234 gcry_mpi_release (skey[1]);
239 * Internal: publicKey => RSA-Key.
241 * Note that the return type is not actually a private
242 * key but rather an sexpression for the public key!
244 static struct GNUNET_CRYPTO_RsaPrivateKey *
245 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
248 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
256 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
257 (ntohs (publicKey->len) !=
258 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
259 sizeof (publicKey->padding)))
264 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
265 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
268 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
271 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
272 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
273 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
277 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
278 gcry_mpi_release (n);
281 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
283 gcry_mpi_release (n);
284 gcry_mpi_release (e);
287 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
290 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
297 * Encode the private key in a format suitable for
298 * storing it into a file.
299 * @returns encoding of the private key.
300 * The first 4 bytes give the size of the array, as usual.
302 static struct RsaPrivateKeyBinaryEncoded *
303 rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
305 struct RsaPrivateKeyBinaryEncoded *retval;
314 if (gcry_pk_testkey (hostkey->sexp))
321 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
322 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
324 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
326 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
328 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
330 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
332 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
333 GNUNET_assert (0 == rc);
334 size = sizeof (struct RsaPrivateKeyBinaryEncoded);
335 for (i = 0; i < 6; i++)
340 gcry_mpi_aprint (GCRYMPI_FMT_USG,
341 (unsigned char **) &pbu[i], &sizes[i],
351 GNUNET_assert (size < 65536);
352 retval = GNUNET_malloc (size);
353 retval->len = htons (size);
355 retval->sizen = htons (sizes[0]);
356 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
358 retval->sizee = htons (sizes[1]);
359 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
361 retval->sized = htons (sizes[2]);
362 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
365 retval->sizep = htons (sizes[4]);
366 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
368 retval->sizeq = htons (sizes[3]);
369 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
371 retval->sizedmp1 = htons (0);
372 retval->sizedmq1 = htons (0);
373 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
374 for (i = 0; i < 6; i++)
377 gcry_mpi_release (pkv[i]);
385 * Decode the private key from the file-format back
386 * to the "normal", internal format.
388 * @param buf the buffer where the private key data is stored
389 * @param len the length of the data in 'buffer'
391 struct GNUNET_CRYPTO_RsaPrivateKey *
392 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
394 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
395 const struct RsaPrivateKeyBinaryEncoded *encoding =
396 (const struct RsaPrivateKeyBinaryEncoded *) buf;
398 gcry_mpi_t n, e, d, p, q, u;
404 enc_len = ntohs (encoding->len);
409 size = ntohs (encoding->sizen);
410 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
411 &((const unsigned char *) (&encoding[1]))[pos], size,
413 pos += ntohs (encoding->sizen);
416 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
419 size = ntohs (encoding->sizee);
420 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
421 &((const unsigned char *) (&encoding[1]))[pos], size,
423 pos += ntohs (encoding->sizee);
426 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
427 gcry_mpi_release (n);
430 size = ntohs (encoding->sized);
431 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
432 &((const unsigned char *) (&encoding[1]))[pos], size,
434 pos += ntohs (encoding->sized);
437 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
438 gcry_mpi_release (n);
439 gcry_mpi_release (e);
443 size = ntohs (encoding->sizep);
446 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
447 &((const unsigned char *) (&encoding[1]))[pos], size,
449 pos += ntohs (encoding->sizep);
452 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
453 gcry_mpi_release (n);
454 gcry_mpi_release (e);
455 gcry_mpi_release (d);
461 size = ntohs (encoding->sizeq);
464 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
465 &((const unsigned char *) (&encoding[1]))[pos], size,
467 pos += ntohs (encoding->sizeq);
470 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
471 gcry_mpi_release (n);
472 gcry_mpi_release (e);
473 gcry_mpi_release (d);
475 gcry_mpi_release (q);
481 pos += ntohs (encoding->sizedmp1);
482 pos += ntohs (encoding->sizedmq1);
484 ntohs (encoding->len) - sizeof (struct RsaPrivateKeyBinaryEncoded) - pos;
487 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
488 &((const unsigned char *) (&encoding[1]))[pos], size,
492 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
493 gcry_mpi_release (n);
494 gcry_mpi_release (e);
495 gcry_mpi_release (d);
497 gcry_mpi_release (p);
499 gcry_mpi_release (q);
506 if ((p != NULL) && (q != NULL) && (u != NULL))
508 rc = gcry_sexp_build (&res, &size, /* erroff */
509 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
514 if ((p != NULL) && (q != NULL))
516 rc = gcry_sexp_build (&res, &size, /* erroff */
517 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
522 rc = gcry_sexp_build (&res, &size, /* erroff */
523 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
526 gcry_mpi_release (n);
527 gcry_mpi_release (e);
528 gcry_mpi_release (d);
530 gcry_mpi_release (p);
532 gcry_mpi_release (q);
534 gcry_mpi_release (u);
537 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
539 if (gcry_pk_testkey (res))
541 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
545 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
552 * Create a new private key by reading it from a file. If the
553 * files does not exist, create a new key and write it to the
554 * file. Caller must free return value. Note that this function
555 * can not guarantee that another process might not be trying
556 * the same operation on the same file at the same time.
557 * If the contents of the file
558 * are invalid the old file is deleted and a fresh key is
561 * @return new private key, NULL on error (for example,
564 struct GNUNET_CRYPTO_RsaPrivateKey *
565 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
567 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
568 struct RsaPrivateKeyBinaryEncoded *enc;
570 struct GNUNET_DISK_FileHandle *fd;
574 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
575 struct GNUNET_PeerIdentity pid;
577 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
579 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
581 fd = GNUNET_DISK_file_open (filename,
582 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
583 | GNUNET_DISK_OPEN_FAILIFEXISTS,
584 GNUNET_DISK_PERM_USER_READ |
585 GNUNET_DISK_PERM_USER_WRITE);
590 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
592 /* must exist but not be accessible, fail for good! */
593 if (0 != ACCESS (filename, R_OK))
594 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
596 GNUNET_break (0); /* what is going on!? */
601 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
607 GNUNET_DISK_file_lock (fd, 0,
608 sizeof (struct RsaPrivateKeyBinaryEncoded),
615 LOG (GNUNET_ERROR_TYPE_ERROR,
616 _("Could not aquire lock on file `%s': %s...\n"), filename,
620 LOG (GNUNET_ERROR_TYPE_INFO,
621 _("Creating a new private key. This may take a while.\n"));
622 ret = GNUNET_CRYPTO_rsa_key_create ();
623 GNUNET_assert (ret != NULL);
624 enc = rsa_encode_key (ret);
625 GNUNET_assert (enc != NULL);
626 GNUNET_assert (ntohs (enc->len) ==
627 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
630 GNUNET_DISK_file_sync (fd);
632 GNUNET_DISK_file_unlock (fd, 0,
633 sizeof (struct RsaPrivateKeyBinaryEncoded)))
634 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
635 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
636 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
637 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
638 LOG (GNUNET_ERROR_TYPE_INFO,
639 _("I am host `%s'. Stored new private key in `%s'.\n"),
640 GNUNET_i2s (&pid), filename);
643 /* hostkey file exists already, read it! */
644 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
645 GNUNET_DISK_PERM_NONE);
648 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
655 GNUNET_DISK_file_lock (fd, 0,
656 sizeof (struct RsaPrivateKeyBinaryEncoded),
662 LOG (GNUNET_ERROR_TYPE_ERROR,
663 _("Could not aquire lock on file `%s': %s...\n"), filename,
665 LOG (GNUNET_ERROR_TYPE_ERROR,
667 ("This may be ok if someone is currently generating a hostkey.\n"));
672 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
674 /* eh, what!? File we opened is now gone!? */
675 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
677 GNUNET_DISK_file_unlock (fd, 0,
678 sizeof (struct RsaPrivateKeyBinaryEncoded)))
679 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
680 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
684 if (GNUNET_YES != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES))
686 if (fs < sizeof (struct RsaPrivateKeyBinaryEncoded))
688 /* maybe we got the read lock before the hostkey generating
689 * process had a chance to get the write lock; give it up! */
691 GNUNET_DISK_file_unlock (fd, 0,
692 sizeof (struct RsaPrivateKeyBinaryEncoded)))
693 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
696 LOG (GNUNET_ERROR_TYPE_ERROR,
698 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
699 filename, (unsigned int) fs,
700 (unsigned int) sizeof (struct RsaPrivateKeyBinaryEncoded));
701 LOG (GNUNET_ERROR_TYPE_ERROR,
703 ("This may be ok if someone is currently generating a hostkey.\n"));
705 sleep (2); /* wait a bit longer! */
710 enc = GNUNET_malloc (fs);
711 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
712 len = ntohs (enc->len);
715 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
717 LOG (GNUNET_ERROR_TYPE_ERROR,
718 _("File `%s' does not contain a valid private key. Deleting it.\n"),
720 if (0 != UNLINK (filename))
722 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
727 GNUNET_DISK_file_unlock (fd, 0,
728 sizeof (struct RsaPrivateKeyBinaryEncoded)))
729 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
730 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
733 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
734 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
735 LOG (GNUNET_ERROR_TYPE_INFO,
736 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
744 * Encrypt a block with the public key of another host that uses the
747 * @param block the block to encrypt
748 * @param size the size of block
749 * @param publicKey the encoded public key used to encrypt
750 * @param target where to store the encrypted block
751 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
754 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
755 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
757 struct GNUNET_CRYPTO_RsaEncryptedData *target)
761 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
767 GNUNET_assert (size <= sizeof (GNUNET_HashCode));
768 pubkey = public2PrivateKey (publicKey);
770 return GNUNET_SYSERR;
773 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
775 gcry_sexp_build (&data, &erroff,
776 "(data (flags pkcs1)(value %m))", val));
777 gcry_mpi_release (val);
778 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
779 gcry_sexp_release (data);
780 GNUNET_CRYPTO_rsa_key_free (pubkey);
782 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
783 gcry_sexp_release (result);
784 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
786 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
787 isize, &isize, rval));
788 gcry_mpi_release (rval);
789 adjust (&target->encoding[0], isize,
790 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
795 * Decrypt a given block with the hostkey.
797 * @param key the key with which to decrypt this block
798 * @param block the data to decrypt, encoded as returned by encrypt
799 * @param result pointer to a location where the result can be stored
800 * @param max the maximum number of bits to store for the result, if
801 * the decrypted block is bigger, an error is returned
802 * @return the size of the decrypted block, -1 on error
805 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
806 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
807 void *result, size_t max)
809 gcry_sexp_t resultsexp;
818 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
820 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
822 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
825 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
827 gcry_mpi_release (val);
828 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
829 gcry_sexp_release (data);
830 /* resultsexp has format "(value %m)" */
831 GNUNET_assert (NULL !=
832 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
833 gcry_sexp_release (resultsexp);
834 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
835 size = max + HOSTKEY_LEN / 8;
836 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
837 gcry_mpi_release (val);
839 endp += (size - max);
841 memcpy (result, endp, size);
848 * Sign a given block.
850 * @param key private key to use for the signing
851 * @param purpose what to sign (size, purpose)
852 * @param sig where to write the signature
853 * @return GNUNET_SYSERR on error, GNUNET_OK on success
856 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
857 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
858 struct GNUNET_CRYPTO_RsaSignature *sig)
868 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
869 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
870 bufSize = strlen (FORMATSTRING) + 1;
871 buff = GNUNET_malloc (bufSize);
872 memcpy (buff, FORMATSTRING, bufSize);
876 ("0123456789012345678901234567890123456789012345678901234567890123))")
877 - 1], &hc, sizeof (GNUNET_HashCode));
878 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
880 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
881 gcry_sexp_release (data);
882 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
883 gcry_sexp_release (result);
884 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
886 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
888 gcry_mpi_release (rval);
889 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
897 * @param purpose what is the purpose that the signature should have?
898 * @param validate block to validate (size, purpose, data)
899 * @param sig signature that is being validated
900 * @param publicKey public key of the signer
901 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
904 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
905 const struct GNUNET_CRYPTO_RsaSignaturePurpose
907 const struct GNUNET_CRYPTO_RsaSignature *sig,
908 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
915 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
922 if (purpose != ntohl (validate->purpose))
923 return GNUNET_SYSERR; /* purpose mismatch */
924 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
925 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
927 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
928 (const unsigned char *) sig, size, &size));
930 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
932 gcry_mpi_release (val);
933 bufSize = strlen (FORMATSTRING) + 1;
934 buff = GNUNET_malloc (bufSize);
935 memcpy (buff, FORMATSTRING, bufSize);
937 [strlen (FORMATSTRING) -
939 ("0123456789012345678901234567890123456789012345678901234567890123))")],
940 &hc, sizeof (GNUNET_HashCode));
941 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
943 hostkey = public2PrivateKey (publicKey);
946 gcry_sexp_release (data);
947 gcry_sexp_release (sigdata);
948 return GNUNET_SYSERR;
950 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
951 GNUNET_CRYPTO_rsa_key_free (hostkey);
952 gcry_sexp_release (data);
953 gcry_sexp_release (sigdata);
956 LOG (GNUNET_ERROR_TYPE_WARNING,
957 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
958 __LINE__, gcry_strerror (rc));
959 return GNUNET_SYSERR;
965 /* end of crypto_rsa.c */