1 /* gc-libgcrypt.c --- Crypto wrappers around Libgcrypt for GC.
2 * Copyright (C) 2002, 2003, 2004, 2005 Simon Josefsson
4 * This file is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published
6 * by the Free Software Foundation; either version 2, or (at your
7 * option) any later version.
9 * This file is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this file; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 /* Note: This file is only built if GC uses Libgcrypt. */
30 /* Get libgcrypt API. */
42 err = gcry_control (GCRYCTL_ANY_INITIALIZATION_P);
43 if (err == GPG_ERR_NO_ERROR)
45 if (gcry_check_version (GCRYPT_VERSION) == NULL)
48 err = gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL, 0);
49 if (err != GPG_ERR_NO_ERROR)
65 gc_nonce (char *data, size_t datalen)
67 gcry_create_nonce ((unsigned char *) data, datalen);
72 gc_pseudo_random (char *data, size_t datalen)
74 gcry_randomize ((unsigned char *) data, datalen, GCRY_STRONG_RANDOM);
79 gc_random (char *data, size_t datalen)
81 gcry_randomize ((unsigned char *) data, datalen, GCRY_VERY_STRONG_RANDOM);
85 /* Memory allocation. */
88 gc_set_allocators (gc_malloc_t func_malloc,
89 gc_malloc_t secure_malloc,
90 gc_secure_check_t secure_check,
91 gc_realloc_t func_realloc, gc_free_t func_free)
93 gcry_set_allocation_handler (func_malloc, secure_malloc, secure_check,
94 func_realloc, func_free);
97 /* One-call interface. */
100 gc_md5 (const void *in, size_t inlen, void *resbuf)
102 size_t outlen = gcry_md_get_algo_dlen (GCRY_MD_MD5);
107 assert (outlen == 16);
109 err = gcry_md_open (&hd, GCRY_MD_MD5, 0);
110 if (err != GPG_ERR_NO_ERROR)
111 return GC_INVALID_HASH;
113 gcry_md_write (hd, in, inlen);
115 p = gcry_md_read (hd, GCRY_MD_MD5);
119 return GC_INVALID_HASH;
122 memcpy (resbuf, p, outlen);
130 gc_hmac_md5 (const void *key, size_t keylen,
131 const void *in, size_t inlen, char *resbuf)
133 size_t hlen = gcry_md_get_algo_dlen (GCRY_MD_MD5);
140 err = gcry_md_open (&mdh, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC);
141 if (err != GPG_ERR_NO_ERROR)
142 return GC_INVALID_HASH;
144 err = gcry_md_setkey (mdh, key, keylen);
145 if (err != GPG_ERR_NO_ERROR)
148 return GC_INVALID_HASH;
151 gcry_md_write (mdh, in, inlen);
153 hash = gcry_md_read (mdh, GCRY_MD_MD5);
157 return GC_INVALID_HASH;
160 memcpy (resbuf, hash, hlen);