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
56 GNUNET_NETWORK_STRUCT_BEGIN
59 * GNUnet mandates a certain format for the encoding
60 * of private RSA key information that is provided
61 * by the RSA implementations. This format is used
62 * to serialize a private RSA key (typically when
63 * writing it to disk).
65 struct RsaPrivateKeyBinaryEncoded
68 * Total size of the structure, in bytes, in big-endian!
70 uint16_t len GNUNET_PACKED;
71 uint16_t sizen GNUNET_PACKED; /* in big-endian! */
72 uint16_t sizee GNUNET_PACKED; /* in big-endian! */
73 uint16_t sized GNUNET_PACKED; /* in big-endian! */
74 uint16_t sizep GNUNET_PACKED; /* in big-endian! */
75 uint16_t sizeq GNUNET_PACKED; /* in big-endian! */
76 uint16_t sizedmp1 GNUNET_PACKED; /* in big-endian! */
77 uint16_t sizedmq1 GNUNET_PACKED; /* in big-endian! */
78 /* followed by the actual values */
80 GNUNET_NETWORK_STRUCT_END
82 #define HOSTKEY_LEN 2048
84 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
88 * Log an error message at log-level 'level' that indicates
89 * a failure of the command 'cmd' with the message given
90 * by gcry_strerror(rc).
92 #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);
95 * If target != size, move target bytes to the
96 * end of the size-sized buffer and zero out the
97 * first target-size bytes.
100 adjust (unsigned char *buf, size_t size, size_t target)
104 memmove (&buf[target - size], buf, size);
105 memset (buf, 0, target - size);
110 * This HostKey implementation uses RSA.
112 struct GNUNET_CRYPTO_RsaPrivateKey *
113 GNUNET_CRYPTO_rsa_key_create ()
115 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
117 gcry_sexp_t s_keyparam;
120 gcry_sexp_build (&s_keyparam, NULL,
121 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
123 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
124 gcry_sexp_release (s_keyparam);
126 GNUNET_assert (0 == gcry_pk_testkey (s_key));
128 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
134 * Free memory occupied by hostkey
137 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
139 gcry_sexp_release (hostkey->sexp);
140 GNUNET_free (hostkey);
144 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
147 gcry_sexp_t list, l2;
151 list = gcry_sexp_find_token (sexp, topname, 0);
156 l2 = gcry_sexp_cadr (list);
157 gcry_sexp_release (list);
165 for (s = elems; *s; s++, idx++)
167 l2 = gcry_sexp_find_token (list, s, 1);
170 for (i = 0; i < idx; i++)
172 gcry_free (array[i]);
175 gcry_sexp_release (list);
176 return 3; /* required parameter not found */
178 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
179 gcry_sexp_release (l2);
182 for (i = 0; i < idx; i++)
184 gcry_free (array[i]);
187 gcry_sexp_release (list);
188 return 4; /* required parameter is invalid */
191 gcry_sexp_release (list);
196 * Extract the public key of the host.
197 * @param priv the private key
198 * @param pub where to write the public key
201 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
203 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
210 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
212 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
214 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
215 GNUNET_assert (0 == rc);
217 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
218 sizeof (pub->padding));
219 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
221 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
223 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
225 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
226 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
228 gcry_mpi_print (GCRYMPI_FMT_USG,
230 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
232 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
233 GNUNET_CRYPTO_RSA_KEY_LENGTH -
234 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
235 gcry_mpi_release (skey[0]);
236 gcry_mpi_release (skey[1]);
241 * Internal: publicKey => RSA-Key.
243 * Note that the return type is not actually a private
244 * key but rather an sexpression for the public key!
246 static struct GNUNET_CRYPTO_RsaPrivateKey *
247 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
250 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
258 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
259 (ntohs (publicKey->len) !=
260 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
261 sizeof (publicKey->padding)))
266 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
267 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
270 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
273 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
274 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
275 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
279 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
280 gcry_mpi_release (n);
283 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
285 gcry_mpi_release (n);
286 gcry_mpi_release (e);
289 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
292 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
299 * Encode the private key in a format suitable for
300 * storing it into a file.
301 * @returns encoding of the private key.
302 * The first 4 bytes give the size of the array, as usual.
304 static struct RsaPrivateKeyBinaryEncoded *
305 rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
307 struct RsaPrivateKeyBinaryEncoded *retval;
316 if (gcry_pk_testkey (hostkey->sexp))
323 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
324 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
326 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
328 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
330 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
332 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
334 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
335 GNUNET_assert (0 == rc);
336 size = sizeof (struct RsaPrivateKeyBinaryEncoded);
337 for (i = 0; i < 6; i++)
342 gcry_mpi_aprint (GCRYMPI_FMT_USG,
343 (unsigned char **) &pbu[i], &sizes[i],
353 GNUNET_assert (size < 65536);
354 retval = GNUNET_malloc (size);
355 retval->len = htons (size);
357 retval->sizen = htons (sizes[0]);
358 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
360 retval->sizee = htons (sizes[1]);
361 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
363 retval->sized = htons (sizes[2]);
364 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
367 retval->sizep = htons (sizes[4]);
368 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
370 retval->sizeq = htons (sizes[3]);
371 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
373 retval->sizedmp1 = htons (0);
374 retval->sizedmq1 = htons (0);
375 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
376 for (i = 0; i < 6; i++)
379 gcry_mpi_release (pkv[i]);
387 * Decode the private key from the file-format back
388 * to the "normal", internal format.
390 * @param buf the buffer where the private key data is stored
391 * @param len the length of the data in 'buffer'
393 struct GNUNET_CRYPTO_RsaPrivateKey *
394 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
396 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
397 const struct RsaPrivateKeyBinaryEncoded *encoding =
398 (const struct RsaPrivateKeyBinaryEncoded *) buf;
400 gcry_mpi_t n, e, d, p, q, u;
406 enc_len = ntohs (encoding->len);
411 size = ntohs (encoding->sizen);
412 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
413 &((const unsigned char *) (&encoding[1]))[pos], size,
415 pos += ntohs (encoding->sizen);
418 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
421 size = ntohs (encoding->sizee);
422 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
423 &((const unsigned char *) (&encoding[1]))[pos], size,
425 pos += ntohs (encoding->sizee);
428 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
429 gcry_mpi_release (n);
432 size = ntohs (encoding->sized);
433 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
434 &((const unsigned char *) (&encoding[1]))[pos], size,
436 pos += ntohs (encoding->sized);
439 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
440 gcry_mpi_release (n);
441 gcry_mpi_release (e);
445 size = ntohs (encoding->sizep);
448 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
449 &((const unsigned char *) (&encoding[1]))[pos], size,
451 pos += ntohs (encoding->sizep);
454 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
455 gcry_mpi_release (n);
456 gcry_mpi_release (e);
457 gcry_mpi_release (d);
463 size = ntohs (encoding->sizeq);
466 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
467 &((const unsigned char *) (&encoding[1]))[pos], size,
469 pos += ntohs (encoding->sizeq);
472 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
473 gcry_mpi_release (n);
474 gcry_mpi_release (e);
475 gcry_mpi_release (d);
477 gcry_mpi_release (q);
483 pos += ntohs (encoding->sizedmp1);
484 pos += ntohs (encoding->sizedmq1);
486 ntohs (encoding->len) - sizeof (struct RsaPrivateKeyBinaryEncoded) - pos;
489 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
490 &((const unsigned char *) (&encoding[1]))[pos], size,
494 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
495 gcry_mpi_release (n);
496 gcry_mpi_release (e);
497 gcry_mpi_release (d);
499 gcry_mpi_release (p);
501 gcry_mpi_release (q);
508 if ((p != NULL) && (q != NULL) && (u != NULL))
510 rc = gcry_sexp_build (&res, &size, /* erroff */
511 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
516 if ((p != NULL) && (q != NULL))
518 rc = gcry_sexp_build (&res, &size, /* erroff */
519 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
524 rc = gcry_sexp_build (&res, &size, /* erroff */
525 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
528 gcry_mpi_release (n);
529 gcry_mpi_release (e);
530 gcry_mpi_release (d);
532 gcry_mpi_release (p);
534 gcry_mpi_release (q);
536 gcry_mpi_release (u);
539 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
541 if (gcry_pk_testkey (res))
543 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
547 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
554 * Create a new private key by reading it from a file. If the
555 * files does not exist, create a new key and write it to the
556 * file. Caller must free return value. Note that this function
557 * can not guarantee that another process might not be trying
558 * the same operation on the same file at the same time.
559 * If the contents of the file
560 * are invalid the old file is deleted and a fresh key is
563 * @return new private key, NULL on error (for example,
566 struct GNUNET_CRYPTO_RsaPrivateKey *
567 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
569 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
570 struct RsaPrivateKeyBinaryEncoded *enc;
572 struct GNUNET_DISK_FileHandle *fd;
576 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
577 struct GNUNET_PeerIdentity pid;
579 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
581 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
583 fd = GNUNET_DISK_file_open (filename,
584 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
585 | GNUNET_DISK_OPEN_FAILIFEXISTS,
586 GNUNET_DISK_PERM_USER_READ |
587 GNUNET_DISK_PERM_USER_WRITE);
592 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
594 /* must exist but not be accessible, fail for good! */
595 if (0 != ACCESS (filename, R_OK))
596 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
598 GNUNET_break (0); /* what is going on!? */
603 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
609 GNUNET_DISK_file_lock (fd, 0,
610 sizeof (struct RsaPrivateKeyBinaryEncoded),
617 LOG (GNUNET_ERROR_TYPE_ERROR,
618 _("Could not aquire lock on file `%s': %s...\n"), filename,
622 LOG (GNUNET_ERROR_TYPE_INFO,
623 _("Creating a new private key. This may take a while.\n"));
624 ret = GNUNET_CRYPTO_rsa_key_create ();
625 GNUNET_assert (ret != NULL);
626 enc = rsa_encode_key (ret);
627 GNUNET_assert (enc != NULL);
628 GNUNET_assert (ntohs (enc->len) ==
629 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
632 GNUNET_DISK_file_sync (fd);
634 GNUNET_DISK_file_unlock (fd, 0,
635 sizeof (struct RsaPrivateKeyBinaryEncoded)))
636 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
637 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
638 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
639 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
640 LOG (GNUNET_ERROR_TYPE_INFO,
641 _("I am host `%s'. Stored new private key in `%s'.\n"),
642 GNUNET_i2s (&pid), filename);
645 /* hostkey file exists already, read it! */
646 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
647 GNUNET_DISK_PERM_NONE);
650 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
657 GNUNET_DISK_file_lock (fd, 0,
658 sizeof (struct RsaPrivateKeyBinaryEncoded),
664 LOG (GNUNET_ERROR_TYPE_ERROR,
665 _("Could not aquire lock on file `%s': %s...\n"), filename,
667 LOG (GNUNET_ERROR_TYPE_ERROR,
669 ("This may be ok if someone is currently generating a hostkey.\n"));
674 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
676 /* eh, what!? File we opened is now gone!? */
677 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
679 GNUNET_DISK_file_unlock (fd, 0,
680 sizeof (struct RsaPrivateKeyBinaryEncoded)))
681 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
682 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
686 if (GNUNET_YES != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES))
688 if (fs < sizeof (struct RsaPrivateKeyBinaryEncoded))
690 /* maybe we got the read lock before the hostkey generating
691 * process had a chance to get the write lock; give it up! */
693 GNUNET_DISK_file_unlock (fd, 0,
694 sizeof (struct RsaPrivateKeyBinaryEncoded)))
695 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
698 LOG (GNUNET_ERROR_TYPE_ERROR,
700 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
701 filename, (unsigned int) fs,
702 (unsigned int) sizeof (struct RsaPrivateKeyBinaryEncoded));
703 LOG (GNUNET_ERROR_TYPE_ERROR,
705 ("This may be ok if someone is currently generating a hostkey.\n"));
707 sleep (2); /* wait a bit longer! */
712 enc = GNUNET_malloc (fs);
713 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
714 len = ntohs (enc->len);
717 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
719 LOG (GNUNET_ERROR_TYPE_ERROR,
720 _("File `%s' does not contain a valid private key. Deleting it.\n"),
722 if (0 != UNLINK (filename))
724 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
729 GNUNET_DISK_file_unlock (fd, 0,
730 sizeof (struct RsaPrivateKeyBinaryEncoded)))
731 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
732 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
735 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
736 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
737 LOG (GNUNET_ERROR_TYPE_INFO,
738 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
746 * Encrypt a block with the public key of another host that uses the
749 * @param block the block to encrypt
750 * @param size the size of block
751 * @param publicKey the encoded public key used to encrypt
752 * @param target where to store the encrypted block
753 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
756 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
757 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
759 struct GNUNET_CRYPTO_RsaEncryptedData *target)
763 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
769 GNUNET_assert (size <= sizeof (GNUNET_HashCode));
770 pubkey = public2PrivateKey (publicKey);
772 return GNUNET_SYSERR;
775 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
777 gcry_sexp_build (&data, &erroff,
778 "(data (flags pkcs1)(value %m))", val));
779 gcry_mpi_release (val);
780 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
781 gcry_sexp_release (data);
782 GNUNET_CRYPTO_rsa_key_free (pubkey);
784 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
785 gcry_sexp_release (result);
786 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
788 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
789 isize, &isize, rval));
790 gcry_mpi_release (rval);
791 adjust (&target->encoding[0], isize,
792 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
797 * Decrypt a given block with the hostkey.
799 * @param key the key with which to decrypt this block
800 * @param block the data to decrypt, encoded as returned by encrypt
801 * @param result pointer to a location where the result can be stored
802 * @param max the maximum number of bits to store for the result, if
803 * the decrypted block is bigger, an error is returned
804 * @return the size of the decrypted block, -1 on error
807 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
808 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
809 void *result, size_t max)
811 gcry_sexp_t resultsexp;
820 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
822 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
824 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
827 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
829 gcry_mpi_release (val);
830 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
831 gcry_sexp_release (data);
832 /* resultsexp has format "(value %m)" */
833 GNUNET_assert (NULL !=
834 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
835 gcry_sexp_release (resultsexp);
836 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
837 size = max + HOSTKEY_LEN / 8;
838 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
839 gcry_mpi_release (val);
841 endp += (size - max);
843 memcpy (result, endp, size);
850 * Sign a given block.
852 * @param key private key to use for the signing
853 * @param purpose what to sign (size, purpose)
854 * @param sig where to write the signature
855 * @return GNUNET_SYSERR on error, GNUNET_OK on success
858 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
859 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
860 struct GNUNET_CRYPTO_RsaSignature *sig)
870 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
871 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
872 bufSize = strlen (FORMATSTRING) + 1;
873 buff = GNUNET_malloc (bufSize);
874 memcpy (buff, FORMATSTRING, bufSize);
878 ("0123456789012345678901234567890123456789012345678901234567890123))")
879 - 1], &hc, sizeof (GNUNET_HashCode));
880 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
882 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
883 gcry_sexp_release (data);
884 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
885 gcry_sexp_release (result);
886 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
888 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
890 gcry_mpi_release (rval);
891 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
899 * @param purpose what is the purpose that the signature should have?
900 * @param validate block to validate (size, purpose, data)
901 * @param sig signature that is being validated
902 * @param publicKey public key of the signer
903 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
906 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
907 const struct GNUNET_CRYPTO_RsaSignaturePurpose
909 const struct GNUNET_CRYPTO_RsaSignature *sig,
910 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
917 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
924 if (purpose != ntohl (validate->purpose))
925 return GNUNET_SYSERR; /* purpose mismatch */
926 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
927 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
929 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
930 (const unsigned char *) sig, size, &size));
932 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
934 gcry_mpi_release (val);
935 bufSize = strlen (FORMATSTRING) + 1;
936 buff = GNUNET_malloc (bufSize);
937 memcpy (buff, FORMATSTRING, bufSize);
939 [strlen (FORMATSTRING) -
941 ("0123456789012345678901234567890123456789012345678901234567890123))")],
942 &hc, sizeof (GNUNET_HashCode));
943 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
945 hostkey = public2PrivateKey (publicKey);
948 gcry_sexp_release (data);
949 gcry_sexp_release (sigdata);
950 return GNUNET_SYSERR;
952 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
953 GNUNET_CRYPTO_rsa_key_free (hostkey);
954 gcry_sexp_release (data);
955 gcry_sexp_release (sigdata);
958 LOG (GNUNET_ERROR_TYPE_WARNING,
959 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
960 __LINE__, gcry_strerror (rc));
961 return GNUNET_SYSERR;
967 /* end of crypto_rsa.c */