This is gcrypt.info, produced by makeinfo version 4.2 from ../../doc/gcrypt.texi. INFO-DIR-SECTION GNU Libraries START-INFO-DIR-ENTRY * libgcrypt: (gcrypt) Cryptographic function library. END-INFO-DIR-ENTRY This file documents the `Libgcrypt' library. This is Edition 1.1.12, last updated 19 January 2003, of `The `Libgcrypt' Reference Manual', for Version 1.1.12. Copyright (C) 2000, 2002, 2003 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no the Front-Cover texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". File: gcrypt.info, Node: Top, Next: Introduction, Up: (dir) Main Menu ********* This is Edition 1.1.12, last updated 19 January 2003, of `The `Libgcrypt' Reference Manual', for Version 1.1.12 of the GPGME library. * Menu: * Introduction:: How to use this manual. * Preparation:: What you should do before using the library. * Cipher Functions:: All about ciphers. * Hash Functions:: How to use cryptographic hash functions. * Public Key Functions:: How to use asymmetric encryption. * Random Numbers:: How to create random. * S-expressions:: How to manage S-expressions. * MPI Functions:: How to work with big integers. * Utilities:: Helper functions. * Error Handling:: Error codes and such. Appendices * Library Copying:: The GNU Lesser General Public License says how you can copy and share `Libgcrypt'. * Copying:: The GNU General Public License says how you can copy and share some parts of `Libgcrypt'. * Free Documentation License:: This manual is under the GNU Free Documentation License. Indices * Concept Index:: Index of concepts and programs. * Function and Data Index:: Index of functions, variables and data types. File: gcrypt.info, Node: Introduction, Next: Preparation, Prev: Top, Up: Top Introduction ************ `Libgcrypt' is a library to provide cryptographic building blocks. * Menu: * Getting Started:: * Features:: * Overview:: File: gcrypt.info, Node: Getting Started, Next: Features, Up: Introduction Getting Started =============== This manual documents the `Libgcrypt' library programming interface. All functions and data types provided by the library are explained. The reader is assumed to possess basic knowledge about applied cryptography. This manual can be used in several ways. If read from the beginning to the end, it gives a good introduction into the library and how it can be used in an application. Forward references are included where necessary. Later on, the manual can be used as a reference manual to get just the information needed about any particular interface of the library. Experienced programmers might want to start looking at the examples at the end of the manual, and then only read up those parts of the interface which are unclear. File: gcrypt.info, Node: Features, Next: Overview, Prev: Getting Started, Up: Introduction Features ======== `Libgcrypt' might have a couple of advantages over other libraries doing a similar job. It's Free Software Anybody can use, modify, and redistribute it under the terms of the GNU Lesser General Public License (*note Library Copying::). Note, that some parts (which are not needed on a GNU or GNU/Linux system) are subject to the terms of the GNU General Public License (*note Copying::); please see the README file of the distribution for of list of these parts. It encapsulates the low level cryptography `Libgcrypt' a high level interface to cryptographic building blocks using an extendable and flexible API. File: gcrypt.info, Node: Overview, Prev: Features, Up: Introduction Overview ======== The `Libgcrypt' library is thread-safe. Well, we hope so ;-). Frankly, `gcry_errno' is not yet thread-safe. Most others are believed to be. Libgcrypt automagically detects whether an applications uses no threading, pthreads or GNU Pth. File: gcrypt.info, Node: Preparation, Next: Cipher Functions, Prev: Introduction, Up: Top Preparation *********** To use `Libgcrypt', you have to perform some changes to your sources and the build system. The necessary changes are small and explained in the following sections. At the end of this chapter, it is described how the library is initialized, and how the requirements of the library are verified. * Menu: * Header:: * Version Check:: * Building the source:: File: gcrypt.info, Node: Header, Next: Version Check, Up: Preparation Header ====== All interfaces (data types and functions) of the library are defined in the header file `gcrypt.h'. You must include this in all programs using the library, either directly or through some other header file, like this: #include <gcrypt.h> The name space of `Libgcrypt' is `gcry_*' for function names, `Gcry*' for data types and `GCRY_*' for other symbols. In addition the same name prefixes with one prepended underscore are reserved for internal use and should never be used by an application. File: gcrypt.info, Node: Version Check, Next: Building the source, Prev: Header, Up: Preparation Version Check ============= It is often desirable to check that the version of `Libgcrypt' used is indeed one which fits all requirements. Even with binary compatibility new features may have been introduced but due to problem with the dynamic linker an old version is actually used. So you may want to check that the version is okay right after program startup. - Function: const char *gcry_check_version (const char *REQ_VERSION) Check that the the version of the library is at minimum the one given as a string in REQ_VERSION and return the actual version string of the library; return NULL if the condition is not met. If `NULL' is passed to this function no check is done and only the version string is returned. It is a pretty good idea to run this function as soon as possible, because it may also initializes some subsystems. In a multi-threaded environment if should be called before any more threads are created. File: gcrypt.info, Node: Building the source, Prev: Version Check, Up: Preparation Building the source =================== If you want to compile a source file including the `gcrypt.h' header file, you must make sure that the compiler can find it in the directory hierarchy. This is accomplished by adding the path to the directory in which the header file is located to the compilers include file search path (via the `-I' option). However, the path to the include file is determined at the time the source is configured. To solve this problem, `Libgcrypt' ships with a small helper program `libgcrypt-config' that knows the path to the include file and other configuration options. The options that need to be added to the compiler invocation at compile time are output by the `--cflags' option to `libgcrypt-config'. The following example shows how it can be used at the command line: gcc -c foo.c `libgcrypt-config --cflags` Adding the output of `libgcrypt-config --cflags' to the compilers command line will ensure that the compiler can find the `Libgcrypt' header file. A similar problem occurs when linking the program with the library. Again, the compiler has to find the library files. For this to work, the path to the library files has to be added to the library search path (via the `-L' option). For this, the option `--libs' to `libgcrypt-config' can be used. For convenience, this option also outputs all other options that are required to link the program with the `Libgcrypt' libraries (in particular, the `-lgcrypt' option). The example shows how to link `foo.o' with the `Libgcrypt' library to a program `foo'. gcc -o foo foo.o `libgcrypt-config --libs` Of course you can also combine both examples to a single command by specifying both options to `libgcrypt-config': gcc -o foo foo.c `libgcrypt-config --cflags --libs` File: gcrypt.info, Node: Cipher Functions, Next: Hash Functions, Prev: Preparation, Up: Top Cipher Functions **************** The cipher functions are used for symmetrical encryption, i.e. encryption using a shared key. The programming model follows an open/process/close paradigm and in that similar to the other building blocks provided by Libgcrypt. To use a cipher algorithm, you must first allocate an handle for this. This can is to be done using the open function: - Function: GcryCipherHd gcry_cipher_open (int ALGO, int MODE, unsigned int FLAGS) This function creates the context required for most of the other cipher functions and returns a handle to it. In case of an error `NULL' is returned. You must tell this function which algorithm and what mode you want to use. The function `gcry_cipher_map_name' may be used to get the a value for the ALGO from a textual name or one of the predefined constants can be used: `GCRY_CIPHER_NONE' This is not a real algorithm but used by some functions as error return. The value always evaluates to false. `GCRY_CIPHER_IDEA' This is the IDEA algorithm. The constant is provided but there is currently no implementation for it because the algorithm is patented. `GCRY_CIPHER_3DES' Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but you have to pass 192 bits because the most significant bits of each byte are ignored. `GCRY_CIPHER_CAST5' CAST128-5 block cipher algorithm. The key size is 128 bits. `GCRY_CIPHER_BLOWFISH' The blowfish algorithm. The current implementation allows only for a key size of 128 bits. `GCRY_CIPHER_SAFER_SK128' Reserved and not currently implemented. `GCRY_CIPHER_DES_SK' Reserved and not currently implemented. `GCRY_CIPHER_AES' `GCRY_CIPHER_AES128' `GCRY_CIPHER_RIJNDAEL' `GCRY_CIPHER_RIJNDAEL128' AES (Rijndael) with a 128 bit key. `GCRY_CIPHER_AES192' `GCRY_CIPHER_RIJNDAEL128' AES (Rijndael) with a 192 bit key. `GCRY_CIPHER_AES256' `GCRY_CIPHER_RIJNDAEL256' AES (Rijndael) with a 256 bit key. `GCRY_CIPHER_TWOFISH' The Twofish algorithm with a 256 bit key. `GCRY_CIPHER_ARCFOUR' An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm. Note that this is a stream cipher and must be used very carefully to avoid a couple of weaknesses. `GCRY_CIPHER_DES' Standard DES with a 56 bit key. You need to pass 64 bit but the high bits of each byte are ignored. Note, that this is a weak algorithm which is can be broken in reasonable time using a brute force approach. The second argument is MODE which describes the mode the algorithm is to be used in. Note, that some modes don't work together with all algorithms. The following modes are available: `GCRY_CIPHER_MODE_NONE' No mode specified, may be set later using other functions. The value of this constant is always 0. `GCRY_CIPHER_MODE_ECB' Electronic Codebook mode. `GCRY_CIPHER_MODE_CFB' Cipher Feedback mode. `GCRY_CIPHER_MODE_CBC' Cipher Block Chaining mode. `GCRY_CIPHER_MODE_STREAM' Stream mode, only to be used with stream cipher algorithms. `GCRY_CIPHER_MODE_OFB' Outer Feedback mode. The third argument FLAGS can either be passed as `0' or as the bit-wise OR of the following constants. `GCRY_CIPHER_SECURE' Make sure that all operations are allocated in secure memory. This is useful, when the key material is highly confidential. `GCRY_CIPHER_ENABLE_SYNC' This flag enables the CFB sync mode, which is a special feature of Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant. See `gcry_cipher_sync'. `GCRY_CIPHER_CBC_CTS' Enable cipher text stealing for the CBS mode. To release the context allocated with this function, `gcry_cipher_close' should be used: - Function: void gcry_cipher_close (GcryCipherHd H) This function releases the context created by `gcry_cipher_open'. Now that a context has been allocated, the key to be used for decryption or encryption must be set. This is done with the following function: - Function: int gcry_cipher_setkey (GcryCipherHd H, void *K, size_t L) Set the key K used for encryption or decryption in the context denoted by the handle H. The length L of the key K must match the required length of the algorithm set for this context or be in the allowed range for algorithms with variable key size. The function checks this and returns an error if there is a problem. A caller should always check for an error. Note, this is currently implemented as a macro but may be changed to a function in the future. Most crypto modes requires an initialization vector (IV), which usually is a non-secret random string acting as a kind of salt value. To set this IV, use the function: - Function: int gcry_cipher_setiv (GCRY_CIPHER_HD H, void *K, size_t L) Set the initialization vector used for encryption or decryption. The vector is passed as the buffer K of length L and copied to internal data structures. The function checks that the IV matches the requirement of the selected algorithm and mode. Note, that this is implemented as a macro. The actual encryption and decryption is done by using one of the following functions. They may be used as often as required to process all the data. - Function: int gcry_cipher_encrypt (GCRY_CIPHER_HD H, unsigned char *out, size_t OUTSIZE, const unsigned char *IN, size_t INLEN) `gcry_cipher_encrypt' is used to encrypt the data. This function can either work in place or with two buffers. It uses the cipher context already setup and described by the handle H. There are 2 ways to use the function: If IN is passed as `NULL' and INLEN is `0', in-place encryption of the data in OUT or length OUTSIZE takes place. With IN being not `NULL', INLEN bytes are encrypted to the buffer OUT which must have at least a size of INLEN. OUTLEN must be set to the allocated size of OUT, so that the function can check that there is sufficient space. Note, that overlapping buffers are not allowed. Depending on the selected algorithms and encryption mode, the length of the buffers must be a multiple of the block size. The function returns `0' on success or an error code. - Function: int gcry_cipher_decrypt (GCRY_CIPHER_HD H, unsigned char *out, size_t OUTSIZE, const unsigned char *IN, size_t INLEN) `gcry_cipher_decrypt' is used to decrypt the data. This function can either work in place or with two buffers. It uses the cipher context already setup and described by the handle H. There are 2 ways to use the function: If IN is passed as `NULL' and INLEN is `0', in-place decryption of the data in OUT or length OUTSIZE takes place. With IN being not `NULL', INLEN bytes are decrypted to the buffer OUT which must have at least a size of INLEN. OUTLEN must be set to the allocated size of OUT, so that the function can check that there is sufficient space. Note, that overlapping buffers are not allowed. Depending on the selected algorithms and encryption mode, the length of the buffers must be a multiple of the block size. The function returns `0' on success or an error code. OpenPGP (as defined in RFC-2440) requires a special sync operation in some places, the following function is used for this: - Function: int gcry_cipher_sync (GCRY_CIPHER_HD H) Perform the OpenPGP sync operation on context H. Note, that this is a no-op unless the context was created with the flag `GCRY_CIPHER_ENABLE_SYNC' Some of the described functions are implemented as macros utilizing a catch-all control function. This control function is rarely used directly but there is nothing which would inhibit it: - Function: int gcry_cipher_ctl (GCRY_CIPHER_HD H, int CMD, void *BUFFER, size_t BUFLEN) `gcry_cipher_ctl' controls various aspects of the cipher module and specific cipher contexts. Usually some more specialized functions or macros are used for this purpose. The semantics of the function and its parameters depends on the the command CMD and the passed context handle H. Please see the comments in the source code (`src/global.c') for details. To work with the algorithms, several functions are available to map algorithm names to the internal identifiers, as well as ways to retrieve information about an algorithm or the current cipher context. - Function: int gcry_cipher_info (GCRY_CIPHER_HD H, int WHAT, void *BUFFER, size_t *NBYTES) `gcry_cipher_info' is used to retrieve various information about a cipher context or the cipher module in general. Currently no information is available. - Function: int gcry_cipher_algo_info (int ALGO, int WHAT, void *BUFFER, size_t *NBYTES) This function is used to retrieve information on a specific algorithm. You pass the cipher algorithm ID as ALGO and the type of information requested as WHAT. The result is either returned as the return code of the function or copied to the provided BUFFER whose allocated length must be available in an integer variable with the address passed in NBYTES. This variable will also receive the actual used length of the buffer. The function returns `-1' on error; `gcry_errno' may be used to get the actual error code. Here is a list of supported codes for WHAT: `GCRYCTL_GET_KEYLEN:' Return the length of the key. If the algorithm supports multiple key length, the maximum supported value is returned. The length is returned as number of octets (bytes) and not as number of bits. BUFFER and NBYTES must be zero. `GCRYCTL_GET_BLKLEN:' Return the block length of the algorithm counted in octets. BUFFER and NBYTES must be zero. `GCRYCTL_TEST_ALGO:' Returns `0' when the specified algorithm is available for use. BUFFER and NBYTES must be zero. - Function: const char *gcry_cipher_algo_name (int ALGO) `gcry_cipher_algo_name' returns a string with the name of the cipher algorithm ALGO. If the algorithm is not known or another error occurred, an empty string is returned. This function will never return `NULL'. - Function: int gcry_cipher_map_name (const char *NAME) `gcry_cipher_map_name' returns the algorithm identifier for the cipher algorithm described by the string NAME. If this algorithm is not available `0' is returned. - Function: int gcry_cipher_mode_from_oid (const char *STRING) Return the cipher mode associated with an ASN.1 object identifier. The object identifier is expected to be in the IETF-style dotted decimal notation. The function returns `0' for an unknown object identifier or when no mode is associated with it. File: gcrypt.info, Node: Hash Functions, Next: Public Key Functions, Prev: Cipher Functions, Up: Top Hash Functions ************** How to use cryptographic hash functions. Libgcrypt provides an easy and consistent to use interface to hash functions. Hashing is buffered and several hash algorithms can be updated at once. It is possible to calculate a MAC using the same routines. For convenience reasons, we plan to integrate simple CRC algorithms too To use most of these function it is necessary to create a context; this is done using: - Function: GcryMDHd gcry_md_open (int ALGO, unsigned int FLAGS) Create a message digest object for algorithm ALGO. FLAGS may be given as an bitwise OR of constants described below. ALGO may be given as `0' if the algorithms to use are later set using `gcry_md_enable'. The following algorithms are supported: `GCRY_MD_NONE' This is not a real algorithm but used by some functions as an error return value. This constant is guaranteed to have the value `0'. `GCRY_MD_SHA1' This is the SHA-1 algorithm which yields a message digest of 20 bytes. `GCRY_MD_RMD160' This is the 160 bit version of the RIPE message digest (RIPE-MD-160). Like SHA-1 it also yields a digest of 20 bytes. `GCRY_MD_MD5' This is the well known MD5 algorithm, which yields a message digest of 16 bytes. `GCRY_MD_MD4' This is the MD4 algorithm, which yields a message digest of 16 bytes. `GCRY_MD_MD2' This is an reserved identifier for MD-2; there is no implementation yet. `GCRY_MD_TIGER' This is the TIGER/192 algorithm which yields a message digest of 24 bytes. `GCRY_MD_HAVAL' This is an reserved for the HAVAL algorithm with 5 passes and 160 bit. It yields a message digest of 20 bytes. Note that there is no implementation yet available. `GCRY_MD_SHA256' This is reserved for SHA-2 with 256 bits. It yields a message digest of 32 bytes. Note that there is no implementation yet available. `GCRY_MD_SHA384' This is reserved for SHA-2 with 384 bits. It yields a message digest of 48 bytes. Note that there is no implementation yet available. `GCRY_MD_SHA512' This is reserved for SHA-2 with 512 bits. It yields a message digest of 64 bytes. Note that there is no implementation yet available. The flags allowed for MODE are: `GCRY_MD_FLAG_SECURE' Allocate all buffers and the resulting digest in "secure memory". Use this is the hashed data is highly confidential. `GCRY_MD_FLAG_HMAC' Turn the algorithm into a HMAC message authentication algorithm. Note that the function `gcry_md_setkey' must be used set the MAC key. If you want to calculate several hash algorithms at the same time, you have to use the following function right after the `gcry_md_open': - Function: int gcry_md_enable (GcryMDHd H, int ALGO) Add the message digest algorithm ALGO to the digest object described by handle H. Duplicated enabling of algorithms is detected and ignored. If the flag `GCRY_MD_FLAG_HMAC' was used, the key for the MAC must be set using the function: - Function: int gcry_md_setkey (GcryMDHd H, const void *KEY, size_t KEYLEN) For use with the HMAC feature, set the MAC key to the value of KEY of length KEYLEN. After you are done with the hash calculation, you should release the resources by using: - Function: void gcry_md_close (GcryMDHd H) Release all resources of hash context H. H should not be used after a call to this function. A `NULL' passed as H is ignored. Often you have to do several hash operations using the same algorithm. To avoid the overhead of creating and releasing context, a reset function is provided: - Function: void gcry_md_reset (GcryMDHd H) Reset the current context to its initial state. This is effectively identical to a close followed by an open and enabling all currently active algorithms. Often it is necessary to start hashing some data and than continue to hash different data. To avoid hashing the same data several times (which might not even be possible if the data is received from a pipe), a snapshot of the current hash context can be taken and turned into a new context: - Function: GcryMDHd gcry_md_copy (GcryMDHd H) Create a new digest object as an exact copy of the object described by handle H. The context is not reset and you can continue to hash data using this context and independently using the original context. Now that we have prepared everything to calculate hashes, its time to see how it is actually done. There are 2 ways for this, one to update the hash with a block of memory and one macro to update the hash by just one character. Both may be used intermixed. - Function: void gcry_md_write (GcryMDHd H, const void *BUFFER, size_t LENGTH) Pass LENGTH bytes of the data in BUFFER to the digest object with handle H to update the digest values. This function should be used for large blocks of data. - Function: void gcry_md_putc (GcryMDHd H, int C) Pass the byte in C to the digest object with handle H to update the digest value. This is an efficient function, implemented as a macro to buffer the data before an actual update. The semantics of the hash functions don't allow to read out intermediate message digests because the calculation must be finalized fist. This finalization may for example include the number of bytes hashed in the message digest. - Function: void gcry_md_final (GcryMDHd H) Finalize the message digest calculation. This is not really needed because `gcry_md_read' does this implicitly. After this has been done no further updates (by means of `gcry_md_write' or `gcry_md_putc' are allowed. Only the first call to this function has an effect. It is implemented as a macro. The way to read out the calculated message digest is by using the function: - Function: unsigned char *gcry_md_read (GcryMDHd H, int ALGO) `gcry_md_read' returns the message digest after finalizing the calculation. This function may be used as often as required but it will always return the same value for one handle. The returned message digest is allocated within the message context and therefore valid until the handle is released or reseted (using `gcry_md_close' or `gcry_md_reset'. ALGO may be given as 0 to return the only enabled message digest or it may specify one of the enabled algorithms. The function does return `NULL' if the requested algorithm has not been enabled. Because it is often necessary to get the message digest of one block of memory, a fast convenience function is available for this task: - Function: void gcry_md_hash_buffer (int ALGO, void *DIGEST, const cvoid *BUFFER, size_t LENGTH); `gcry_md_hash_buffer' is a shortcut function to calculate a message digest of a buffer. This function does not require a context and immediately returns the message digest of the LENGTH bytes at BUFFER. DIGEST must be allocated by the caller, large enough to hold the message digest yielded by the the specified algorithm ALGO. This required size may be obtained by using the function `gcry_md_get_algo_dlen'. Note, that this function will abort the process if an unavailable algorithm is used. Hash algorithms are identified by internal algorithm numbers (see `gcry_md_open' for a list. However, in most applications they are used by names, so 2 functions are available to map between string representations and hash algorithm identifiers. - Function: const char *gcry_md_algo_name (int ALGO) Map the digest algorithm id ALGO to a string representation of the algorithm name. For unknown algorithms this functions returns an empty string. This function should not be used to test for the availability of an algorithm. - Function: int gcry_md_map_name (const char *NAME) Map the algorithm with NAME to a digest algorithm identifier. Returns 0 if the algorithm name is not known. Names representing ASN.1 object identifiers are recognized if the IETF dotted format is used and the OID is prefixed with either "`oid.'" or "`OID.'". For a list of supported OIDs, see the source code at `cipher/md.c'. This function should not be used to test for the availability of an algorithm. - Function: int gcry_md_get_asnoid (int ALGO, void *BUFFER, size_t *LENGTH) Return an DER encoded ASN.1 OID for the algorithm ALGO in the user allocated BUFFER. LENGTH must point to variable with the available size of BUFFER and receives after return the actual size of the returned OID. The return value may be `GCRYERR_TOO_SHORT' if the provided buffer is to short to receive the OID; it is possible to call the function with `NULL' for BUFFER to have it only return the required size. The function returns 0 on success. To test whether an algorithm is actually available for use, the following macro should be used: - Function: int gcry_md_test_algo (int ALGO) The macro returns 0 if the algorithm ALGO is available for use. If the length of a message digest is not known, it can be retrieved using the following function: - Function: unsigned int gcry_md_get_algo_dlen (int ALGO) Retrieve the length in bytes of the digest yielded by algorithm ALGO. This is often used prior to `gcry_md_read' to allocate sufficient memory for the digest. In some situations it might be hard to remember the algorithm used for the ongoing hashing. The following function might be used to get that information: - Function: int gcry_md_get_algo (GcryMDHd H) Retrieve the algorithm used with the handle H. Note, that this does not work reliable if more than one algorithm is enabled in H. The following macro might also be useful: - Function: int gcry_md_is_secure (GcryMDHd H) This macro return true when the digest object H is allocated in "secure memory"; i.e. H was created with the `GCRY_MD_FLAG_SECURE'. Tracking bugs related to hashing is often a cumbersome task which requires to add a lot of printf statements into the code. Libgcrypt provides an easy way to avoid this. The actual data hashed can be written to files on request. The following 2 macros should be used to implement such a debugging facility: - Function: void gcry_md_start_debug (GcryMDHd H, const char *SUFFIX) Enable debugging for the digest object with handle H. This creates create files named `dbgmd-<n>.<string>' while doing the actual hashing. SUFFIX is the string part in the filename. The number is a counter incremented for each new hashing. The data in the file is the raw data as passed to `gcry_md_write' or `gcry_md_putc'. - Function: void gcry_md_stop_debug (GcryMDHd H, int RESERVED) Stop debugging on handle H. RESERVED should be specified as 0. This function is usually not required because `gcry_md_close' does implicitly stop debugging. File: gcrypt.info, Node: Public Key Functions, Next: Random Numbers, Prev: Hash Functions, Up: Top Public Key Functions ******************** Public key encryption, also known as asymmetric encryption, is am easy way for key management and to provide digital signatures. Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well as DSA (Digital Signature Algorithm) and ElGamal. The versatile interface allows to add more algorithms in the future. The API is based on data structures called S-expressions (see XXXX) and does not work with contexts as most of the other building blocks Libgcrypt provides. To describe how Libgcrypt expect keys, we use some examples. Note that words in uppercase indicate parameters whereas lowercase words are literals. (private-key (dsa (p P-MPI) (q Q-MPI) (g G-MPI) (y Y-MPI) (x X-MPI))) This specifies an DSA private key with the following parameters: P-MPI DSA prime p. Q-MPI DSA group order q (which is a prime divisor of p-1). G-MPI DSA group generator g. Y-MPI DSA public key value y = g^x \bmod p. X-MPI DSA secret exponent x. All the MPI values are expected to be in `GCRYMPI_FMT_USG' format. The public key is similar with "private-key" replaced by "public-key" and no X-MPI. An easy way to create such an S-expressions is by using `gcry_sexp_build' which allows to pass a string with printf-like escapes to insert MPI values. Here is an example for an RSA key: (private-key (rsa (n N-MPI) (e E-MPI) (d D-MPI) (p P-MPI) (q Q-MPI) (u U-MPI) with N-MPI RSA public modulus n. E-MPI RSA public exponent e. D-MPI RSA secret exponent d = e^-1 \bmod (p-1)(q-1). P-MPI RSA secret prime p. Q-MPI RSA secret prime q with q > p. U-MPI multiplicative inverse u = p^-1 \bmod q. Note, that we will in future allow to use keys without p,q and u specified and may also support other parameters for performance reasons. Now that we know the key basics, we can carry on and explain how to encrypt and decrypt data. In almost all cases the data is a random session key which is in turn used for the actual encryption of the real data. There are 2 functions to do this: - Function: int gcry_pk_encrypt (GcrySexp *R_CIPH, GcrySexp DATA, GcrySexp PKEY) Obviously a public key must be provided for encryption. It is expected as an appropriate S-expression (see above) in PKEY. The data to be encrypted can either be in the simple old format, which is a very simple S-expression consisting only of one MPI, or it may be a more complex S-expression which also allows to specify padding rules. If you don't want to let Libgcrypt handle the padding, you must pass an appropriate MPI using the this expression for DATA: (data (flags raw) (value MPI)) This has the same semantics as the old style MPI only way. MPI is the actual data, already padded appropriate for your protocol. Most systems however use PKCS#1 padding and so you can use this S-expression for DATA: (data (flags pkcs1) (value BLOCK)) Here, the "flags" list has the "pkcs1" flag which let the function know that it should provide PKCS#1 block type 2 padding. The actual data to be encrypted is passed as a string of octets in BLOCK. The function checks that this data actually can be used with the given key, does the padding and encrypts it. If the function could successfully perform the encryption, the return value will be 0 and a a new S-expression with the encrypted result is allocated and assign to the variable at the address of R_CIPH. The caller is responsible to release this value using `gcry_sexp_release'. In case of an error, an error code is returned and R_CIPH will be set to `NULL'. The returned S-expression has this format when used with RSA: (enc-val (rsa (a A-MPI))) Where A-MPI is an MPI with the result of the RSA operation. When using the ElGamal algorithm, the return value will have this format: (enc-val (elg (a A-MPI) (b B-MPI))) Where A-MPI and B-MPI are MPIs with the result of the ElGamal encryption operation. - Function: int gcry_pk_decrypt (GcrySexp *R_PLAIN, GcrySexp DATA, GcrySexp SKEY) Obviously a private key must be provided for decryption. It is expected as an appropriate S-expression (see above) in SKEY. The data to be decrypted must match the format of the result as returned by `gcry_pk_encrypt'. Note that this function does not know of any padding and the caller must do any un-padding on his own. The function returns 0 on success or an error code. The variable at the address of R_PLAIN will be set to NULL on error or receive the decrypted value on success. The format of R_PLAIN is currently a simple S-expression with just one MPI. Another operation commonly performed using public keys are digital signature. In some sense they are even more important than the encryption because digital signature are an important instrument for key management. Libgcrypt support digital signatures using 2 functions, similar to the encryption functions: - Function: int gcry_pk_sign (GcrySexp *R_SIG, GcrySexp DATA, GcrySexp SKEY) This function creates a digital signature for DATA using the private key SKEY and place it into the variable at the address of R_SIG. DATA may either be the simple old style S-expression with just one MPI or a modern and more versatile S-expression which allows to let Libgcrypt handle padding: (data (flags pkcs1) (hash HASH-ALGO BLOCK)) This example requests to sign the data in BLOCK after applying PKCS#1 block type 1 style padding. HASH-ALGO is a string with the hash algorithm to be encoded into the signature, this may be any hash algorithm name as supported by Libgcrypt. Most likely, this will be "sha1", "rmd160" or "md5". It is obvious that the length of BLOCK must match the size of that message digests; the function checks that this and other constraints are valid. If PKCS#1 padding is not required (because the caller does already provide a padded value), either the old format or better the following format should be used: (data (flags raw) (value MPI)) Here, the data to be signed is directly given as an MPI. The signature is returned as a newly allocated S-expression in R_SIG using this format for RSA: (sig-val (rsa (s S-MPI))) Where S-MPI is the result of the RSA sign operation. For DSA the S-expression returned is: (sig-val (dsa (r R-MPI) (s S-MPI))) Where R-MPI and S-MPI are the result of the DSA sign operation. For ElGamal signing (which is slow, yields large numbers and probably is not as secure as the other algorithms), the same format is used with "elg" replacing "dsa". The operation most commonly used is definitely the verification of a signature. Libgcrypt provides this function: - Function: int gcry_pk_verify (GcrySexp SIG, GcrySexp DATA, GcrySexp PKEY) This is used to check whether the signature SIG matches the DATA. The public key PKEY must be provided to perform this verification. This function is similar in its parameters to `gcry_pk_sign' with the exceptions that the public key is used instead of the private key and that no signature is created but a signature, in a format as created by `gcry_pk_sign', is passed to the function in SIG. The result is 0 for success (i.e. the data matches the signature), or an error code where the most relevant code is `GCRYERR_BAD_SIGNATURE' to indicate that the signature does not match the provided data. A couple of utility functions are available to retrieve the length of the key, map algorithm identifiers and perform sanity checks: - Function: const char * gcry_pk_algo_name (int ALGO) Map the public key algorithm id ALGO to a string representation of the algorithm name. For unknown algorithms this functions returns an empty string. - Function: int gcry_pk_map_name (const char *NAME) Map the algorithm NAME to a public key algorithm Id. Returns 0 if the algorithm name is not known. - Function: int gcry_pk_test_algo (int ALGO) Return 0 if the public key algorithm ALGO is available for use. - Function: unsigned int gcry_pk_get_nbits (GcrySexp KEY) Return what is commonly referred as the key length for the given public or private in KEY. - Function: unsigned char * gcry_pk_get_keygrip (GcrySexp KEY, unsigned char *ARRAY) Return the so called "keygrip" which is the SHA-1 hash of the public key parameters expressed in a way depended on the algorithm. ARRAY must either provide space for 20 bytes or `NULL;'. In the latter case a newly allocated array of that size is returned. On success a pointer to the newly allocated space or to ARRAY is returned. `NULL' is returned to indicate an error which is most likely an unknown algorithm or one where a "keygrip" has not yet been defined. The function accepts public or secret keys in KEY. - Function: int gcry_pk_testkey (GcrySexp KEY) Return 0 if KEY (either private or public) is sane. - Function: int gcry_pk_algo_info (int ALGO, int WHAT, void *BUFFER, size_t *NBYTES) Depending on the value of WHAT return various information about the public key algorithm with the id ALGO. Note, that the function returns `-1' on error and the actual error code must be retrieved using the function `gcry_errno'. The currently defined values for WHAT are: `GCRYCTL_TEST_ALGO:' Return 0 when the specified algorithm is available for use. BUFFER must be `NULL', NBYTES may be passed as `NULL' or point to a variable with the required usage of the algorithm. This may be 0 for "don't care" or the bit-wise OR of these flags: `GCRY_PK_USAGE_SIGN' Algorithm is usable for signing. `GCRY_PK_USAGE_ENCR' Algorithm is usable for encryption. `GCRYCTL_GET_ALGO_USAGE:' Return the usage flags for the given algorithm. An invalid algorithm return 0. Disabled algorithms are ignored here because we want to know whether the algorithm is at all capable of a certain usage. `GCRYCTL_GET_ALGO_NPKEY' Return the number of elements the public key for algorithm ALGO consist of. Return 0 for an unknown algorithm. `GCRYCTL_GET_ALGO_NSKEY' Return the number of elements the private key for algorithm ALGO consist of. Note that this value is always larger than that of the public key. Return 0 for an unknown algorithm. `GCRYCTL_GET_ALGO_NSIGN' Return the number of elements a signature created with the algorithm ALGO consists of. Return 0 for an unknown algorithm or for an algorithm not capable of creating signatures. `GCRYCTL_GET_ALGO_NENC' Return the number of elements a encrypted message created with the algorithm ALGO consists of. Return 0 for an unknown algorithm or for an algorithm not capable of encryption. Please note that parameters not required should be passed as `NULL'. - Function: int gcry_pk_ctl (int CMD, void *BUFFER, size_t BUFLEN) This is a general purpose function to perform certain control operations. CMD controls what is to be done. The return value is 0 for success or an error code. Currently supported values for CMD are: `GCRYCTL_DISABLE_ALGO' Disable the algorithm given as an algorithm id in BUFFER. BUFFER must point to an `int' variable with the algorithm id and BUFLEN must have the value `sizeof (int)'. Libgcrypt also provides a function to generate public key pairs: - Function: int gcry_pk_genkey (GcrySexp *R_KEY, GcrySexp PARMS) This function create a new public key pair using information given in the S-expression PARMS and stores the private and the public key in one new S-expression at the address given by R_KEY. In case of an error, R_KEY is set to `NULL'. The return code is 0 for success or an error code otherwise. Here is an example for PARMS for creating a 1024 bit RSA key: (genkey (rsa (nbits 1024))) To create an ElGamal key, substitute "elg" for "rsa" and to create a DSA key use "elg". Valid ranges for the key length depend on the algorithms; all commonly used key lengths are supported. The key pair is returned in a format depending on the algorithm. Both, private and secret, keys are returned and my be accompanied by some miscellaneous information. The format resembles closely the one of the public respectively the private key. Frankly, they are put into one container, so that they can easily be extracted. As an example, here is what the ElGamal key generation returns: (key-data (public-key (elg (p P-MPI) (g G-MPI) (y Y-MPI))) (private-key (elg (p P-MPI) (g G-MPI) (y Y-MPI) (x X-MPI))) (misc-key-info (pm1-factors N1 N2 ... NN))) As you can see, some of the information is duplicated, but this provides an easy way to extract either the public or the private key. Note that the order of the elements is not defined, e.g. the private key may be stored before the public key. N1 N2 ... NN is a list of prime numbers used to composite P-MPI; this is in general not a very useful information. File: gcrypt.info, Node: Random Numbers, Next: S-expressions, Prev: Public Key Functions, Up: Top Random Numbers ************** - Function: void gcry_randomize (unsigned char *BUFFER, size_t LENGTH, enum gcry_random_level LEVEL) Fill BUFFER with LENGTH random bytes using a random quality as defined by LEVEL. - Function: void * gcry_random_bytes (size_t NBYTES, enum gcry_random_level LEVEL) Allocate a memory block consisting of NBYTES fresh random bytes using a random quality as defined by LEVEL. - Function: void * gcry_random_bytes_secure (size_t NBYTES, enum gcry_random_level LEVEL) Allocate a memory block consisting of NBYTES fresh random bytes using a random quality as defined by LEVEL. This function differs from `gcry_random_bytes' in that the returned buffer is allocated in a "secure" area of the memory.