OpenSSLcrypto Pod
OpenSSLcrypto Pod
0.9.7
Crypto Library
Title Page Crypto Library
CRYPTO 1
ASN1_OBJECT allocation 2
ASN1_STRING utility 3
ASN1_STRING allocation 4
ASN1_STRING output 5
BIO - I/O abstraction 7
BIO control 8
BIO chain traversal 10
BIO base64 12
BIO buffering 14
BIO cipher 15
BIO message digest 16
BIO null 18
BIO SSL 19
BIO allocation 24
BIO chain 25
BIO I/O 26
BIO callback 27
BIO retry 29
BIO accept 31
BIO pair 34
BIO connect 37
BIO file decscriptor 40
BIO file 41
BIO memory 43
BIO null 45
BIO socket 46
Blowfish encryption 47
BN multiprecision integer 49
BIGNUM operations 52
BIGNUM functions 54
BIGNUM conversion 55
BIGNUM compare and test 57
BIGNUM copy 58
BN_CTX allocation 59
BIGNUM temp 60
BIGNUM primes 61
BIGNUM internals 62
BIGNUM inverse 65
BIGNUM Montgomery 66
BIGNUM modular multiplication 68
BIGNUM allocation 69
BIGNUM size 70
BIGNUM pseudo-random 71
BIGNUM bit-operations 72
BIGNUM exchange 73
BIGNUM assignment 74
BUF_MEM 75
CRYPTO internals 76
d2i/i2d ASN1_OBJECT 77
d2i/i2d PKCS#3 DH parameter 78
d2i/i2d DSA key encoding and parsing 79
05 July 2003 i
Crypto Library Table of Contents
ii 05 July 2003
Table of Contents Crypto Library
PKCS12_parse 183
PKCS7_decrypt 184
PKCS7_encrypt 185
PKCS7_sign 186
PKCS7_verify 187
RAND pseudo-random number generator 189
RAND entropy 191
RAND random data 192
RAND cleanup 193
RAND_egd entropy daemon 194
RAND seed file 195
RAND select method 196
RC4 encryption 198
RIPEMD-160 hash 199
RSA public key cryptosystem 200
RSA protection from timing attacks 202
RSA validate private keys 203
RSA generate key pair 204
RSA add application data 205
RSA allocation 207
RSA asymmetric encryption padding 208
RSA print cryptographic parameters 210
RSA low level signature 211
RSA public key cryptography 212
RSA select method 213
RSA signatures 216
RSA ASN1 signatures 217
RSA size 218
SHA Secure Hash Algorithm 219
SMIME parse 220
SMIME_write_PKCS7 221
OpenSSL thread support 222
UI New User Interface 224
Compatibility user interface 227
X509_NAME modification 228
X509_NAME_ENTRY utility 230
X509_NAME lookup and enumeration 231
X509_NAME printing 233
X509 certificate ASN1 allocation 235
iv 05 July 2003
Crypto Library CRYPTO
CRYPTO
CRYPTO - OpenSSL cryptographic library
SYNOPSIS
DESCRIPTION
The OpenSSL crypto library implements a wide range of cryptographic algorithms used in various
Internet standards. The services provided by this library are used by the OpenSSL implementations of
SSL, TLS and S/MIME, and they have also been used to implement SSH, OpenPGP, and other
cryptographic standards.
OVERVIEW
libcrypto consists of a number of sub-libraries that implement the individual algorithms.
The functionality includes symmetric encryption, public key cryptography and key agreement, certificate
handling, cryptographic hash functions and a cryptographic pseudo-random number generator.
SYMMETRIC CIPHERS
blowfish(3)|blowfish(3), cast(3)|cast(3), des(3)|des(3), idea(3)|idea(3), rc2(3)|rc2(3),
rc4(3)|rc4(3), rc5(3)|rc5(3)
PUBLIC KEY CRYPTOGRAPHY AND KEY AGREEMENT
dsa(3)|dsa(3), dh(3)|dh(3), rsa(3)|rsa(3)
CERTIFICATES
x509(3)|x509(3), x509v3(3)|x509v3(3)
AUTHENTICATION CODES, HASH FUNCTIONS
hmac(3)|hmac(3), md2(3)|md2(3), md4(3)|md4(3), md5(3)|md5(3), mdc2(3)|mdc2(3),
ripemd(3)|ripemd(3), sha(3)|sha(3)
AUXILIARY FUNCTIONS
err(3)|err(3), threads(3)|threads(3), rand(3)|rand(3),
OPENSSL_VERSION_NUMBER(3)|OPENSSL_VERSION_NUMBER(3)
INPUT/OUTPUT, DATA ENCODING
asn1(3)|asn1(3), bio(3)|bio(3), evp(3)|evp(3), pem(3)|pem(3), pkcs7(3)|pkcs7(3),
pkcs12(3)|pkcs12(3)
INTERNAL FUNCTIONS
bn(3)|bn(3), buffer(3)|buffer(3), lhash(3)|lhash(3), objects(3)|objects(3), stack(3)|stack(3),
txt_db(3)|txt_db(3)
NOTES
Some of the newer functions follow a naming convention using the numbers 0 and 1. For example the
functions:
int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_add1_trust_object(X509 *x, ASN1_OBJECT *obj);
The 0 version uses the supplied structure pointer directly in the parent and it will be freed up when the
parent is freed. In the above example crl would be freed but rev would not.
The 1 function uses a copy of the supplied structure pointer (or in some cases increases its link count) in
the parent and so both (x and obj above) should be freed up.
SEE ALSO
openssl(1)|openssl(1), ssl(3)|ssl(3)
05 July 2003 1
ASN1_OBJECT allocation Crypto Library
ASN1_OBJECT allocation
ASN1_OBJECT_new, ASN1_OBJECT_free - object allocation functions
SYNOPSIS
ASN1_OBJECT *ASN1_OBJECT_new(void);
void ASN1_OBJECT_free(ASN1_OBJECT *a);
DESCRIPTION
The ASN1_OBJECT allocation routines, allocate and free an ASN1_OBJECT structure, which
represents an ASN1 OBJECT IDENTIFIER.
ASN1_OBJECT_new() allocates and initializes a ASN1_OBJECT structure.
ASN1_OBJECT_free() frees up the ASN1_OBJECT structure a.
NOTES
Although ASN1_OBJECT_new() allocates a new ASN1_OBJECT structure it is almost never used in
applications. The ASN1 object utility functions such as OBJ_nid2obj() are used instead.
RETURN VALUES
If the allocation fails, ASN1_OBJECT_new() returns NULL and sets an error code that can be obtained
by ERR_get_error(3)|ERR_get_error(3). Otherwise it returns a pointer to the newly allocated structure.
ASN1_OBJECT_free() returns no value.
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), d2i_ASN1_OBJECT(3)|d2i_ASN1_OBJECT(3)
HISTORY
ASN1_OBJECT_new() and ASN1_OBJECT_free() are available in all versions of SSLeay and
OpenSSL.
2 05 July 2003
Crypto Library ASN1_STRING utility
ASN1_STRING utility
ASN1_STRING_dup, ASN1_STRING_cmp, ASN1_STRING_set, ASN1_STRING_length,
ASN1_STRING_length_set, ASN1_STRING_type, ASN1_STRING_data - ASN1_STRING utility
functions
SYNOPSIS
int ASN1_STRING_length(ASN1_STRING *x);
unsigned char * ASN1_STRING_data(ASN1_STRING *x);
05 July 2003 3
ASN1_STRING allocation Crypto Library
ASN1_STRING allocation
ASN1_STRING_new, ASN1_STRING_type_new, ASN1_STRING_free - ASN1_STRING allocation
functions
SYNOPSIS
ASN1_STRING * ASN1_STRING_new(void);
ASN1_STRING * ASN1_STRING_type_new(int type);
void ASN1_STRING_free(ASN1_STRING *a);
DESCRIPTION
ASN1_STRING_new() returns an allocated ASN1_STRING structure. Its type is undefined.
ASN1_STRING_type_new() returns an allocated ASN1_STRING structure of type type.
ASN1_STRING_free() frees up a.
NOTES
Other string types call the ASN1_STRING functions. For example ASN1_OCTET_STRING_new()
calls ASN1_STRING_type(V_ASN1_OCTET_STRING).
RETURN VALUES
ASN1_STRING_new() and ASN1_STRING_type_new() return a valid ASN1_STRING structure or
NULL if an error occurred.
ASN1_STRING_free() does not return a value.
SEE ALSO
ERR_get_error(3)|ERR_get_error(3)
HISTORY
TBA
4 05 July 2003
Crypto Library ASN1_STRING output
ASN1_STRING output
ASN1_STRING_print_ex, ASN1_STRING_print_ex_fp - ASN1_STRING output routines.
SYNOPSIS
#include <openssl/asn1.h>
05 July 2003 5
ASN1_STRING output Crypto Library
HISTORY
TBA
6 05 July 2003
Crypto Library BIO - I/O abstraction
TBA
DESCRIPTION
A BIO is an I/O abstraction, it hides many of the underlying I/O details from an application. If an
application uses a BIO for its I/O it can transparently handle SSL connections, unencrypted network
connections and file I/O.
There are two type of BIO, a source/sink BIO and a filter BIO.
As its name implies a source/sink BIO is a source and/or sink of data, examples include a socket BIO
and a file BIO.
A filter BIO takes data from one BIO and passes it through to another, or the application. The data may
be left unmodified (for example a message digest BIO) or translated (for example an encryption BIO).
The effect of a filter BIO may change according to the I/O operation it is performing: for example an
encryption BIO will encrypt data if it is being written to and decrypt data if it is being read from.
BIOs can be joined together to form a chain (a single BIO is a chain with one component). A chain
normally consist of one source/sink BIO and one or more filter BIOs. Data read from or written to the
first BIO then traverses the chain to the end (normally a source/sink BIO).
SEE ALSO
BIO_ctrl(3)|BIO_ctrl(3), BIO_f_base64(3)|BIO_f_base64(3), BIO_f_buffer(3)|BIO_f_buffer(3),
BIO_f_cipher(3)|BIO_f_cipher(3), BIO_f_md(3)|BIO_f_md(3), BIO_f_null(3)|BIO_f_null(3),
BIO_f_ssl(3)|BIO_f_ssl(3), BIO_find_type(3)|BIO_find_type(3), BIO_new(3)|BIO_new(3),
BIO_new_bio_pair(3)|BIO_new_bio_pair(3), BIO_push(3)|BIO_push(3), BIO_read(3)|BIO_read(3),
BIO_s_accept(3)|BIO_s_accept(3), BIO_s_bio(3)|BIO_s_bio(3), BIO_s_connect(3)|BIO_s_connect(3),
BIO_s_fd(3)|BIO_s_fd(3), BIO_s_file(3)|BIO_s_file(3), BIO_s_mem(3)|BIO_s_mem(3),
BIO_s_null(3)|BIO_s_null(3), BIO_s_socket(3)|BIO_s_socket(3),
BIO_set_callback(3)|BIO_set_callback(3), BIO_should_retry(3)|BIO_should_retry(3)
05 July 2003 7
BIO control Crypto Library
BIO control
BIO_ctrl, BIO_callback_ctrl, BIO_ptr_ctrl, BIO_int_ctrl, BIO_reset, BIO_seek, BIO_tell, BIO_flush,
BIO_eof, BIO_set_close, BIO_get_close, BIO_pending, BIO_wpending, BIO_ctrl_pending,
BIO_ctrl_wpending, BIO_get_info_callback, BIO_set_info_callback - BIO control operations
SYNOPSIS
#include <openssl/bio.h>
typedef void bio_info_cb(BIO *b, int oper, const char *ptr, int arg1,
long arg2, long arg3);
DESCRIPTION
BIO_ctrl(), BIO_callback_ctrl(), BIO_ptr_ctrl() and BIO_int_ctrl() are BIO "control" operations taking
arguments of various types. These functions are not normally called directly, various macros are used
instead. The standard macros are described below, macros specific to a particular type of BIO are
described in the specific BIOs manual page as well as any special features of the standard calls.
BIO_reset() typically resets a BIO to some initial state, in the case of file related BIOs for example it
rewinds the file pointer to the start of the file.
BIO_seek() resets a file related BIO‘s (that is file descriptor and FILE BIOs) file position pointer to ofs
bytes from start of file.
BIO_tell() returns the current file position of a file related BIO.
BIO_flush() normally writes out any internally buffered data, in some cases it is used to signal EOF and
that no more data will be written.
BIO_eof() returns 1 if the BIO has read EOF, the precise meaning of "EOF" varies according to the BIO
type.
BIO_set_close() sets the BIO b close flag to flag. flag can take the value BIO_CLOSE or
BIO_NOCLOSE. Typically BIO_CLOSE is used in a source/sink BIO to indicate that the underlying
I/O stream should be closed when the BIO is freed.
BIO_get_close() returns the BIOs close flag.
BIO_pending(), BIO_ctrl_pending(), BIO_wpending() and BIO_ctrl_wpending() return the number of
pending characters in the BIOs read and write buffers. Not all BIOs support these calls.
BIO_ctrl_pending() and BIO_ctrl_wpending() return a size_t type and are functions, BIO_pending() and
BIO_wpending() are macros which call BIO_ctrl().
RETURN VALUES
BIO_reset() normally returns 1 for success and 0 or -1 for failure. File BIOs are an exception, they return
0 for success and -1 for failure.
8 05 July 2003
Crypto Library BIO control
BIO_seek() and BIO_tell() both return the current file position on success and -1 for failure, except file
BIOs which for BIO_seek() always return 0 for success and -1 for failure.
BIO_flush() returns 1 for success and 0 or -1 for failure.
BIO_eof() returns 1 if EOF has been reached 0 otherwise.
BIO_set_close() always returns 1.
BIO_get_close() returns the close flag value: BIO_CLOSE or BIO_NOCLOSE.
BIO_pending(), BIO_ctrl_pending(), BIO_wpending() and BIO_ctrl_wpending() return the amount of
pending data.
NOTES
BIO_flush(), because it can write data may return 0 or -1 indicating that the call should be retried later in
a similar manner to BIO_write(). The BIO_should_retry() call should be used and appropriate action
taken is the call fails.
The return values of BIO_pending() and BIO_wpending() may not reliably determine the amount of
pending data in all cases. For example in the case of a file BIO some data may be available in the FILE
structures internal buffers but it is not possible to determine this in a portably way. For other types of
BIO they may not be supported.
Filter BIOs if they do not internally handle a particular BIO_ctrl() operation usually pass the operation to
the next BIO in the chain. This often means there is no need to locate the required BIO for a particular
operation, it can be called on a chain and it will be automatically passed to the relevant BIO. However
this can cause unexpected results: for example no current filter BIOs implement BIO_seek(), but this
may still succeed if the chain ends in a FILE or file descriptor BIO.
Source/sink BIOs return an 0 if they do not recognize the BIO_ctrl() operation.
BUGS
Some of the return values are ambiguous and care should be taken. In particular a return value of 0 can
be returned if an operation is not supported, if an error occurred, if EOF has not been reached and in the
case of BIO_seek() on a file BIO for a successful operation.
SEE ALSO
TBA
05 July 2003 9
BIO chain traversal Crypto Library
#define BIO_TYPE_NONE 0
#define BIO_TYPE_MEM (1|0x0400)
#define BIO_TYPE_FILE (2|0x0400)
10 05 July 2003
Crypto Library BIO chain traversal
EXAMPLE
Traverse a chain looking for digest BIOs:
BIO *btmp;
btmp = in_bio; /* in_bio is chain to search through */
do {
btmp = BIO_find_type(btmp, BIO_TYPE_MD);
if(btmp == NULL) break; /* Not found */
/* btmp is a digest BIO, do something with it ...*/
...
btmp = BIO_next(btmp);
} while(btmp);
SEE ALSO
TBA
05 July 2003 11
BIO base64 Crypto Library
BIO base64
BIO_f_base64 - base64 BIO filter
SYNOPSIS
#include <openssl/bio.h>
#include <openssl/evp.h>
BIO_METHOD * BIO_f_base64(void);
DESCRIPTION
BIO_f_base64() returns the base64 BIO method. This is a filter BIO that base64 encodes any data
written through it and decodes any data read through it.
Base64 BIOs do not support BIO_gets() or BIO_puts().
BIO_flush() on a base64 BIO that is being written through is used to signal that no more data is to be
encoded: this is used to flush the final block through the BIO.
The flag BIO_FLAGS_BASE64_NO_NL can be set with BIO_set_flags() to encode the data all on one
line or expect the data to be all on one line.
NOTES
Because of the format of base64 encoding the end of the encoded block cannot always be reliably
determined.
RETURN VALUES
BIO_f_base64() returns the base64 BIO method.
EXAMPLES
Base64 encode the string "Hello World\n" and write the result to standard output:
BIO *bio, *b64;
char message[] = "Hello World \n";
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdout, BIO_NOCLOSE);
bio = BIO_push(b64, bio);
BIO_write(bio, message, strlen(message));
BIO_flush(bio);
BIO_free_all(bio);
Read Base64 encoded data from standard input and write the decoded data to standard output:
BIO *bio, *b64, bio_out;
char inbuf[512];
int inlen;
char message[] = "Hello World \n";
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdin, BIO_NOCLOSE);
bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
bio = BIO_push(b64, bio);
while((inlen = BIO_read(bio, inbuf, strlen(message))) > 0)
BIO_write(bio_out, inbuf, inlen);
BIO_free_all(bio);
BUGS
The ambiguity of EOF in base64 encoded data can cause additional data following the base64 encoded
block to be misinterpreted.
There should be some way of specifying a test that the BIO can perform to reliably determine EOF (for
example a MIME boundary).
12 05 July 2003
Crypto Library BIO base64
SEE ALSO
TBA
05 July 2003 13
BIO buffering Crypto Library
BIO buffering
BIO_f_buffer - buffering BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_f_buffer(void);
14 05 July 2003
Crypto Library BIO cipher
BIO cipher
BIO_f_cipher, BIO_set_cipher, BIO_get_cipher_status, BIO_get_cipher_ctx - cipher BIO filter
SYNOPSIS
#include <openssl/bio.h>
#include <openssl/evp.h>
BIO_METHOD * BIO_f_cipher(void);
void BIO_set_cipher(BIO *b,const EVP_CIPHER *cipher,
unsigned char *key, unsigned char *iv, int enc);
int BIO_get_cipher_status(BIO *b)
int BIO_get_cipher_ctx(BIO *b, EVP_CIPHER_CTX **pctx)
DESCRIPTION
BIO_f_cipher() returns the cipher BIO method. This is a filter BIO that encrypts any data written
through it, and decrypts any data read from it. It is a BIO wrapper for the cipher routines
EVP_CipherInit(), EVP_CipherUpdate() and EVP_CipherFinal().
Cipher BIOs do not support BIO_gets() or BIO_puts().
BIO_flush() on an encryption BIO that is being written through is used to signal that no more data is to
be encrypted: this is used to flush and possibly pad the final block through the BIO.
BIO_set_cipher() sets the cipher of BIO <b> to cipher using key key and IV iv. enc should be set to 1
for encryption and zero for decryption.
When reading from an encryption BIO the final block is automatically decrypted and checked when
EOF is detected. BIO_get_cipher_status() is a BIO_ctrl() macro which can be called to determine
whether the decryption operation was successful.
BIO_get_cipher_ctx() is a BIO_ctrl() macro which retrieves the internal BIO cipher context. The
retrieved context can be used in conjunction with the standard cipher routines to set it up. This is useful
when BIO_set_cipher() is not flexible enough for the applications needs.
NOTES
When encrypting BIO_flush() must be called to flush the final block through the BIO. If it is not then
the final block will fail a subsequent decrypt.
When decrypting an error on the final block is signalled by a zero return value from the read operation.
A successful decrypt followed by EOF will also return zero for the final read. BIO_get_cipher_status()
should be called to determine if the decrypt was successful.
As always, if BIO_gets() or BIO_puts() support is needed then it can be achieved by preceding the
cipher BIO with a buffering BIO.
RETURN VALUES
BIO_f_cipher() returns the cipher BIO method.
BIO_set_cipher() does not return a value.
BIO_get_cipher_status() returns 1 for a successful decrypt and 0 for failure.
BIO_get_cipher_ctx() currently always returns 1.
EXAMPLES
TBA
SEE ALSO
TBA
05 July 2003 15
BIO message digest Crypto Library
BIO_METHOD * BIO_f_md(void);
int BIO_set_md(BIO *b,EVP_MD *md);
int BIO_get_md(BIO *b,EVP_MD **mdp);
int BIO_get_md_ctx(BIO *b,EVP_MD_CTX **mdcp);
DESCRIPTION
BIO_f_md() returns the message digest BIO method. This is a filter BIO that digests any data passed
through it, it is a BIO wrapper for the digest routines EVP_DigestInit(), EVP_DigestUpdate() and
EVP_DigestFinal().
Any data written or read through a digest BIO using BIO_read() and BIO_write() is digested.
BIO_gets(), if its size parameter is large enough finishes the digest calculation and returns the digest
value. BIO_puts() is not supported.
BIO_reset() reinitialises a digest BIO.
BIO_set_md() sets the message digest of BIO b to md: this must be called to initialize a digest BIO
before any data is passed through it. It is a BIO_ctrl() macro.
BIO_get_md() places the a pointer to the digest BIOs digest method in mdp, it is a BIO_ctrl() macro.
BIO_get_md_ctx() returns the digest BIOs context into mdcp.
NOTES
The context returned by BIO_get_md_ctx() can be used in calls to EVP_DigestFinal() and also the
signature routines EVP_SignFinal() and EVP_VerifyFinal().
The context returned by BIO_get_md_ctx() is an internal context structure. Changes made to this context
will affect the digest BIO itself and the context pointer will become invalid when the digest BIO is freed.
After the digest has been retrieved from a digest BIO it must be reinitialized by calling BIO_reset(), or
BIO_set_md() before any more data is passed through it.
If an application needs to call BIO_gets() or BIO_puts() through a chain containing digest BIOs then this
can be done by prepending a buffering BIO.
RETURN VALUES
BIO_f_md() returns the digest BIO method.
BIO_set_md(), BIO_get_md() and BIO_md_ctx() return 1 for success and 0 for failure.
EXAMPLES
The following example creates a BIO chain containing an SHA1 and MD5 digest BIO and passes the
string "Hello World" through it. Error checking has been omitted for clarity.
BIO *bio, *mdtmp;
char message[] = "Hello World";
bio = BIO_new(BIO_s_null());
mdtmp = BIO_new(BIO_f_md());
BIO_set_md(mdtmp, EVP_sha1());
/* For BIO_push() we want to append the sink BIO and keep a note of
* the start of the chain.
*/
bio = BIO_push(mdtmp, bio);
mdtmp = BIO_new(BIO_f_md());
BIO_set_md(mdtmp, EVP_md5());
bio = BIO_push(mdtmp, bio);
/* Note: mdtmp can now be discarded */
BIO_write(bio, message, strlen(message));
16 05 July 2003
Crypto Library BIO message digest
This next example retrieves the message digests from a BIO chain and outputs them. This could be used
with the examples above.
BIO *mdtmp;
unsigned char mdbuf[EVP_MAX_MD_SIZE];
int mdlen;
int i;
mdtmp = bio; /* Assume bio has previously been set up */
do {
EVP_MD *md;
mdtmp = BIO_find_type(mdtmp, BIO_TYPE_MD);
if(!mdtmp) break;
BIO_get_md(mdtmp, &md);
printf("%s digest", OBJ_nid2sn(EVP_MD_type(md)));
mdlen = BIO_gets(mdtmp, mdbuf, EVP_MAX_MD_SIZE);
for(i = 0; i < mdlen; i++) printf(":%02X", mdbuf[i]);
printf("\n");
mdtmp = BIO_next(mdtmp);
} while(mdtmp);
BIO_free_all(bio);
BUGS
The lack of support for BIO_puts() and the non standard behaviour of BIO_gets() could be regarded as
anomalous. It could be argued that BIO_gets() and BIO_puts() should be passed to the next BIO in the
chain and digest the data passed through and that digests should be retrieved using a separate BIO_ctrl()
call.
SEE ALSO
TBA
05 July 2003 17
BIO null Crypto Library
BIO null
BIO_f_null - null filter
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_f_null(void);
DESCRIPTION
BIO_f_null() returns the null filter BIO method. This is a filter BIO that does nothing.
All requests to a null filter BIO are passed through to the next BIO in the chain: this means that a BIO
chain containing a null filter BIO behaves just as though the BIO was not there.
NOTES
As may be apparent a null filter BIO is not particularly useful.
RETURN VALUES
BIO_f_null() returns the null filter BIO method.
SEE ALSO
TBA
18 05 July 2003
Crypto Library BIO SSL
BIO SSL
BIO_f_ssl, BIO_set_ssl, BIO_get_ssl, BIO_set_ssl_mode, BIO_set_ssl_renegotiate_bytes,
BIO_get_num_renegotiates, BIO_set_ssl_renegotiate_timeout, BIO_new_ssl, BIO_new_ssl_connect,
BIO_new_buffer_ssl_connect, BIO_ssl_copy_session_id, BIO_ssl_shutdown - SSL BIO
SYNOPSIS
#include <openssl/bio.h>
#include <openssl/ssl.h>
BIO_METHOD *BIO_f_ssl(void);
05 July 2003 19
BIO SSL Crypto Library
BIO_ssl_shutdown() closes down an SSL connection on BIO chain bio. It does this by locating the SSL
BIO in the chain and calling SSL_shutdown() on its internal SSL pointer.
BIO_do_handshake() attempts to complete an SSL handshake on the supplied BIO and establish the SSL
connection. It returns 1 if the connection was established successfully. A zero or negative value is
returned if the connection could not be established, the call BIO_should_retry() should be used for non
blocking connect BIOs to determine if the call should be retried. If an SSL connection has already been
established this call has no effect.
NOTES
SSL BIOs are exceptional in that if the underlying transport is non blocking they can still request a retry
in exceptional circumstances. Specifically this will happen if a session renegotiation takes place during a
BIO_read() operation, one case where this happens is when SGC or step up occurs.
In OpenSSL 0.9.6 and later the SSL flag SSL_AUTO_RETRY can be set to disable this behaviour. That
is when this flag is set an SSL BIO using a blocking transport will never request a retry.
Since unknown BIO_ctrl() operations are sent through filter BIOs the servers name and port can be set
using BIO_set_host() on the BIO returned by BIO_new_ssl_connect() without having to locate the
connect BIO first.
Applications do not have to call BIO_do_handshake() but may wish to do so to separate the handshake
process from other I/O processing.
RETURN VALUES
TBA
EXAMPLE
This SSL/TLS client example, attempts to retrieve a page from an SSL/TLS web server. The I/O
routines are identical to those of the unencrypted example in BIO_s_connect(3)|BIO_s_connect(3).
BIO *sbio, *out;
int len;
char tmpbuf[1024];
SSL_CTX *ctx;
SSL *ssl;
ERR_load_crypto_strings();
ERR_load_SSL_strings();
OpenSSL_add_all_algorithms();
ctx = SSL_CTX_new(SSLv23_client_method());
/* We’d normally set some stuff like the verify paths and
* mode here because as things stand this will connect to
* any server whose certificate is signed by any CA.
*/
sbio = BIO_new_ssl_connect(ctx);
BIO_get_ssl(sbio, &ssl);
if(!ssl) {
fprintf(stderr, "Can’t locate SSL pointer\n");
/* whatever ... */
}
20 05 July 2003
Crypto Library BIO SSL
BIO_set_conn_hostname(sbio, "localhost:https");
if(BIO_do_handshake(sbio) <= 0) {
fprintf(stderr, "Error establishing SSL connection\n");
ERR_print_errors_fp(stderr);
/* whatever ... */
}
Here is a simple server example. It makes use of a buffering BIO to allow lines to be read from the SSL
BIO using BIO_gets. It creates a pseudo web page containing the actual request from a client and also
echoes the request to standard output.
BIO *sbio, *bbio, *acpt, *out;
int len;
char tmpbuf[1024];
SSL_CTX *ctx;
SSL *ssl;
ERR_load_crypto_strings();
ERR_load_SSL_strings();
OpenSSL_add_all_algorithms();
ctx = SSL_CTX_new(SSLv23_server_method());
if (!SSL_CTX_use_certificate_file(ctx,"server.pem",SSL_FILETYPE_PEM)
|| !SSL_CTX_use_PrivateKey_file(ctx,"server.pem",SSL_FILETYPE_PEM)
|| !SSL_CTX_check_private_key(ctx)) {
05 July 2003 21
BIO SSL Crypto Library
BIO_get_ssl(sbio, &ssl);
if(!ssl) {
fprintf(stderr, "Can’t locate SSL pointer\n");
/* whatever ... */
}
bbio = BIO_new(BIO_f_buffer());
/* Add to chain */
sbio = BIO_push(bbio, sbio);
acpt=BIO_new_accept("4433");
BIO_set_accept_bios(acpt,sbio);
sbio = BIO_pop(acpt);
BIO_free_all(acpt);
if(BIO_do_handshake(sbio) <= 0) {
fprintf(stderr, "Error in SSL handshake\n");
ERR_print_errors_fp(stderr);
return 0;
}
22 05 July 2003
Crypto Library BIO SSL
for(;;) {
len = BIO_gets(sbio, tmpbuf, 1024);
if(len <= 0) break;
BIO_write(sbio, tmpbuf, len);
BIO_write(out, tmpbuf, len);
/* Look for blank line signifying end of headers*/
if((tmpbuf[0] == ’\r’) || (tmpbuf[0] == ’\n’)) break;
}
BIO_puts(sbio, "--------------------------------------------------\r\n");
BIO_puts(sbio, "</pre>\r\n");
BIO_free_all(sbio);
SEE ALSO
TBA
05 July 2003 23
BIO allocation Crypto Library
BIO allocation
BIO_new, BIO_set, BIO_free, BIO_vfree, BIO_free_all - BIO allocation and freeing functions
SYNOPSIS
#include <openssl/bio.h>
24 05 July 2003
Crypto Library BIO chain
BIO chain
BIO_push, BIO_pop - add and remove BIOs from a chain.
SYNOPSIS
#include <openssl/bio.h>
is made then the new chain will be b64-chain. After making the calls
BIO_push(md2, b64);
BIO_push(md1, md2);
the new chain is md1-md2-b64-f. Data written to md1 will be digested by md1 and md2, base64
encoded and written to f.
It should be noted that reading causes data to pass in the reverse direction, that is data is read from f,
base64 decoded and digested by md1 and md2. If the call:
BIO_pop(md2);
The call will return b64 and the new chain will be md1-b64-f data can be written to md1 as before.
RETURN VALUES
BIO_push() returns the end of the chain, b.
BIO_pop() returns the next BIO in the chain, or NULL if there is no next BIO.
SEE ALSO
TBA
05 July 2003 25
BIO I/O Crypto Library
BIO I/O
BIO_read, BIO_write, BIO_gets, BIO_puts - BIO I/O functions
SYNOPSIS
#include <openssl/bio.h>
26 05 July 2003
Crypto Library BIO callback
BIO callback
BIO_set_callback, BIO_get_callback, BIO_set_callback_arg, BIO_get_callback_arg,
BIO_debug_callback - BIO callback functions
SYNOPSIS
#include <openssl/bio.h>
05 July 2003 27
BIO callback Crypto Library
EXAMPLE
The BIO_debug_callback() function is a good example, its source is in crypto/bio/bio_cb.c
SEE ALSO
TBA
28 05 July 2003
Crypto Library BIO retry
BIO retry
BIO_should_retry, BIO_should_read, BIO_should_write, BIO_should_io_special, BIO_retry_type,
BIO_should_retry, BIO_get_retry_BIO, BIO_get_retry_reason - BIO retry functions
SYNOPSIS
#include <openssl/bio.h>
05 July 2003 29
BIO retry Crypto Library
For example if the cause is ultimately a socket and BIO_should_read() is true then a call to select() may
be made to wait until data is available and then retry the BIO operation. By combining the retry
conditions of several non blocking BIOs in a single select() call it is possible to service several BIOs in a
single thread, though the performance may be poor if SSL BIOs are present because long delays can
occur during the initial handshake process.
It is possible for a BIO to block indefinitely if the underlying I/O structure cannot process or return any
data. This depends on the behaviour of the platforms I/O functions. This is often not desirable: one
solution is to use non blocking I/O and use a timeout on the select() (or equivalent) call.
BUGS
The OpenSSL ASN1 functions cannot gracefully deal with non blocking I/O: that is they cannot retry
after a partial read or write. This is usually worked around by only passing the relevant data to ASN1
functions when the entire structure can be read or written.
SEE ALSO
TBA
30 05 July 2003
Crypto Library BIO accept
BIO accept
BIO_s_accept, BIO_set_accept_port, BIO_get_accept_port, BIO_set_nbio_accept,
BIO_set_accept_bios, BIO_set_bind_mode, BIO_get_bind_mode, BIO_do_accept - accept BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD *BIO_s_accept(void);
#define BIO_BIND_NORMAL 0
#define BIO_BIND_REUSEADDR_IF_UNUSED 1
#define BIO_BIND_REUSEADDR 2
05 July 2003 31
BIO accept Crypto Library
BIO_BIND_REUSEADDR.
BIO_do_accept() serves two functions. When it is first called, after the accept BIO has been setup, it will
attempt to create the accept socket and bind an address to it. Second and subsequent calls to
BIO_do_accept() will await an incoming connection, or request a retry in non blocking mode.
NOTES
When an accept BIO is at the end of a chain it will await an incoming connection before processing I/O
calls. When an accept BIO is not at then end of a chain it passes I/O calls to the next BIO in the chain.
When a connection is established a new socket BIO is created for the connection and appended to the
chain. That is the chain is now accept-socket. This effectively means that attempting I/O on an initial
accept socket will await an incoming connection then perform I/O on it.
If any additional BIOs have been set using BIO_set_accept_bios() then they are placed between the
socket and the accept BIO, that is the chain will be accept-otherbios-socket.
If a server wishes to process multiple connections (as is normally the case) then the accept BIO must be
made available for further incoming connections. This can be done by waiting for a connection and then
calling:
connection = BIO_pop(accept);
After this call connection will contain a BIO for the recently established connection and accept will
now be a single BIO again which can be used to await further incoming connections. If no further
connections will be accepted the accept can be freed using BIO_free().
If only a single connection will be processed it is possible to perform I/O using the accept BIO itself.
This is often undesirable however because the accept BIO will still accept additional incoming
connections. This can be resolved by using BIO_pop() (see above) and freeing up the accept BIO after
the initial connection.
If the underlying accept socket is non-blocking and BIO_do_accept() is called to await an incoming
connection it is possible for BIO_should_io_special() with the reason BIO_RR_ACCEPT. If this
happens then it is an indication that an accept attempt would block: the application should take
appropriate action to wait until the underlying socket has accepted a connection and retry the call.
BIO_set_accept_port(), BIO_get_accept_port(), BIO_set_nbio_accept(), BIO_set_accept_bios(),
BIO_set_bind_mode(), BIO_get_bind_mode() and BIO_do_accept() are macros.
RETURN VALUES
TBA
EXAMPLE
This example accepts two connections on port 4444, sends messages down each and finally closes both
down.
BIO *abio, *cbio, *cbio2;
ERR_load_crypto_strings();
abio = BIO_new_accept("4444");
32 05 July 2003
Crypto Library BIO accept
05 July 2003 33
BIO pair Crypto Library
BIO pair
BIO_s_bio, BIO_make_bio_pair, BIO_destroy_bio_pair, BIO_shutdown_wr, BIO_set_write_buf_size,
BIO_get_write_buf_size, BIO_new_bio_pair, BIO_get_write_guarantee, BIO_ctrl_get_write_guarantee,
BIO_get_read_request, BIO_ctrl_get_read_request, BIO_ctrl_reset_read_request - BIO pair BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD *BIO_s_bio(void);
34 05 July 2003
Crypto Library BIO pair
called.
BIO_get_write_guarantee() and BIO_ctrl_get_write_guarantee() return the maximum length of data that
can be currently written to the BIO. Writes larger than this value will return a value from BIO_write()
less than the amount requested or if the buffer is full request a retry. BIO_ctrl_get_write_guarantee() is a
function whereas BIO_get_write_guarantee() is a macro.
BIO_get_read_request() and BIO_ctrl_get_read_request() return the amount of data requested, or the
buffer size if it is less, if the last read attempt at the other half of the BIO pair failed due to an empty
buffer. This can be used to determine how much data should be written to the BIO so the next read will
succeed: this is most useful in TLS/SSL applications where the amount of data read is usually
meaningful rather than just a buffer size. After a successful read this call will return zero. It also will
return zero once new data has been written satisfying the read request or part of it. Note that
BIO_get_read_request() never returns an amount larger than that returned by
BIO_get_write_guarantee().
BIO_ctrl_reset_read_request() can also be used to reset the value returned by BIO_get_read_request() to
zero.
NOTES
Both halves of a BIO pair should be freed. That is even if one half is implicit freed due to a
BIO_free_all() or SSL_free() call the other half needs to be freed.
When used in bidirectional applications (such as TLS/SSL) care should be taken to flush any data in the
write buffer. This can be done by calling BIO_pending() on the other half of the pair and, if any data is
pending, reading it and sending it to the underlying transport. This must be done before any normal
processing (such as calling select() ) due to a request and BIO_should_read() being true.
To see why this is important consider a case where a request is sent using BIO_write() and a response
read with BIO_read(), this can occur during an TLS/SSL handshake for example. BIO_write() will
succeed and place data in the write buffer. BIO_read() will initially fail and BIO_should_read() will be
true. If the application then waits for data to be available on the underlying transport before flushing the
write buffer it will never succeed because the request was never sent!
RETURN VALUES
BIO_new_bio_pair() returns 1 on success, with the new BIOs available in bio1 and bio2, or 0 on failure,
with NULL pointers stored into the locations for bio1 and bio2. Check the error stack for more
information.
[XXXXX: More return values need to be added here]
EXAMPLE
The BIO pair can be used to have full control over the network access of an application. The application
can call select() on the socket as required without having to go through the SSL-interface.
BIO *internal_bio, *network_bio;
...
BIO_new_bio_pair(internal_bio, 0, network_bio, 0);
SSL_set_bio(ssl, internal_bio, internal_bio);
SSL_operations();
...
application | TLS-engine
| |
+----------> SSL_operations()
| /\ ||
| || \/
| BIO-pair (internal_bio)
+----------< BIO-pair (network_bio)
| |
socket |
...
SSL_free(ssl); /* implicitly frees internal_bio */
BIO_free(network_bio);
...
05 July 2003 35
BIO pair Crypto Library
As the BIO pair will only buffer the data and never directly access the connection, it behaves
non-blocking and will return as soon as the write buffer is full or the read buffer is drained. Then the
application has to flush the write buffer and/or fill the read buffer.
Use the BIO_ctrl_pending(), to find out whether data is buffered in the BIO and must be transfered to
the network. Use BIO_ctrl_get_read_request() to find out, how many bytes must be written into the
buffer before the SSL_operation() can successfully be continued.
WARNING
As the data is buffered, SSL_operation() may return with a ERROR_SSL_WANT_READ condition, but
there is still data in the write buffer. An application must not rely on the error value of SSL_operation()
but must assure that the write buffer is always flushed first. Otherwise a deadlock may occur as the peer
might be waiting for the data before being able to continue.
SEE ALSO
SSL_set_bio(3)|SSL_set_bio(3), ssl(3)|ssl(3), bio(3)|bio(3), BIO_should_retry(3)|BIO_should_retry(3),
BIO_read(3)|BIO_read(3)
36 05 July 2003
Crypto Library BIO connect
BIO connect
BIO_s_connect, BIO_set_conn_hostname, BIO_set_conn_port, BIO_set_conn_ip,
BIO_set_conn_int_port, BIO_get_conn_hostname, BIO_get_conn_port, BIO_get_conn_ip,
BIO_get_conn_int_port, BIO_set_nbio, BIO_do_connect - connect BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_s_connect(void);
05 July 2003 37
BIO connect Crypto Library
BIO_do_connect() attempts to connect the supplied BIO. It returns 1 if the connection was established
successfully. A zero or negative value is returned if the connection could not be established, the call
BIO_should_retry() should be used for non blocking connect BIOs to determine if the call should be
retried.
NOTES
If blocking I/O is set then a non positive return value from any I/O call is caused by an error condition,
although a zero return will normally mean that the connection was closed.
If the port name is supplied as part of the host name then this will override any value set with
BIO_set_conn_port(). This may be undesirable if the application does not wish to allow connection to
arbitrary ports. This can be avoided by checking for the presence of the ‘:’ character in the passed
hostname and either indicating an error or truncating the string at that point.
The values returned by BIO_get_conn_hostname(), BIO_get_conn_port(), BIO_get_conn_ip() and
BIO_get_conn_int_port() are updated when a connection attempt is made. Before any connection
attempt the values returned are those set by the application itself.
Applications do not have to call BIO_do_connect() but may wish to do so to separate the connection
process from other I/O processing.
If non blocking I/O is set then retries will be requested as appropriate.
It addition to BIO_should_read() and BIO_should_write() it is also possible for
BIO_should_io_special() to be true during the initial connection process with the reason
BIO_RR_CONNECT. If this is returned then this is an indication that a connection attempt would block,
the application should then take appropriate action to wait until the underlying socket has connected and
retry the call.
BIO_set_conn_hostname(), BIO_set_conn_port(), BIO_set_conn_ip(), BIO_set_conn_int_port(),
BIO_get_conn_hostname(), BIO_get_conn_port(), BIO_get_conn_ip(), BIO_get_conn_int_port(),
BIO_set_nbio() and BIO_do_connect() are macros.
RETURN VALUES
BIO_s_connect() returns the connect BIO method.
BIO_get_fd() returns the socket or -1 if the BIO has not been initialized.
BIO_set_conn_hostname(), BIO_set_conn_port(), BIO_set_conn_ip() and BIO_set_conn_int_port()
always return 1.
BIO_get_conn_hostname() returns the connected hostname or NULL is none was set.
BIO_get_conn_port() returns a string representing the connected port or NULL if not set.
BIO_get_conn_ip() returns a pointer to the connected IP address in binary form or all zeros if not set.
BIO_get_conn_int_port() returns the connected port or 0 if none was set.
BIO_set_nbio() always returns 1.
BIO_do_connect() returns 1 if the connection was successfully established and 0 or -1 if the connection
failed.
EXAMPLE
This is example connects to a webserver on the local host and attempts to retrieve a page and copy the
result to standard output.
38 05 July 2003
Crypto Library BIO connect
}
BIO_free(cbio);
BIO_free(out);
SEE ALSO
TBA
05 July 2003 39
BIO file decscriptor Crypto Library
BIO_METHOD * BIO_s_fd(void);
40 05 July 2003
Crypto Library BIO file
BIO file
BIO_s_file, BIO_new_file, BIO_new_fp, BIO_set_fp, BIO_get_fp, BIO_read_filename,
BIO_write_filename, BIO_append_filename, BIO_rw_filename - BIO file
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_s_file(void);
BIO *BIO_new_file(const char *filename, const char *mode);
BIO *BIO_new_fp(FILE *stream, int flags);
Alternative technique:
BIO *bio_out;
bio_out = BIO_new(BIO_s_file());
if(bio_out == NULL) /* Error ... */
if(!BIO_set_fp(bio_out, stdout, BIO_NOCLOSE)) /* Error ... */
BIO_printf(bio_out, "Hello World\n");
05 July 2003 41
BIO file Crypto Library
Write to a file:
BIO *out;
out = BIO_new_file("filename.txt", "w");
if(!out) /* Error occurred */
BIO_printf(out, "Hello World\n");
BIO_free(out);
Alternative technique:
BIO *out;
out = BIO_new(BIO_s_file());
if(out == NULL) /* Error ... */
if(!BIO_write_filename(out, "filename.txt")) /* Error ... */
BIO_printf(out, "Hello World\n");
BIO_free(out);
RETURN VALUES
BIO_s_file() returns the file BIO method.
BIO_new_file() and BIO_new_fp() return a file BIO or NULL if an error occurred.
BIO_set_fp() and BIO_get_fp() return 1 for success or 0 for failure (although the current implementation
never return 0).
BIO_seek() returns the same value as the underlying fseek() function: 0 for success or -1 for failure.
BIO_tell() returns the current file position.
BIO_read_filename(), BIO_write_filename(), BIO_append_filename() and BIO_rw_filename() return 1
for success or 0 for failure.
BUGS
BIO_reset() and BIO_seek() are implemented using fseek() on the underlying stream. The return value
for fseek() is 0 for success or -1 if an error occurred this differs from other types of BIO which will
typically return 1 for success and a non positive value if an error occurred.
SEE ALSO
BIO_seek(3)|BIO_seek(3), BIO_tell(3)|BIO_tell(3), BIO_reset(3)|BIO_reset(3),
BIO_flush(3)|BIO_flush(3), BIO_read(3)|BIO_read(3), BIO_write(3)|BIO_write(3),
BIO_puts(3)|BIO_puts(3), BIO_gets(3)|BIO_gets(3), BIO_printf(3)|BIO_printf(3),
BIO_set_close(3)|BIO_set_close(3), BIO_get_close(3)|BIO_get_close(3)
42 05 July 2003
Crypto Library BIO memory
BIO memory
BIO_s_mem, BIO_set_mem_eof_return, BIO_get_mem_data, BIO_set_mem_buf, BIO_get_mem_ptr,
BIO_new_mem_buf - memory BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_s_mem(void);
BIO_set_mem_eof_return(BIO *b,int v)
long BIO_get_mem_data(BIO *b, char **pp)
BIO_set_mem_buf(BIO *b,BUF_MEM *bm,int c)
BIO_get_mem_ptr(BIO *b,BUF_MEM **pp)
05 July 2003 43
BIO memory Crypto Library
EXAMPLE
Create a memory BIO and write some data to it:
BIO *mem = BIO_new(BIO_s_mem());
BIO_puts(mem, "Hello World\n");
Extract the BUF_MEM structure from a memory BIO and then free up the BIO:
BUF_MEM *bptr;
BIO_get_mem_ptr(mem, &bptr);
BIO_set_close(mem, BIO_NOCLOSE); /* So BIO_free() leaves BUF_MEM alone */
BIO_free(mem);
SEE ALSO
TBA
44 05 July 2003
Crypto Library BIO null
BIO null
BIO_s_null - null data sink
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD * BIO_s_null(void);
DESCRIPTION
BIO_s_null() returns the null sink BIO method. Data written to the null sink is discarded, reads return
EOF.
NOTES
A null sink BIO behaves in a similar manner to the Unix /dev/null device.
A null bio can be placed on the end of a chain to discard any data passed through it.
A null sink is useful if, for example, an application wishes to digest some data by writing through a
digest bio but not send the digested data anywhere. Since a BIO chain must normally include a
source/sink BIO this can be achieved by adding a null sink BIO to the end of the chain
RETURN VALUES
BIO_s_null() returns the null sink BIO method.
SEE ALSO
TBA
05 July 2003 45
BIO socket Crypto Library
BIO socket
BIO_s_socket, BIO_new_socket - socket BIO
SYNOPSIS
#include <openssl/bio.h>
BIO_METHOD *BIO_s_socket(void);
46 05 July 2003
Crypto Library Blowfish encryption
Blowfish encryption
blowfish, BF_set_key, BF_encrypt, BF_decrypt, BF_ecb_encrypt, BF_cbc_encrypt, BF_cfb64_encrypt,
BF_ofb64_encrypt, BF_options - Blowfish encryption
SYNOPSIS
#include <openssl/blowfish.h>
05 July 2003 47
Blowfish encryption Crypto Library
BF_ecb_encrypt(). If you still want to use these functions, you should be aware that they take each
32-bit chunk in host-byte order, which is little-endian on little-endian platforms and big-endian on
big-endian ones.
RETURN VALUES
None of the functions presented here return any value.
NOTE
Applications should use the higher level functions EVP_EncryptInit(3)|EVP_EncryptInit(3) etc. instead
of calling the blowfish functions directly.
SEE ALSO
des_modes(7)|des_modes(7)
HISTORY
The Blowfish functions are available in all versions of SSLeay and OpenSSL.
48 05 July 2003
Crypto Library BN multiprecision integer
BN multiprecision integer
BN - multiprecision integer arithmetics
SYNOPSIS
#include <openssl/bn.h>
BIGNUM *BN_new(void);
void BN_free(BIGNUM *a);
void BN_init(BIGNUM *);
void BN_clear(BIGNUM *a);
void BN_clear_free(BIGNUM *a);
BN_CTX *BN_CTX_new(void);
void BN_CTX_init(BN_CTX *c);
void BN_CTX_free(BN_CTX *c);
05 July 2003 49
BN multiprecision integer Crypto Library
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_init(BN_RECP_CTX *recp);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *a, BIGNUM *b,
BN_RECP_CTX *recp, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_new(void);
void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *m, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
int BN_mod_mul_montgomery(BIGNUM *r, BIGNUM *a, BIGNUM *b,
BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_from_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
int BN_to_montgomery(BIGNUM *r, BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
50 05 July 2003
Crypto Library BN multiprecision integer
DESCRIPTION
This library performs arithmetic operations on integers of arbitrary size. It was written for use in public
key cryptography, such as RSA and Diffie-Hellman.
It uses dynamic memory allocation for storing its data structures. That means that there is no limit on the
size of the numbers manipulated by these functions, but return values must always be checked in case a
memory allocation error has occurred.
The basic object in this library is a BIGNUM. It is used to hold a single large integer. This type should
be considered opaque and fields should not be modified or accessed directly.
The creation of BIGNUM objects is described in BN_new(3)|BN_new(3); BN_add(3)|BN_add(3)
describes most of the arithmetic operations. Comparison is described in BN_cmp(3)|BN_cmp(3);
BN_zero(3)|BN_zero(3) describes certain assignments, BN_rand(3)|BN_rand(3) the generation of
random numbers, BN_generate_prime(3)|BN_generate_prime(3) deals with prime numbers and
BN_set_bit(3)|BN_set_bit(3) with bit operations. The conversion of BIGNUMs to external formats is
described in BN_bn2bin(3)|BN_bn2bin(3).
SEE ALSO
bn_internal(3)|bn_internal(3), dh(3)|dh(3), err(3)|err(3), rand(3)|rand(3), rsa(3)|rsa(3),
BN_new(3)|BN_new(3), BN_CTX_new(3)|BN_CTX_new(3), BN_copy(3)|BN_copy(3),
BN_swap(3)|BN_swap(3), BN_num_bytes(3)|BN_num_bytes(3), BN_add(3)|BN_add(3),
BN_add_word(3)|BN_add_word(3), BN_cmp(3)|BN_cmp(3), BN_zero(3)|BN_zero(3),
BN_rand(3)|BN_rand(3), BN_generate_prime(3)|BN_generate_prime(3), BN_set_bit(3)|BN_set_bit(3),
BN_bn2bin(3)|BN_bn2bin(3), BN_mod_inverse(3)|BN_mod_inverse(3),
BN_mod_mul_reciprocal(3)|BN_mod_mul_reciprocal(3),
BN_mod_mul_montgomery(3)|BN_mod_mul_montgomery(3)
05 July 2003 51
BIGNUM operations Crypto Library
BIGNUM operations
BN_add, BN_sub, BN_mul, BN_sqr, BN_div, BN_mod, BN_nnmod, BN_mod_add, BN_mod_sub,
BN_mod_mul, BN_mod_sqr, BN_exp, BN_mod_exp, BN_gcd - arithmetic operations on BIGNUMs
SYNOPSIS
#include <openssl/bn.h>
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *a, const BIGNUM *d,
BN_CTX *ctx);
int BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_nnmod(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_add(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sqr(BIGNUM *r, BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
52 05 July 2003
Crypto Library BIGNUM operations
05 July 2003 53
BIGNUM functions Crypto Library
BIGNUM functions
BN_add_word, BN_sub_word, BN_mul_word, BN_div_word, BN_mod_word - arithmetic functions on
BIGNUMs with integers
SYNOPSIS
#include <openssl/bn.h>
54 05 July 2003
Crypto Library BIGNUM conversion
BIGNUM conversion
BN_bn2bin, BN_bin2bn, BN_bn2hex, BN_bn2dec, BN_hex2bn, BN_dec2bn, BN_print, BN_print_fp,
BN_bn2mpi, BN_mpi2bn - format conversions
SYNOPSIS
#include <openssl/bn.h>
05 July 2003 55
BIGNUM conversion Crypto Library
HISTORY
BN_bn2bin(), BN_bin2bn(), BN_print_fp() and BN_print() are available in all versions of SSLeay and
OpenSSL.
BN_bn2hex(), BN_bn2dec(), BN_hex2bn(), BN_dec2bn(), BN_bn2mpi() and BN_mpi2bn() were added
in SSLeay 0.9.0.
56 05 July 2003
Crypto Library BIGNUM compare and test
05 July 2003 57
BIGNUM copy Crypto Library
BIGNUM copy
BN_copy, BN_dup - copy BIGNUMs
SYNOPSIS
#include <openssl/bn.h>
58 05 July 2003
Crypto Library BN_CTX allocation
BN_CTX allocation
BN_CTX_new, BN_CTX_init, BN_CTX_free - allocate and free BN_CTX structures
SYNOPSIS
#include <openssl/bn.h>
BN_CTX *BN_CTX_new(void);
RETURN VALUES
BN_CTX_new() returns a pointer to the BN_CTX. If the allocation fails, it returns NULL and sets an
error code that can be obtained by ERR_get_error(3)|ERR_get_error(3).
BN_CTX_init() and BN_CTX_free() have no return values.
SEE ALSO
bn(3)|bn(3), ERR_get_error(3)|ERR_get_error(3), BN_add(3)|BN_add(3),
BN_CTX_start(3)|BN_CTX_start(3)
HISTORY
BN_CTX_new() and BN_CTX_free() are available in all versions on SSLeay and OpenSSL.
BN_CTX_init() was added in SSLeay 0.9.1b.
05 July 2003 59
BIGNUM temp Crypto Library
BIGNUM temp
BN_CTX_start, BN_CTX_get, BN_CTX_end - use temporary BIGNUM variables
SYNOPSIS
#include <openssl/bn.h>
SEE ALSO
BN_CTX_new(3)|BN_CTX_new(3)
HISTORY
BN_CTX_start(), BN_CTX_get() and BN_CTX_end() were added in OpenSSL 0.9.5.
60 05 July 2003
Crypto Library BIGNUM primes
BIGNUM primes
BN_generate_prime, BN_is_prime, BN_is_prime_fasttest - generate primes and test for primality
SYNOPSIS
#include <openssl/bn.h>
callback(0, i, cb_arg) is called after generating the i-th potential prime number.
While the number is being tested for primality, callback(1, j, cb_arg) is called as described below.
The prime may have to fulfill additional requirements for use in Diffie-Hellman key exchange:
If add is not NULL, the prime will fulfill the condition p % add == rem (p % add == 1 if rem ==
NULL) in order to suit a given generator.
If safe is true, it will be a safe prime (i.e. a prime p so that (p-1)/2 is also prime).
The PRNG must be seeded prior to calling BN_generate_prime(). The prime number generation has a
negligible error probability.
BN_is_prime() and BN_is_prime_fasttest() test if the number a is prime. The following tests are
performed until one of them shows that a is composite; if a passes all these tests, it is considered prime.
BN_is_prime_fasttest(), when called with do_trial_division == 1, first attempts trial division by a
number of small primes; if no divisors are found by this test and callback is not NULL, callback(1, -1,
cb_arg) is called. If do_trial_division == 0, this test is skipped.
Both BN_is_prime() and BN_is_prime_fasttest() perform a Miller-Rabin probabilistic primality test with
checks iterations. If checks == BN_prime_checks, a number of iterations is used that yields a false
positive rate of at most 2^-80 for random input.
If callback is not NULL, callback(1, j, cb_arg) is called after the j-th iteration (j = 0, 1, ...). ctx is a
pre-allocated BN_CTX (to save the overhead of allocating and freeing the structure in a loop), or
NULL.
RETURN VALUES
BN_generate_prime() returns the prime number on success, NULL otherwise.
BN_is_prime() returns 0 if the number is composite, 1 if it is prime with an error probability of less than
0.25^checks, and -1 on error.
The error codes can be obtained by ERR_get_error(3)|ERR_get_error(3).
SEE ALSO
bn(3)|bn(3), ERR_get_error(3)|ERR_get_error(3), rand(3)|rand(3)
HISTORY
The cb_arg arguments to BN_generate_prime() and to BN_is_prime() were added in SSLeay 0.9.0. The
ret argument to BN_generate_prime() was added in SSLeay 0.9.1. BN_is_prime_fasttest() was added in
OpenSSL 0.9.5.
05 July 2003 61
BIGNUM internals Crypto Library
BIGNUM internals
bn_mul_words, bn_mul_add_words, bn_sqr_words, bn_div_words, bn_add_words, bn_sub_words,
bn_mul_comba4, bn_mul_comba8, bn_sqr_comba4, bn_sqr_comba8, bn_cmp_words, bn_mul_normal,
bn_mul_low_normal, bn_mul_recursive, bn_mul_part_recursive, bn_mul_low_recursive, bn_mul_high,
bn_sqr_normal, bn_sqr_recursive, bn_expand, bn_wexpand, bn_expand2, bn_fix_top, bn_check_top,
bn_print, bn_dump, bn_set_max, bn_set_high, bn_set_low - BIGNUM library internal functions
SYNOPSIS
BN_ULONG bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w);
BN_ULONG bn_mul_add_words(BN_ULONG *rp, BN_ULONG *ap, int num,
BN_ULONG w);
void bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num);
BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d);
BN_ULONG bn_add_words(BN_ULONG *rp, BN_ULONG *ap, BN_ULONG *bp,
int num);
BN_ULONG bn_sub_words(BN_ULONG *rp, BN_ULONG *ap, BN_ULONG *bp,
int num);
62 05 July 2003
Crypto Library BIGNUM internals
The big number is stored in d, a malloc()ed array of BN_ULONGs, least significant first. A
BN_ULONG can be either 16, 32 or 64 bits in size (BITS2), depending on the ‘number of bits’
specified in openssl/bn.h.
max is the size of the d array that has been allocated. top is the ‘last’ entry being used, so for a value of
4, bn.d[0]=4 and bn.top=1. neg is 1 if the number is negative. When a BIGNUM is 0, the d field can be
NULL and top == 0.
Various routines in this library require the use of temporary BIGNUM variables during their execution.
Since dynamic memory allocation to create BIGNUMs is rather expensive when used in conjunction
with repeated subroutine calls, the BN_CTX structure is used. This structure contains BN_CTX_NUM
BIGNUMs, see BN_CTX_start(3)|BN_CTX_start(3).
Low-level arithmetic operations
These functions are implemented in C and for several platforms in assembly language:
bn_mul_words(rp, ap, num, w) operates on the num word arrays rp and ap. It computes ap * w,
places the result in rp, and returns the high word (carry).
bn_mul_add_words(rp, ap, num, w) operates on the num word arrays rp and ap. It computes ap * w +
rp, places the result in rp, and returns the high word (carry).
bn_sqr_words(rp, ap, n) operates on the num word array ap and the 2*num word array ap. It computes
ap * ap word-wise, and places the low and high bytes of the result in rp.
bn_div_words(h, l, d) divides the two word number (h,l) by d and returns the result.
bn_add_words(rp, ap, bp, num) operates on the num word arrays ap, bp and rp. It computes ap + bp,
places the result in rp, and returns the high word (carry).
bn_sub_words(rp, ap, bp, num) operates on the num word arrays ap, bp and rp. It computes ap - bp,
places the result in rp, and returns the carry (1 if bp ap, 0 otherwise).
bn_mul_comba4(r, a, b) operates on the 4 word arrays a and b and the 8 word array r. It computes a*b
and places the result in r.
bn_mul_comba8(r, a, b) operates on the 8 word arrays a and b and the 16 word array r. It computes
a*b and places the result in r.
bn_sqr_comba4(r, a, b) operates on the 4 word arrays a and b and the 8 word array r.
bn_sqr_comba8(r, a, b) operates on the 8 word arrays a and b and the 16 word array r.
The following functions are implemented in C:
bn_cmp_words(a, b, n) operates on the n word arrays a and b. It returns 1, 0 and -1 if a is greater than,
equal and less than b.
bn_mul_normal(r, a, na, b, nb) operates on the na word array a, the nb word array b and the na+nb
word array r. It computes a*b and places the result in r.
bn_mul_low_normal(r, a, b, n) operates on the n word arrays r, a and b. It computes the n low words
of a*b and places the result in r.
bn_mul_recursive(r, a, b, n2, dna, dnb, t) operates on the word arrays a and b of length n2+dna and
n2+dnb (dna and dnb are currently allowed to be 0 or negative) and the 2*n2 word arrays r and t. n2
must be a power of 2. It computes a*b and places the result in r.
bn_mul_part_recursive(r, a, b, n, tna, tnb, tmp) operates on the word arrays a and b of length n+tna
and n+tnb and the 4*n word arrays r and tmp.
bn_mul_low_recursive(r, a, b, n2, tmp) operates on the n2 word arrays r and tmp and the n2/2 word
arrays a and b.
bn_mul_high(r, a, b, l, n2, tmp) operates on the n2 word arrays r, a, b and l (?) and the 3*n2 word array
tmp.
BN_mul() calls bn_mul_normal(), or an optimized implementation if the factors have the same size:
bn_mul_comba8() is used if they are 8 words long, bn_mul_recursive() if they are larger than
BN_MULL_SIZE_NORMAL and the size is an exact multiple of the word size, and
bn_mul_part_recursive() for others that are larger than BN_MULL_SIZE_NORMAL.
05 July 2003 63
BIGNUM internals Crypto Library
bn_sqr_normal(r, a, n, tmp) operates on the n word array a and the 2*n word arrays tmp and r.
The implementations use the following macros which, depending on the architecture, may use "long
long" C operations or inline assembler. They are defined in bn_lcl.h.
mul(r, a, w, c) computes w*a+c and places the low word of the result in r and the high word in c.
mul_add(r, a, w, c) computes w*a+r+c and places the low word of the result in r and the high word in c.
sqr(r0, r1, a) computes a*a and places the low word of the result in r0 and the high word in r1.
Size changes
bn_expand() ensures that b has enough space for a bits bit number. bn_wexpand() ensures that b has
enough space for an n word number. If the number has to be expanded, both macros call bn_expand2(),
which allocates a new d array and copies the data. They return NULL on error, b otherwise.
The bn_fix_top() macro reduces a-top to point to the most significant non-zero word when a has shrunk.
Debugging
bn_check_top() verifies that ((a)-top = 0 && (a)-top <= (a)->max). A violation will cause the
program to abort.
bn_print() prints a to stderr. bn_dump() prints n words at d (in reverse order, i.e. most significant word
first) to stderr.
bn_set_max() makes a a static number with a max of its current size. This is used by bn_set_low() and
bn_set_high() to make r a read-only BIGNUM that contains the n low or high words of a.
If BN_DEBUG is not defined, bn_check_top(), bn_print(), bn_dump() and bn_set_max() are defined as
empty macros.
SEE ALSO
bn(3)|bn(3)
64 05 July 2003
Crypto Library BIGNUM inverse
BIGNUM inverse
BN_mod_inverse - compute inverse modulo n
SYNOPSIS
#include <openssl/bn.h>
05 July 2003 65
BIGNUM Montgomery Crypto Library
BIGNUM Montgomery
BN_mod_mul_montgomery, BN_MONT_CTX_new, BN_MONT_CTX_init, BN_MONT_CTX_free,
BN_MONT_CTX_set, BN_MONT_CTX_copy, BN_from_montgomery, BN_to_montgomery -
Montgomery multiplication
SYNOPSIS
#include <openssl/bn.h>
BN_MONT_CTX *BN_MONT_CTX_new(void);
void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
BN_to_montgomery() is a macro.
RETURN VALUES
BN_MONT_CTX_new() returns the newly allocated BN_MONT_CTX, and NULL on error.
BN_MONT_CTX_init() and BN_MONT_CTX_free() have no return values.
For the other functions, 1 is returned for success, 0 on error. The error codes can be obtained by
ERR_get_error(3)|ERR_get_error(3).
66 05 July 2003
Crypto Library BIGNUM Montgomery
WARNING
The inputs must be reduced modulo m, otherwise the result will be outside the expected range.
SEE ALSO
bn(3)|bn(3), ERR_get_error(3)|ERR_get_error(3), BN_add(3)|BN_add(3),
BN_CTX_new(3)|BN_CTX_new(3)
HISTORY
BN_MONT_CTX_new(), BN_MONT_CTX_free(), BN_MONT_CTX_set(),
BN_mod_mul_montgomery(), BN_from_montgomery() and BN_to_montgomery() are available in all
versions of SSLeay and OpenSSL.
BN_MONT_CTX_init() and BN_MONT_CTX_copy() were added in SSLeay 0.9.1b.
05 July 2003 67
BIGNUM modular multiplication Crypto Library
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_init(BN_RECP_CTX *recp);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
68 05 July 2003
Crypto Library BIGNUM allocation
BIGNUM allocation
BN_new, BN_init, BN_clear, BN_free, BN_clear_free - allocate and free BIGNUMs
SYNOPSIS
#include <openssl/bn.h>
BIGNUM *BN_new(void);
05 July 2003 69
BIGNUM size Crypto Library
BIGNUM size
BN_num_bits, BN_num_bytes, BN_num_bits_word - get BIGNUM size
SYNOPSIS
#include <openssl/bn.h>
BN_num_bytes() is a macro.
RETURN VALUES
The size.
SEE ALSO
bn(3)|bn(3)
HISTORY
BN_num_bytes(), BN_num_bits() and BN_num_bits_word() are available in all versions of SSLeay and
OpenSSL.
70 05 July 2003
Crypto Library BIGNUM pseudo-random
BIGNUM pseudo-random
BN_rand, BN_pseudo_rand - generate pseudo-random number
SYNOPSIS
#include <openssl/bn.h>
05 July 2003 71
BIGNUM bit-operations Crypto Library
BIGNUM bit-operations
BN_set_bit, BN_clear_bit, BN_is_bit_set, BN_mask_bits, BN_lshift, BN_lshift1, BN_rshift, BN_rshift1
- bit operations on BIGNUMs
SYNOPSIS
#include <openssl/bn.h>
72 05 July 2003
Crypto Library BIGNUM exchange
BIGNUM exchange
BN_swap - exchange BIGNUMs
SYNOPSIS
#include <openssl/bn.h>
05 July 2003 73
BIGNUM assignment Crypto Library
BIGNUM assignment
BN_zero, BN_one, BN_value_one, BN_set_word, BN_get_word - BIGNUM assignment operations
SYNOPSIS
#include <openssl/bn.h>
74 05 July 2003
Crypto Library BUF_MEM
BUF_MEM
BUF_MEM_new, BUF_MEM_free, BUF_MEM_grow, BUF_strdup - simple character arrays structure
SYNOPSIS
#include <openssl/buffer.h>
BUF_MEM *BUF_MEM_new(void);
length is the current size of the buffer in bytes, max is the amount of memory allocated to the buffer.
There are three functions which handle these and one "miscellaneous" function.
BUF_MEM_new() allocates a new buffer of zero size.
BUF_MEM_free() frees up an already existing buffer. The data is zeroed before freeing up in case the
buffer contains sensitive data.
BUF_MEM_grow() changes the size of an already existing buffer to len. Any data already in the buffer
is preserved if it increases in size.
BUF_strdup() copies a null terminated string into a block of allocated memory and returns a pointer to
the allocated block. Unlike the standard C library strdup() this function uses OPENSSL_malloc() and so
should be used in preference to the standard library strdup() because it can be used for memory leak
checking or replacing the malloc() function.
The memory allocated from BUF_strdup() should be freed up using the OPENSSL_free() function.
RETURN VALUES
BUF_MEM_new() returns the buffer or NULL on error.
BUF_MEM_free() has no return value.
BUF_MEM_grow() returns zero on error or the new size (i.e. len).
SEE ALSO
bio(3)|bio(3)
HISTORY
BUF_MEM_new(), BUF_MEM_free() and BUF_MEM_grow() are available in all versions of SSLeay
and OpenSSL. BUF_strdup() was added in SSLeay 0.8.
05 July 2003 75
CRYPTO internals Crypto Library
CRYPTO internals
CRYPTO_set_ex_data, CRYPTO_get_ex_data - internal application specific data functions
SYNOPSIS
int CRYPTO_set_ex_data(CRYPTO_EX_DATA *r, int idx, void *arg);
76 05 July 2003
Crypto Library d2i/i2d ASN1_OBJECT
d2i/i2d ASN1_OBJECT
d2i_ASN1_OBJECT, i2d_ASN1_OBJECT - ASN1 OBJECT IDENTIFIER functions
SYNOPSIS
#include <openssl/objects.h>
05 July 2003 77
d2i/i2d PKCS#3 DH parameter Crypto Library
78 05 July 2003
Crypto Library d2i/i2d DSA key encoding and parsing
05 July 2003 79
d2i/i2d DSA key encoding and parsing Crypto Library
HISTORY
TBA
80 05 July 2003
Crypto Library d2i/i2d PKCS#8 private key
05 July 2003 81
d2i/i2d RSA public and private key encoding Crypto Library
RSA * d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
DESCRIPTION
d2i_RSAPublicKey() and i2d_RSAPublicKey() decode and encode a PKCS#1 RSAPublicKey structure.
d2i_RSA_PUKEY() and i2d_RSA_PUKEY() decode and encode an RSA public key using a
SubjectPublicKeyInfo (certificate public key) structure.
d2i_RSAPrivateKey(), i2d_RSAPrivateKey() decode and encode a PKCS#1 RSAPrivateKey structure.
d2i_Netscape_RSA(), i2d_Netscape_RSA() decode and encode an RSA private key in NET format.
The usage of all of these functions is similar to the d2i_X509() and i2d_X509() described in the
d2i_X509(3)|d2i_X509(3) manual page.
NOTES
The RSA structure passed to the private key encoding functions should have all the PKCS#1 private key
components present.
The data encoded by the private key functions is unencrypted and therefore offers no private key
security.
The NET format functions are present to provide compatibility with certain very old software. This
format has some severe security weaknesses and should be avoided if possible.
SEE ALSO
d2i_X509(3)|d2i_X509(3)
HISTORY
TBA
82 05 July 2003
Crypto Library d2i/i2d X509 encode and decode
buf = OPENSSL_malloc(len);
if (buf == NULL)
05 July 2003 83
d2i/i2d X509 encode and decode Crypto Library
/* error */
p = buf;
i2d_X509(x, &p);
If you are using OpenSSL 0.9.7 or later then this can be simplified to:
int len;
unsigned char *buf;
buf = NULL;
if (len < 0)
/* error */
int len;
p = buf;
if (x == NULL)
/* Some error */
Alternative technique:
X509 *x;
int len;
p = buf;
x = NULL;
84 05 July 2003
Crypto Library d2i/i2d X509 encode and decode
buf = OPENSSL_malloc(len);
if (buf == NULL)
/* error */
i2d_X509(x, &buf);
OPENSSL_free(buf);
This code will result in buf apparently containing garbage because it was incremented after the call to
point after the data just written. Also buf will no longer contain the pointer allocated by
OPENSSL_malloc() and the subsequent call to OPENSSL_free() may well crash.
The auto allocation feature (setting buf to NULL) only works on OpenSSL 0.9.7 and later. Attempts to
use it on earlier versions will typically cause a segmentation violation.
Another trap to avoid is misuse of the xp argument to d2i_X509():
X509 *x;
This will probably crash somewhere in d2i_X509(). The reason for this is that the variable x is
uninitialized and an attempt will be made to interpret its (invalid) value as an X509 structure, typically
causing a segmentation violation. If x is set to NULL first then this will not happen.
BUGS
In some versions of OpenSSL the "reuse" behaviour of d2i_X509() when *px is valid is broken and
some parts of the reused structure may persist if they are not present in the new one. As a result the use
of this "reuse" behaviour is strongly discouraged.
i2d_X509() will not return an error in many versions of OpenSSL, if mandatory fields are not initialized
due to a programming error then the encoded structure may contain invalid data or omit the fields
entirely and will not be parsed by d2i_X509(). This may be fixed in future so code should not assume
that i2d_X509() will always succeed.
RETURN VALUES
d2i_X509(), d2i_X509_bio() and d2i_X509_fp() return a valid X509 structure or NULL if an error
occurs. The error code that can be obtained by ERR_get_error(3)|ERR_get_error(3).
i2d_X509(), i2d_X509_bio() and i2d_X509_fp() return a the number of bytes successfully encoded or a
negative value if an error occurs. The error code can be obtained by
ERR_get_error(3)|ERR_get_error(3).
i2d_X509_bio() and i2d_X509_fp() returns 1 for success and 0 if an error occurs The error code can be
obtained by ERR_get_error(3)|ERR_get_error(3).
SEE ALSO
ERR_get_error(3)|ERR_get_error(3)
HISTORY
d2i_X509, i2d_X509, d2i_X509_bio, d2i_X509_fp, i2d_X509_bio and i2d_X509_fp are available in all
versions of SSLeay and OpenSSL.
05 July 2003 85
d2i/i2d AlgorithmIdentifier Crypto Library
d2i/i2d AlgorithmIdentifier
d2i_X509_ALGOR, i2d_X509_ALGOR - AlgorithmIdentifier functions.
SYNOPSIS
#include <openssl/x509.h>
86 05 July 2003
Crypto Library d2i/i2d PKCS#10 certificate request
05 July 2003 87
d2i/i2d X509_NAME encoding Crypto Library
88 05 July 2003
Crypto Library d2i/i2d PKCS#10 certificate request
05 July 2003 89
d2i/i2d DigestInfo Crypto Library
d2i/i2d DigestInfo
d2i_X509_SIG, i2d_X509_SIG - DigestInfo functions.
SYNOPSIS
#include <openssl/x509.h>
90 05 July 2003
Crypto Library DES encryption
DES encryption
DES_random_key, DES_set_key, DES_key_sched, DES_set_key_checked, DES_set_key_unchecked,
DES_set_odd_parity, DES_is_weak_key, DES_ecb_encrypt, DES_ecb2_encrypt, DES_ecb3_encrypt,
DES_ncbc_encrypt, DES_cfb_encrypt, DES_ofb_encrypt, DES_pcbc_encrypt, DES_cfb64_encrypt,
DES_ofb64_encrypt, DES_xcbc_encrypt, DES_ede2_cbc_encrypt, DES_ede2_cfb64_encrypt,
DES_ede2_ofb64_encrypt, DES_ede3_cbc_encrypt, DES_ede3_cbcm_encrypt,
DES_ede3_cfb64_encrypt, DES_ede3_ofb64_encrypt, DES_cbc_cksum, DES_quad_cksum,
DES_string_to_key, DES_string_to_2keys, DES_fcrypt, DES_crypt, DES_enc_read, DES_enc_write -
DES encryption
SYNOPSIS
#include <openssl/des.h>
05 July 2003 91
DES encryption Crypto Library
92 05 July 2003
Crypto Library DES encryption
The following routines mostly operate on an input and output stream of DES_cblocks.
DES_ecb_encrypt() is the basic DES encryption routine that encrypts or decrypts a single 8-byte
DES_cblock in electronic code book (ECB) mode. It always transforms the input data, pointed to by
input, into the output data, pointed to by the output argument. If the encrypt argument is non-zero
(DES_ENCRYPT), the input (cleartext) is encrypted in to the output (ciphertext) using the key_schedule
specified by the schedule argument, previously set via DES_set_key. If encrypt is zero
(DES_DECRYPT), the input (now ciphertext) is decrypted into the output (now cleartext). Input and
output may overlap. DES_ecb_encrypt() does not return a value.
DES_ecb3_encrypt() encrypts/decrypts the input block by using three-key Triple-DES encryption in
ECB mode. This involves encrypting the input with ks1, decrypting with the key schedule ks2, and then
encrypting with ks3. This routine greatly reduces the chances of brute force breaking of DES and has
the advantage of if ks1, ks2 and ks3 are the same, it is equivalent to just encryption using ECB mode and
ks1 as the key.
The macro DES_ecb2_encrypt() is provided to perform two-key Triple-DES encryption by using ks1 for
the final encryption.
DES_ncbc_encrypt() encrypts/decrypts using the cipher-block-chaining (CBC) mode of DES. If the
encrypt argument is non-zero, the routine cipher-block-chain encrypts the cleartext data pointed to by the
input argument into the ciphertext pointed to by the output argument, using the key schedule provided by
the schedule argument, and initialization vector provided by the ivec argument. If the length argument is
not an integral multiple of eight bytes, the last block is copied to a temporary area and zero filled. The
output is always an integral multiple of eight bytes.
DES_xcbc_encrypt() is RSA‘s DESX mode of DES. It uses inw and outw to ‘whiten’ the encryption.
inw and outw are secret (unlike the iv) and are as such, part of the key. So the key is sort of 24 bytes.
This is much better than CBC DES.
DES_ede3_cbc_encrypt() implements outer triple CBC DES encryption with three keys. This means that
each DES operation inside the CBC mode is really an C=E(ks3,D(ks2,E(ks1,M))). This mode is
used by SSL.
The DES_ede2_cbc_encrypt() macro implements two-key Triple-DES by reusing ks1 for the final
encryption. C=E(ks1,D(ks2,E(ks1,M))). This form of Triple-DES is used by the RSAREF
library.
DES_pcbc_encrypt() encrypt/decrypts using the propagating cipher block chaining mode used by
Kerberos v4. Its parameters are the same as DES_ncbc_encrypt().
DES_cfb_encrypt() encrypt/decrypts using cipher feedback mode. This method takes an array of
characters as input and outputs and array of characters. It does not require any padding to 8 character
groups. Note: the ivec variable is changed and the new changed value needs to be passed to the next call
to this function. Since this function runs a complete DES ECB encryption per numbits, this function is
only suggested for use when sending small numbers of characters.
DES_cfb64_encrypt() implements CFB mode of DES with 64bit feedback. Why is this useful you ask?
Because this routine will allow you to encrypt an arbitrary number of bytes, no 8 byte padding. Each
call to this routine will encrypt the input bytes to output and then update ivec and num. num contains
‘how far’ we are though ivec. If this does not make much sense, read more about cfb mode of DES :-).
DES_ede3_cfb64_encrypt() and DES_ede2_cfb64_encrypt() is the same as DES_cfb64_encrypt() except
that Triple-DES is used.
DES_ofb_encrypt() encrypts using output feedback mode. This method takes an array of characters as
input and outputs and array of characters. It does not require any padding to 8 character groups. Note:
the ivec variable is changed and the new changed value needs to be passed to the next call to this
function. Since this function runs a complete DES ECB encryption per numbits, this function is only
suggested for use when sending small numbers of characters.
DES_ofb64_encrypt() is the same as DES_cfb64_encrypt() using Output Feed Back mode.
DES_ede3_ofb64_encrypt() and DES_ede2_ofb64_encrypt() is the same as DES_ofb64_encrypt(), using
Triple-DES.
The following functions are included in the DES library for compatibility with the MIT Kerberos library.
DES_cbc_cksum() produces an 8 byte checksum based on the input stream (via CBC encryption). The
last 4 bytes of the checksum are returned and the complete 8 bytes are placed in output. This function is
used by Kerberos v4. Other applications should use EVP_DigestInit(3)|EVP_DigestInit(3) etc. instead.
DES_quad_cksum() is a Kerberos v4 function. It returns a 4 byte checksum from the input bytes. The
algorithm can be iterated over the input, depending on out_count, 1, 2, 3 or 4 times. If output is
non-NULL, the 8 bytes generated by each pass are written into output.
05 July 2003 93
DES encryption Crypto Library
94 05 July 2003
Crypto Library DES encryption
05 July 2003 95
DES modes Crypto Library
DES modes
Modes of DES - the variants of DES and other crypto algorithms of OpenSSL
DESCRIPTION
Several crypto algorithms for OpenSSL can be used in a number of modes. Those are used for using
block ciphers in a way similar to stream ciphers, among other things.
OVERVIEW
Electronic Codebook Mode (ECB)
Normally, this is found as the function algorithm_ecb_encrypt().
96 05 July 2003
Crypto Library DES modes
The absence of chaining makes the OFB more vulnerable to specific attacks.
The use of different start variables values prevents the same plaintext enciphering to the same
ciphertext, by producing different key streams.
Selection of a small value for j will require more cycles through the encipherment algorithm per unit
of plaintext and thus cause greater processing overheads.
Only multiples of j bits can be enciphered.
OFB mode of operation does not extend ciphertext errors in the resultant plaintext output. Every bit
error in the ciphertext causes only one bit to be in error in the deciphered plaintext.
OFB mode is not self-synchronizing. If the two operation of encipherment and decipherment get out
of synchronism, the system needs to be re-initialized.
Each re-initialization should use a value of the start variable different from the start variable values
used before with the same key. The reason for this is that an identical bit stream would be produced
each time from the same parameters. This would be susceptible to a ‘known plaintext’ attack.
Encrypt with key1, decrypt with key2 and encrypt with key3 again.
As for ECB encryption but increases the key length to 168 bits. There are theoretic attacks that can be
used that make the effective key length 112 bits, but this attack also requires 2^56 blocks of memory,
not very likely, even for the NSA.
If both keys are the same it is equivalent to encrypting once with just one key.
If the first and last key are the same, the key length is 112 bits. There are attacks that could reduce the
effective key strength to only slightly more than 56 bits, but these require a lot of memory.
If all 3 keys are the same, this is effectively the same as normal ecb mode.
Encrypt with key1, decrypt with key2 and then encrypt with key3.
As for CBC encryption but increases the key length to 168 bits with the same restrictions as for triple
ecb mode.
NOTES
This text was been written in large parts by Eric Young in his original documentation for SSLeay, the
predecessor of OpenSSL. In turn, he attributed it to:
AS 2805.5.2
Australian Standard
Electronic funds transfer - Requirements for interfaces,
Part 5.2: Modes of operation for an n-bit block cipher algorithm
Appendix A
SEE ALSO
blowfish(3)|blowfish(3), des(3)|des(3), idea(3)|idea(3), rc2(3)|rc2(3)
05 July 2003 97
DH - Diffie-Hellman key agreement Crypto Library
DH * DH_new(void);
void DH_free(DH *dh);
Note that DH keys may use non-standard DH_METHOD implementations, either directly or by the use
of ENGINE modules. In some cases (eg. an ENGINE providing support for hardware-embedded keys),
these BIGNUM values will not be used by the implementation or may be used for alternative data
storage. For this reason, applications should generally avoid using DH structure elements directly and
instead use API functions to query or modify keys.
98 05 July 2003
Crypto Library DH - Diffie-Hellman key agreement
SEE ALSO
dhparam(1)|dhparam(1), bn(3)|bn(3), dsa(3)|dsa(3), err(3)|err(3), rand(3)|rand(3), rsa(3)|rsa(3),
engine(3)|engine(3), DH_set_method(3)|DH_set_method(3), DH_new(3)|DH_new(3),
DH_get_ex_new_index(3)|DH_get_ex_new_index(3),
DH_generate_parameters(3)|DH_generate_parameters(3), DH_compute_key(3)|DH_compute_key(3),
d2i_DHparams(3)|d2i_DHparams(3), RSA_print(3)|RSA_print(3)
05 July 2003 99
DH Diffie-Hellman key exchange Crypto Library
DH allocation
DH_new, DH_free - allocate and free DH objects
SYNOPSIS
#include <openssl/dh.h>
DH* DH_new(void);
DH select method
DH_set_default_method, DH_get_default_method, DH_set_method, DH_new_method, DH_OpenSSL -
select DH method
SYNOPSIS
#include <openssl/dh.h>
#include <openssl/engine.h>
DH *DH_new_method(ENGINE *engine);
/* called at DH_new */
/* called at DH_free */
int (*finish)(DH *dh);
int flags;
char *app_data; /* ?? */
} DH_METHOD;
RETURN VALUES
DH_OpenSSL() and DH_get_default_method() return pointers to the respective DH_METHODs.
DH_set_default_method() returns no value.
DH_set_method() returns non-zero if the provided meth was successfully set as the method for dh
(including unloading the ENGINE handle if the previous method was supplied by an ENGINE).
DH_new_method() returns NULL and sets an error code that can be obtained by
ERR_get_error(3)|ERR_get_error(3) if the allocation fails. Otherwise it returns a pointer to the newly
allocated structure.
NOTES
As of version 0.9.7, DH_METHOD implementations are grouped together with other algorithmic APIs
(eg. RSA_METHOD, EVP_CIPHER, etc) in ENGINE modules. If a default ENGINE is specified for
DH functionality using an ENGINE API function, that will override any DH defaults set using the DH
API (ie. DH_set_default_method()). For this reason, the ENGINE API is the recommended way to
control default implementations for use in DH and other cryptographic algorithms.
SEE ALSO
dh(3)|dh(3), DH_new(3)|DH_new(3)
HISTORY
DH_set_default_method(), DH_get_default_method(), DH_set_method(), DH_new_method() and
DH_OpenSSL() were added in OpenSSL 0.9.4.
DH_set_default_openssl_method() and DH_get_default_openssl_method() replaced
DH_set_default_method() and DH_get_default_method() respectively, and DH_set_method() and
DH_new_method() were altered to use ENGINEs rather than DH_METHODs during development of
the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was
restructured so that this change was reversed, and behaviour of the other functions resembled more
closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently
overrides the behaviour of defaults in the DH API without requiring changing these function prototypes.
DH size
DH_size - get Diffie-Hellman prime size
SYNOPSIS
#include <openssl/dh.h>
DSA * DSA_new(void);
void DSA_free(DSA *dsa);
DSA_SIG *DSA_SIG_new(void);
void DSA_SIG_free(DSA_SIG *a);
int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);
DSA_SIG *d2i_DSA_SIG(DSA_SIG **v, unsigned char **pp, long length);
DESCRIPTION
These functions implement the Digital Signature Algorithm (DSA). The generation of shared DSA
parameters is described in DSA_generate_parameters(3)|DSA_generate_parameters(3);
DSA_generate_key(3)|DSA_generate_key(3) describes how to generate a signature key. Signature
generation and verification are described in DSA_sign(3)|DSA_sign(3).
The DSA structure consists of several BIGNUM components.
struct
{
BIGNUM *p; // prime number (public)
BIGNUM *q; // 160-bit subprime, q | p-1 (public)
BIGNUM *g; // generator of subgroup (public)
BIGNUM *priv_key; // private key x
BIGNUM *pub_key; // public key y = g^x
// ...
}
DSA;
DSA dup DH
DSA_dup_DH - create a DH structure out of DSA structure
SYNOPSIS
#include <openssl/dsa.h>
When a candidate for q is generated, callback(0, m++, cb_arg) is called (m is 0 for the first
candidate).
When a candidate for q has passed a test by trial division, callback(1, -1, cb_arg) is called. While
a candidate for q is tested by Miller-Rabin primality tests, callback(1, i, cb_arg) is called in the
outer loop (once for each witness that confirms that the candidate may be prime); i is the loop
counter (starting at 0).
When a prime q has been found, callback(2, 0, cb_arg) and callback(3, 0, cb_arg) are called.
Before a candidate for p (other than the first) is generated and tested, callback(0, counter,
cb_arg) is called.
When a candidate for p has passed the test by trial division, callback(1, -1, cb_arg) is called.
While it is tested by the Miller-Rabin primality test, callback(1, i, cb_arg) is called in the outer
loop (once for each witness that confirms that the candidate may be prime). i is the loop counter
(starting at 0).
When p has been found, callback(2, 1, cb_arg) is called.
When the generator has been found, callback(3, 1, cb_arg) is called.
RETURN VALUE
DSA_generate_parameters() returns a pointer to the DSA structure, or NULL if the parameter
generation fails. The error codes can be obtained by ERR_get_error(3)|ERR_get_error(3).
BUGS
Seed lengths 20 are not supported.
SEE ALSO
dsa(3)|dsa(3), ERR_get_error(3)|ERR_get_error(3), rand(3)|rand(3), DSA_free(3)|DSA_free(3)
HISTORY
DSA_generate_parameters() appeared in SSLeay 0.8. The cb_arg argument was added in SSLeay 0.9.0.
In versions up to OpenSSL 0.9.4, callback(1, ...) was called in the inner loop of the Miller-Rabin test
whenever it reached the squaring step (the parameters to callback did not reveal how many witnesses
had been tested); since OpenSSL 0.9.5, callback(1, ...) is called as in BN_is_prime(3), i.e. once for each
witness.
DSA allocation
DSA_new, DSA_free - allocate and free DSA objects
SYNOPSIS
#include <openssl/dsa.h>
DSA* DSA_new(void);
DSA_METHOD *DSA_OpenSSL(void);
DESCRIPTION
A DSA_METHOD specifies the functions that OpenSSL uses for DSA operations. By modifying the
method, alternative implementations such as hardware accelerators may be used. IMPORTANT: See the
NOTES section for important information about how these DSA API functions are affected by the use of
ENGINE API calls.
Initially, the default DSA_METHOD is the OpenSSL internal implementation, as returned by
DSA_OpenSSL().
DSA_set_default_method() makes meth the default method for all DSA structures created later. NB:
This is true only whilst no ENGINE has been set as a default for DSA, so this function is no longer
recommended.
DSA_get_default_method() returns a pointer to the current default DSA_METHOD. However, the
meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is
no longer recommended.
DSA_set_method() selects meth to perform all operations using the key rsa. This will replace the
DSA_METHOD used by the DSA key and if the previous method was supplied by an ENGINE, the
handle to that ENGINE will be released during the change. It is possible to have DSA keys that only
work with certain DSA_METHOD implementations (eg. from an ENGINE module that supports
embedded hardware-protected keys), and in such cases attempting to change the DSA_METHOD for the
key can have unexpected results.
DSA_new_method() allocates and initializes a DSA structure so that engine will be used for the DSA
operations. If engine is NULL, the default engine for DSA operations is used, and if no default ENGINE
is set, the DSA_METHOD controlled by DSA_set_default_method() is used.
THE DSA_METHOD STRUCTURE
struct
{
/* name of the implementation */
const char *name;
/* sign */
DSA_SIG *(*dsa_do_sign)(const unsigned char *dgst, int dlen,
DSA *dsa);
/* verify */
int (*dsa_do_verify)(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa);
implementations) */
int (*dsa_mod_exp)(DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1,
BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont);
/* called at DSA_new */
int (*init)(DSA *DSA);
/* called at DSA_free */
int (*finish)(DSA *DSA);
int flags;
char *app_data; /* ?? */
} DSA_METHOD;
RETURN VALUES
DSA_OpenSSL() and DSA_get_default_method() return pointers to the respective DSA_METHODs.
DSA_set_default_method() returns no value.
DSA_set_method() returns non-zero if the provided meth was successfully set as the method for dsa
(including unloading the ENGINE handle if the previous method was supplied by an ENGINE).
DSA_new_method() returns NULL and sets an error code that can be obtained by
ERR_get_error(3)|ERR_get_error(3) if the allocation fails. Otherwise it returns a pointer to the newly
allocated structure.
NOTES
As of version 0.9.7, DSA_METHOD implementations are grouped together with other algorithmic APIs
(eg. RSA_METHOD, EVP_CIPHER, etc) in ENGINE modules. If a default ENGINE is specified for
DSA functionality using an ENGINE API function, that will override any DSA defaults set using the
DSA API (ie. DSA_set_default_method()). For this reason, the ENGINE API is the recommended way
to control default implementations for use in DSA and other cryptographic algorithms.
SEE ALSO
dsa(3)|dsa(3), DSA_new(3)|DSA_new(3)
HISTORY
DSA_set_default_method(), DSA_get_default_method(), DSA_set_method(), DSA_new_method() and
DSA_OpenSSL() were added in OpenSSL 0.9.4.
DSA_set_default_openssl_method() and DSA_get_default_openssl_method() replaced
DSA_set_default_method() and DSA_get_default_method() respectively, and DSA_set_method() and
DSA_new_method() were altered to use ENGINEs rather than DSA_METHODs during development
of the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was
restructured so that this change was reversed, and behaviour of the other functions resembled more
closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently
overrides the behaviour of defaults in the DSA API without requiring changing these function
prototypes.
DSA signatures
DSA_sign, DSA_sign_setup, DSA_verify - DSA signatures
SYNOPSIS
#include <openssl/dsa.h>
DSA_SIG *DSA_SIG_new(void);
DSA size
DSA_size - get DSA signature size
SYNOPSIS
#include <openssl/dsa.h>
ENGINE *ENGINE_get_first(void);
ENGINE *ENGINE_get_last(void);
ENGINE *ENGINE_get_next(ENGINE *e);
ENGINE *ENGINE_get_prev(ENGINE *e);
void ENGINE_load_openssl(void);
void ENGINE_load_dynamic(void);
void ENGINE_load_cswift(void);
void ENGINE_load_chil(void);
void ENGINE_load_atalla(void);
void ENGINE_load_nuron(void);
void ENGINE_load_ubsec(void);
void ENGINE_load_aep(void);
void ENGINE_load_sureware(void);
void ENGINE_load_4758cca(void);
void ENGINE_load_openbsd_dev_crypto(void);
void ENGINE_load_builtin_engines(void);
void ENGINE_cleanup(void);
ENGINE *ENGINE_get_default_RSA(void);
ENGINE *ENGINE_get_default_DSA(void);
ENGINE *ENGINE_get_default_DH(void);
ENGINE *ENGINE_get_default_RAND(void);
ENGINE *ENGINE_get_cipher_engine(int nid);
ENGINE *ENGINE_get_digest_engine(int nid);
void ENGINE_register_all_DSA(void);
int ENGINE_register_DH(ENGINE *e);
void ENGINE_unregister_DH(ENGINE *e);
void ENGINE_register_all_DH(void);
int ENGINE_register_RAND(ENGINE *e);
void ENGINE_unregister_RAND(ENGINE *e);
void ENGINE_register_all_RAND(void);
int ENGINE_register_ciphers(ENGINE *e);
void ENGINE_unregister_ciphers(ENGINE *e);
void ENGINE_register_all_ciphers(void);
int ENGINE_register_digests(ENGINE *e);
void ENGINE_unregister_digests(ENGINE *e);
void ENGINE_register_all_digests(void);
int ENGINE_register_complete(ENGINE *e);
int ENGINE_register_all_complete(void);
int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
int ENGINE_cmd_is_executable(ENGINE *e, int cmd);
int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name,
long i, void *p, void (*f)(), int cmd_optional);
int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg,
int cmd_optional);
ENGINE *ENGINE_new(void);
int ENGINE_free(ENGINE *e);
void ENGINE_add_conf_module(void);
DESCRIPTION
These functions create, manipulate, and use cryptographic modules in the form of ENGINE objects.
These objects act as containers for implementations of cryptographic algorithms, and support a
reference-counted mechanism to allow them to be dynamically loaded in and out of the running
application.
The cryptographic functionality that can be provided by an ENGINE implementation includes the
following abstractions;
RSA_METHOD - for providing alternative RSA implementations
DSA_METHOD, DH_METHOD, RAND_METHOD - alternative DSA, DH, and RAND
EVP_CIPHER - potentially multiple cipher algorithms (indexed by ’nid’)
EVP_DIGEST - potentially multiple hash algorithms (indexed by ’nid’)
key-loading - loading public and/or private EVP_PKEY keys
Reference counting and handles
Due to the modular nature of the ENGINE API, pointers to ENGINEs need to be treated as handles - ie.
not only as pointers, but also as references to the underlying ENGINE object. Ie. you should obtain a
new reference when making copies of an ENGINE pointer if the copies will be used (and released)
independantly.
ENGINE objects have two levels of reference-counting to match the way in which the objects are used.
At the most basic level, each ENGINE pointer is inherently a structural reference - you need a
structural reference simply to refer to the pointer value at all, as this kind of reference is your guarantee
that the structure can not be deallocated until you release your reference.
However, a structural reference provides no guarantee that the ENGINE has been initiliased to be usable
to perform any of its cryptographic implementations - and indeed it‘s quite possible that most ENGINEs
will not initialised at all on standard setups, as ENGINEs are typically used to support specialised
hardware. To use an ENGINE‘s functionality, you need a functional reference. This kind of reference
can be considered a specialised form of structural reference, because each functional reference implicitly
contains a structural reference as well - however to avoid difficult-to-find programming bugs, it is
recommended to treat the two kinds of reference independantly. If you have a functional reference to an
ENGINE, you have a guarantee that the ENGINE has been initialised ready to perform cryptographic
operations and will not be uninitialised or cleaned up until after you have released your reference.
We will discuss the two kinds of reference separately, including how to tell which one you are dealing
with at any given point in time (after all they are both simply (ENGINE *) pointers, the difference is in
the way they are used).
Structural references
This basic type of reference is typically used for creating new ENGINEs dynamically, iterating across
OpenSSL‘s internal linked-list of loaded ENGINEs, reading information about an ENGINE, etc.
Essentially a structural reference is sufficient if you only need to query or manipulate the data of an
ENGINE implementation rather than use its functionality.
The ENGINE_new() function returns a structural reference to a new (empty) ENGINE object. Other
than that, structural references come from return values to various ENGINE API functions such as;
ENGINE_by_id(), ENGINE_get_first(), ENGINE_get_last(), ENGINE_get_next(),
Having called any of these functions, ENGINE objects would have been dynamically allocated and
populated with these implementations and linked into OpenSSL‘s internal linked list. At this point it is
important to mention an important API function;
void ENGINE_cleanup(void);
If no ENGINE API functions are called at all in an application, then there are no inherent memory leaks
to worry about from the ENGINE functionality, however if any ENGINEs are "load"ed, even if they are
never registered or used, it is necessary to use the ENGINE_cleanup() function to correspondingly
cleanup before program exit, if the caller wishes to avoid memory leaks. This mechanism uses an
internal callback registration table so that any ENGINE API functionality that knows it requires cleanup
can register its cleanup details to be called during ENGINE_cleanup(). This approach allows
ENGINE_cleanup() to clean up after any ENGINE functionality at all that your program uses, yet
doesn‘t automatically create linker dependencies to all possible ENGINE functionality - only the cleanup
callbacks required by the functionality you do use will be required by the linker.
The fact that ENGINEs are made visible to OpenSSL (and thus are linked into the program and loaded
into memory at run-time) does not mean they are "registered" or called into use by OpenSSL
automatically - that behaviour is something for the application to have control over. Some applications
will want to allow the user to specify exactly which ENGINE they want used if any is to be used at all.
Others may prefer to load all support and have OpenSSL automatically use at run-time any ENGINE
that is able to successfully initialise - ie. to assume that this corresponds to acceleration hardware
attached to the machine or some such thing. There are probably numerous other ways in which
applications may prefer to handle things, so we will simply illustrate the consequences as they apply to a
couple of simple cases and leave developers to consider these and the source code to openssl‘s builtin
utilities as guides.
Using a specific ENGINE implementation
Here we‘ll assume an application has been configured by its user or admin to want to use the "ACME"
ENGINE if it is available in the version of OpenSSL the application was compiled with. If it is available,
it should be used by default for all RSA, DSA, and symmetric cipher operation, otherwise OpenSSL
should use its builtin software as per usual. The following code illustrates how to approach this;
ENGINE *e;
const char *engine_id = "ACME";
ENGINE_load_builtin_engines();
e = ENGINE_by_id(engine_id);
if(!e)
/* the engine isn’t available */
return;
if(!ENGINE_init(e)) {
/* the engine couldn’t initialise, release ’e’ */
ENGINE_free(e);
return;
}
if(!ENGINE_set_default_RSA(e))
/* This should only happen when ’e’ can’t initialise, but the previous
* statement suggests it did. */
abort();
ENGINE_set_default_DSA(e);
ENGINE_set_default_ciphers(e);
/* Release the functional reference from ENGINE_init() */
ENGINE_finish(e);
/* Release the structural reference from ENGINE_by_id() */
ENGINE_free(e);
That‘s all that‘s required. Eg. the next time OpenSSL tries to set up an RSA key, any bundled ENGINEs
that implement RSA_METHOD will be passed to ENGINE_init() and if any of those succeed, that
ENGINE will be set as the default for use with RSA from then on.
Advanced configuration support
There is a mechanism supported by the ENGINE framework that allows each ENGINE implementation
to define an arbitrary set of configuration "commands" and expose them to OpenSSL and any
applications based on OpenSSL. This mechanism is entirely based on the use of name-value pairs and
and assumes ASCII input (no unicode or UTF for now!), so it is ideal if applications want to provide a
transparent way for users to provide arbitrary configuration "directives" directly to such ENGINEs. It is
also possible for the application to dynamically interrogate the loaded ENGINE implementations for the
names, descriptions, and input flags of their available "control commands", providing a more flexible
configuration scheme. However, if the user is expected to know which ENGINE device he/she is using
(in the case of specialised hardware, this goes without saying) then applications may not need to concern
themselves with discovering the supported control commands and simply prefer to allow settings to
passed into ENGINEs exactly as they are provided by the user.
Before illustrating how control commands work, it is worth mentioning what they are typically used for.
Broadly speaking there are two uses for control commands; the first is to provide the necessary details to
the implementation (which may know nothing at all specific to the host system) so that it can be
initialised for use. This could include the path to any driver or config files it needs to load, required
network addresses, smart-card identifiers, passwords to initialise password-protected devices, logging
information, etc etc. This class of commands typically needs to be passed to an ENGINE before
attempting to initialise it, ie. before calling ENGINE_init(). The other class of commands consist of
settings or operations that tweak certain behaviour or cause certain operations to take place, and these
commands may work either before or after ENGINE_init(), or in same cases both. ENGINE
implementations should provide indications of this in the descriptions attached to builtin control
commands and/or in external product documentation.
Issuing control commands to an ENGINE
Let‘s illustrate by example; a function for which the caller supplies the name of the ENGINE it wishes to
use, a table of string-pairs for use before initialisation, and another table for use after initialisation. Note
that the string-pairs used for control commands consist of a command "name" followed by the command
"parameter" - the parameter could be NULL in some cases but the name can not. This function should
initialise the ENGINE (issuing the "pre" commands beforehand and the "post" commands afterwards)
and set it as the default for everything except RAND and then return a boolean success or failure.
int generic_load_engine_fn(const char *engine_id,
const char **pre_cmds, int pre_num,
const char **post_cmds, int post_num)
{
ENGINE *e = ENGINE_by_id(engine_id);
if(!e) return 0;
while(pre_num--) {
if(!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) {
fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
pre_cmds[0], pre_cmds[1] ? pre_cmds[1] : "(NULL)");
ENGINE_free(e);
return 0;
}
pre_cmds += 2;
}
if(!ENGINE_init(e)) {
fprintf(stderr, "Failed initialisation\n");
ENGINE_free(e);
return 0;
}
/* ENGINE_init() returned a functional reference, so free the structural
* reference from ENGINE_by_id(). */
ENGINE_free(e);
while(post_num--) {
if(!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) {
fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id,
post_cmds[0], post_cmds[1] ? post_cmds[1] : "(NULL)");
ENGINE_finish(e);
return 0;
}
post_cmds += 2;
}
ENGINE_set_default(e, ENGINE_METHOD_ALL & ~ENGINE_METHOD_RAND);
/* Success */
return 1;
}
Note that ENGINE_ctrl_cmd_string() accepts a boolean argument that can relax the semantics of the
function - if set non-zero it will only return failure if the ENGINE supported the given command name
but failed while executing it, if the ENGINE doesn‘t support the command name it will simply return
success without doing anything. In this case we assume the user is only supplying commands specific to
the given ENGINE so we set this to FALSE.
Discovering supported control commands
It is possible to discover at run-time the names, numerical-ids, descriptions and input parameters of the
control commands supported from a structural reference to any ENGINE. It is first important to note that
some control commands are defined by OpenSSL itself and it will intercept and handle these control
commands on behalf of the ENGINE, ie. the ENGINE‘s ctrl() handler is not used for the control
command. openssl/engine.h defines a symbol, ENGINE_CMD_BASE, that all control commands
implemented by ENGINEs from. Any command value lower than this symbol is considered a "generic"
command is handled directly by the OpenSSL core routines.
It is using these "core" control commands that one can discover the the control commands implemented
by a given ENGINE, specifically the commands;
#define ENGINE_HAS_CTRL_FUNCTION 10
#define ENGINE_CTRL_GET_FIRST_CMD_TYPE 11
#define ENGINE_CTRL_GET_NEXT_CMD_TYPE 12
#define ENGINE_CTRL_GET_CMD_FROM_NAME 13
#define ENGINE_CTRL_GET_NAME_LEN_FROM_CMD 14
#define ENGINE_CTRL_GET_NAME_FROM_CMD 15
#define ENGINE_CTRL_GET_DESC_LEN_FROM_CMD 16
#define ENGINE_CTRL_GET_DESC_FROM_CMD 17
#define ENGINE_CTRL_GET_CMD_FLAGS 18
Whilst these commands are automatically processed by the OpenSSL framework code, they use various
properties exposed by each ENGINE by which to process these queries. An ENGINE has 3 properties it
exposes that can affect this behaviour; it can supply a ctrl() handler, it can specify
ENGINE_FLAGS_MANUAL_CMD_CTRL in the ENGINE‘s flags, and it can expose an array of
control command descriptions. If an ENGINE specifies the ENGINE_FLAGS_MANUAL_CMD_CTRL
flag, then it will simply pass all these "core" control commands directly to the ENGINE‘s ctrl() handler
(and thus, it must have supplied one), so it is up to the ENGINE to reply to these "discovery" commands
itself. If that flag is not set, then the OpenSSL framework code will work with the following rules;
if no ctrl() handler supplied;
ENGINE_HAS_CTRL_FUNCTION returns FALSE (zero),
all other commands fail.
if a ctrl() handler was supplied but no array of control commands;
ENGINE_HAS_CTRL_FUNCTION returns TRUE,
all other commands fail.
if a ctrl() handler and array of control commands was supplied;
ENGINE_HAS_CTRL_FUNCTION returns TRUE,
all other commands proceed processing ...
If the ENGINE‘s array of control commands is empty then all other commands will fail, otherwise;
ENGINE_CTRL_GET_FIRST_CMD_TYPE returns the identifier of the first command supported by
the ENGINE, ENGINE_GET_NEXT_CMD_TYPE takes the identifier of a command supported by the
ENGINE and returns the next command identifier or fails if there are no more,
ENGINE_CMD_FROM_NAME takes a string name for a command and returns the corresponding
identifier or fails if no such command name exists, and the remaining commands take a command
identifier and return properties of the corresponding commands. All except
ENGINE_CTRL_GET_FLAGS return the string length of a command name or description, or populate
a supplied character buffer with a copy of the command name or description.
ENGINE_CTRL_GET_FLAGS returns a bitwise-OR‘d mask of the following possible values;
#define ENGINE_CMD_FLAG_NUMERIC (unsigned int)0x0001
#define ENGINE_CMD_FLAG_STRING (unsigned int)0x0002
#define ENGINE_CMD_FLAG_NO_INPUT (unsigned int)0x0004
#define ENGINE_CMD_FLAG_INTERNAL (unsigned int)0x0008
If the ENGINE_CMD_FLAG_INTERNAL flag is set, then any other flags are purely informational to
the caller - this flag will prevent the command being usable for any higher-level ENGINE functions such
as ENGINE_ctrl_cmd_string(). "INTERNAL" commands are not intended to be exposed to text-based
configuration by applications, administrations, users, etc. These can support arbitrary operations via
ENGINE_ctrl(), including passing to and/or from the control commands data of any arbitrary type.
These commands are supported in the discovery mechanisms simply to allow applications determinie if
an ENGINE supports certain specific commands it might want to use (eg. application "foo" might query
various ENGINEs to see if they implement "FOO_GET_VENDOR_LOGO_GIF" - and ENGINE could
therefore decide whether or not to support this "foo"-specific extension).
Future developments
The ENGINE API and internal architecture is currently being reviewed. Slated for possible release in
0.9.8 is support for transparent loading of "dynamic" ENGINEs (built as self-contained shared-libraries).
This would allow ENGINE implementations to be provided independantly of OpenSSL libraries and/or
OpenSSL-based applications, and would also remove any requirement for applications to explicitly use
the "dynamic" ENGINE to bind to shared-library implementations.
SEE ALSO
rsa(3)|rsa(3), dsa(3)|dsa(3), dh(3)|dh(3), rand(3)|rand(3), RSA_new_method(3)|RSA_new_method(3)
void ERR_clear_error(void);
void ERR_load_crypto_strings(void);
void ERR_free_strings(void);
void ERR_put_error(int lib, int func, int reason, const char *file,
int line);
void ERR_add_error_data(int num, ...);
Reporting errors
Each sub-library has a specific macro XXXerr() that is used to report errors. Its first argument is a
function code XXX_F_..., the second argument is a reason code XXX_R_.... Function codes are derived
from the function names; reason codes consist of textual error descriptions. For example, the function
ssl23_read() reports a "handshake failure" as follows:
SSLerr(SSL_F_SSL23_READ, SSL_R_SSL_HANDSHAKE_FAILURE);
Function and reason codes should consist of upper case characters, numbers and underscores only. The
error file generation script translates function codes into function names by looking in the header files
for an appropriate function name, if none is found it just uses the capitalized form such as
"SSL23_READ" in the above example.
The trailing section of a reason code (after the "_R_") is translated into lower case and underscores
changed to spaces.
When you are using new function or reason codes, run make errors. The necessary #defines will then
automatically be added to the sub-library‘s header file.
Although a library will normally report errors using its own specific XXXerr macro, another library‘s
macro can be used. This is normally only done when a library wants to include ASN1 code which must
use the ASN1err() macro.
Adding new libraries
When adding a new sub-library to OpenSSL, assign it a library number ERR_LIB_XXX, define a
macro XXXerr() (both in err.h), add its name to ERR_str_libraries[] (in crypto/err/err.c), and add
ERR_load_XXX_strings() to the ERR_load_crypto_strings() function (in crypto/err/err_all.c).
Finally, add an entry
L XXX xxx.h xxx_err.c
to crypto/err/openssl.ec, and add xxx_err.c to the Makefile. Running make errors will then generate a
file xxx_err.c, and add all error codes used in the library to xxx.h.
Additionally the library include file must have a certain form. Typically it will initially look like this:
#ifndef HEADER_XXX_H
#define HEADER_XXX_H
#ifdef __cplusplus
extern "C" {
#endif
/* Include files */
#include <openssl/bio.h>
#include <openssl/x509.h>
The BEGIN ERROR CODES sequence is used by the error code generation script as the point to place
new error codes, any text after this point will be overwritten when make errors is run. The closing
#endif etc will be automatically added by the script.
The generated C error code file xxx_err.c will load the header files stdio.h, openssl/err.h and
openssl/xxx.h so the header file must load any additional header files containing any definitions it uses.
USING ERROR CODES IN EXTERNAL LIBRARIES
It is also possible to use OpenSSL‘s error code scheme in external libraries. The library needs to load its
own codes and call the OpenSSL error code insertion script mkerr.pl explicitly to add codes to the
header file and generate the C error code file. This will normally be done if the external library needs to
generate new ASN1 structures but it can also be used to add more general purpose error code handling.
TBA more details
INTERNALS
The error queues are stored in a hash table with one ERR_STATE entry for each pid. ERR_get_state()
returns the current thread‘s ERR_STATE. An ERR_STATE can hold up to ERR_NUM_ERRORS
error codes. When more error codes are added, the old ones are overwritten, on the assumption that the
most recent errors are most important.
Error strings are also stored in hash table. The hash tables can be obtained by calling
ERR_get_err_state_table(void) and ERR_get_string_table(void) respectively.
SEE ALSO
CRYPTO_set_id_callback(3)|CRYPTO_set_id_callback(3),
CRYPTO_set_locking_callback(3)|CRYPTO_set_locking_callback(3),
ERR_get_error(3)|ERR_get_error(3), ERR_GET_LIB(3)|ERR_GET_LIB(3),
ERR_clear_error(3)|ERR_clear_error(3), ERR_error_string(3)|ERR_error_string(3),
ERR_print_errors(3)|ERR_print_errors(3), ERR_load_crypto_strings(3)|ERR_load_crypto_strings(3),
ERR_remove_state(3)|ERR_remove_state(3), ERR_put_error(3)|ERR_put_error(3),
ERR_load_strings(3)|ERR_load_strings(3), SSL_get_error(3)|SSL_get_error(3)
void ERR_clear_error(void);
DESCRIPTION
ERR_clear_error() empties the current thread‘s error queue.
RETURN VALUES
ERR_clear_error() has no return value.
SEE ALSO
err(3)|err(3), ERR_get_error(3)|ERR_get_error(3)
HISTORY
ERR_clear_error() is available in all versions of SSLeay and OpenSSL.
error code is an 8 digit hexadecimal number, library name, function name and reason string are ASCII
text.
ERR_lib_error_string(), ERR_func_error_string() and ERR_reason_error_string() return the library
name, function name and reason string respectively.
The OpenSSL error strings should be loaded by calling
ERR_load_crypto_strings(3)|ERR_load_crypto_strings(3) or, for SSL applications,
SSL_load_error_strings(3)|SSL_load_error_strings(3) first. If there is no text string registered for the
given error code, the error string will contain the numeric code.
ERR_print_errors(3)|ERR_print_errors(3) can be used to print all error codes currently in the queue.
RETURN VALUES
ERR_error_string() returns a pointer to a static buffer containing the string if buf == NULL, buf
otherwise.
ERR_lib_error_string(), ERR_func_error_string() and ERR_reason_error_string() return the strings, and
NULL if none is registered for the error code.
SEE ALSO
err(3)|err(3), ERR_get_error(3)|ERR_get_error(3),
ERR_load_crypto_strings(3)|ERR_load_crypto_strings(3),
SSL_load_error_strings(3)|SSL_load_error_strings(3) ERR_print_errors(3)|ERR_print_errors(3)
HISTORY
ERR_error_string() is available in all versions of SSLeay and OpenSSL. ERR_error_string_n() was
added in OpenSSL 0.9.6.
void ERR_load_crypto_strings(void);
void ERR_free_strings(void);
#include <openssl/ssl.h>
void SSL_load_error_strings(void);
DESCRIPTION
ERR_load_crypto_strings() registers the error strings for all libcrypto functions.
SSL_load_error_strings() does the same, but also registers the libssl error strings.
One of these functions should be called before generating textual error messages. However, this is not
required when memory usage is an issue.
ERR_free_strings() frees all previously loaded error strings.
RETURN VALUES
ERR_load_crypto_strings(), SSL_load_error_strings() and ERR_free_strings() return no values.
SEE ALSO
err(3)|err(3), ERR_error_string(3)|ERR_error_string(3)
HISTORY
ERR_load_error_strings(), SSL_load_error_strings() and ERR_free_strings() are available in all
versions of SSLeay and OpenSSL.
int ERR_get_next_error_library(void);
The error code is generated from the library number and a function and reason code: error =
ERR_PACK(lib, func, reason). ERR_PACK() is a macro.
The last entry in the array is {0,0}.
ERR_get_next_error_library() can be used to assign library numbers to user libraries at runtime.
RETURN VALUE
ERR_load_strings() returns no value. ERR_PACK() return the error code. ERR_get_next_error_library()
returns a new library number.
SEE ALSO
err(3)|err(3), ERR_load_strings(3)|ERR_load_strings(3)
HISTORY
ERR_load_error_strings() and ERR_PACK() are available in all versions of SSLeay and OpenSSL.
ERR_get_next_error_library() was added in SSLeay 0.9.0.
error code is an 8 digit hexadecimal number. library name, function name and reason string are ASCII
text, as is optional text message if one was set for the respective error code.
If there is no text string registered for the given error code, the error string will contain the numeric code.
RETURN VALUES
ERR_print_errors() and ERR_print_errors_fp() return no values.
SEE ALSO
err(3)|err(3), ERR_error_string(3)|ERR_error_string(3), ERR_get_error(3)|ERR_get_error(3),
ERR_load_crypto_strings(3)|ERR_load_crypto_strings(3),
SSL_load_error_strings(3)|SSL_load_error_strings(3)
HISTORY
ERR_print_errors() and ERR_print_errors_fp() are available in all versions of SSLeay and OpenSSL.
ERR recording
ERR_put_error, ERR_add_error_data - record an error
SYNOPSIS
#include <openssl/err.h>
void ERR_put_error(int lib, int func, int reason, const char *file,
int line);
where || denotes concatentaion, D_0 is empty, HASH is the digest algorithm in use, HASH^1(data) is
simply HASH(data), HASH^2(data) is HASH(HASH(data)) and so on.
The initial bytes are used for the key and the subsequent bytes for the IV.
RETURN VALUES
EVP_BytesToKey() returns the size of the derived key in bytes.
SEE ALSO
evp(3)|evp(3), rand(3)|rand(3), EVP_EncryptInit(3)|EVP_EncryptInit(3),
HISTORY
EVP digest
EVP_MD_CTX_init, EVP_MD_CTX_create, EVP_DigestInit_ex, EVP_DigestUpdate,
EVP_DigestFinal_ex, EVP_MD_CTX_cleanup, EVP_MD_CTX_destroy, EVP_MAX_MD_SIZE,
EVP_MD_CTX_copy_ex EVP_MD_CTX_copy, EVP_MD_type, EVP_MD_pkey_type,
EVP_MD_size, EVP_MD_block_size, EVP_MD_CTX_md, EVP_MD_CTX_size,
EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_md_null, EVP_md2, EVP_md5, EVP_sha,
EVP_sha1, EVP_dss, EVP_dss1, EVP_mdc2, EVP_ripemd160, EVP_get_digestbyname,
EVP_get_digestbynid, EVP_get_digestbyobj - EVP digest routines
SYNOPSIS
#include <openssl/evp.h>
DESCRIPTION
The EVP digest routines are a high level interface to message digests.
EVP_MD_CTX_init() initializes digest contet ctx.
EVP_MD_CTX_create() allocates, initializes and returns a digest contet.
EVP_DigestInit_ex() sets up digest context ctx to use a digest type from ENGINE impl. ctx must be
initialized before calling this function. type will typically be supplied by a functionsuch as EVP_sha1().
If impl is NULL then the default implementation of digest type is used.
EVP_DigestUpdate() hashes cnt bytes of data at d into the digest context ctx. This function can be
called several times on the same ctx to hash additional data.
EVP_DigestFinal_ex() retrieves the digest value from ctx and places it in md. If the s parameter is not
NULL then the number of bytes of data written (i.e. the length of the digest) will be written to the
integer at s, at most EVP_MAX_MD_SIZE bytes will be written. After calling EVP_DigestFinal_ex()
no additional calls to EVP_DigestUpdate() can be made, but EVP_DigestInit_ex() can be called to
initialize a new digest operation.
EVP_MD_CTX_cleanup() cleans up digest context ctx, it should be called after a digest context is no
longer needed.
EVP_MD_CTX_destroy() cleans up digest context ctx and frees up the space allocated to it, it should be
called only on a context created using EVP_MD_CTX_create().
EVP_MD_CTX_copy_ex() can be used to copy the message digest state from in to out. This is useful if
large amounts of data are to be hashed which only differ in the last few bytes. out must be initialized
before calling this function.
EVP_DigestInit() behaves in the same way as EVP_DigestInit_ex() except the passed context ctx does
not have to be initialized, and it always uses the default digest implementation.
EVP_DigestFinal() is similar to EVP_DigestFinal_ex() except the digest contet ctx is automatically
cleaned up.
EVP_MD_CTX_copy() is similar to EVP_MD_CTX_copy_ex() except the destination out does not
have to be initialized.
EVP_MD_size() and EVP_MD_CTX_size() return the size of the message digest when passed an
EVP_MD or an EVP_MD_CTX structure, i.e. the size of the hash.
EVP_MD_block_size() and EVP_MD_CTX_block_size() return the block size of the message digest
when passed an EVP_MD or an EVP_MD_CTX structure.
EVP_MD_type() and EVP_MD_CTX_type() return the NID of the OBJECT IDENTIFIER representing
the given message digest when passed an EVP_MD structure. For example
EVP_MD_type(EVP_sha1()) returns NID_sha1. This function is normally used when setting ASN1
OIDs.
EVP_MD_CTX_md() returns the EVP_MD structure corresponding to the passed EVP_MD_CTX.
EVP_MD_pkey_type() returns the NID of the public key signing algorithm associated with this digest.
For example EVP_sha1() is associated with RSA so this will return NID_sha1WithRSAEncryption.
This "link" between digests and signature algorithms may not be retained in future versions of OpenSSL.
OpenSSL_add_all_digests();
if(!argv[1]) {
printf("Usage: mdtest digestname\n");
exit(1);
}
md = EVP_get_digestbyname(argv[1]);
if(!md) {
printf("Unknown message digest %s\n", argv[1]);
exit(1);
}
EVP_MD_CTX_init(&mdctx);
EVP_DigestInit_ex(&mdctx, md, NULL);
EVP_DigestUpdate(&mdctx, mess1, strlen(mess1));
EVP_DigestUpdate(&mdctx, mess2, strlen(mess2));
EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
EVP_MD_CTX_cleanup(&mdctx);
BUGS
The link between digests and signing algorithms results in a situation where EVP_sha1() must be used
with RSA and EVP_dss1() must be used with DSS even though they are identical digests.
SEE ALSO
evp(3)|evp(3), hmac(3)|hmac(3), md2(3)|md2(3), md5(3)|md5(3), mdc2(3)|mdc2(3),
ripemd(3)|ripemd(3), sha(3)|sha(3), dgst(1)|dgst(1)
HISTORY
EVP_DigestInit(), EVP_DigestUpdate() and EVP_DigestFinal() are available in all versions of SSLeay
and OpenSSL.
EVP_MD_CTX_init(), EVP_MD_CTX_create(), EVP_MD_CTX_copy_ex(),
EVP_MD_CTX_cleanup(), EVP_MD_CTX_destroy(), EVP_DigestInit_ex() and EVP_DigestFinal_ex()
were added in OpenSSL 0.9.7.
EVP_md_null(), EVP_md2(), EVP_md5(), EVP_sha(), EVP_sha1(), EVP_dss(), EVP_dss1(),
EVP_mdc2() and EVP_ripemd160() were changed to return truely const EVP_MD * in OpenSSL 0.9.7.
EVP cipher
EVP_CIPHER_CTX_init, EVP_EncryptInit_ex, EVP_EncryptUpdate, EVP_EncryptFinal_ex,
EVP_DecryptInit_ex, EVP_DecryptUpdate, EVP_DecryptFinal_ex, EVP_CipherInit_ex,
EVP_CipherUpdate, EVP_CipherFinal_ex, EVP_CIPHER_CTX_set_key_length,
EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX_cleanup, EVP_EncryptInit, EVP_EncryptFinal,
EVP_DecryptInit, EVP_DecryptFinal, EVP_CipherInit, EVP_CipherFinal, EVP_get_cipherbyname,
EVP_get_cipherbynid, EVP_get_cipherbyobj, EVP_CIPHER_nid, EVP_CIPHER_block_size,
EVP_CIPHER_key_length, EVP_CIPHER_iv_length, EVP_CIPHER_flags, EVP_CIPHER_mode,
EVP_CIPHER_type, EVP_CIPHER_CTX_cipher, EVP_CIPHER_CTX_nid,
EVP_CIPHER_CTX_block_size, EVP_CIPHER_CTX_key_length, EVP_CIPHER_CTX_iv_length,
EVP_CIPHER_CTX_get_app_data, EVP_CIPHER_CTX_set_app_data, EVP_CIPHER_CTX_type,
EVP_CIPHER_CTX_flags, EVP_CIPHER_CTX_mode, EVP_CIPHER_param_to_asn1,
EVP_CIPHER_asn1_to_param, EVP_CIPHER_CTX_set_padding - EVP cipher routines
SYNOPSIS
#include <openssl/evp.h>
EVP_CIPHER_CTX_cleanup() clears all information from a cipher context and free up any allocated
memory associate with it. It should be called after all operations using a cipher are complete so sensitive
information does not remain in memory.
EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit() behave in a similar way to
EVP_EncryptInit_ex(), EVP_DecryptInit_ex and EVP_CipherInit_ex() except the ctx paramter does not
need to be initialized and they always use the default cipher implementation.
EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal() behave in a similar way to
EVP_EncryptFinal_ex(), EVP_DecryptFinal_ex() and EVP_CipherFinal_ex() except ctx is
automatically cleaned up after the call.
EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() return an EVP_CIPHER
structure when passed a cipher name, a NID or an ASN1_OBJECT structure.
EVP_CIPHER_nid() and EVP_CIPHER_CTX_nid() return the NID of a cipher when passed an
EVP_CIPHER or EVP_CIPHER_CTX structure. The actual NID value is an internal value which
may not have a corresponding OBJECT IDENTIFIER.
EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are
padded using standard block padding and the padding is checked and removed when decrypting. If the
pad parameter is zero then no padding is performed, the total amount of data encrypted or decrypted
must then be a multiple of the block size or an error will occur.
EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key length of a cipher
when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant
EVP_MAX_KEY_LENGTH is the maximum key length for all ciphers. Note: although
EVP_CIPHER_key_length() is fixed for a given cipher, the value of EVP_CIPHER_CTX_key_length()
may be different for variable key length ciphers.
EVP_CIPHER_CTX_set_key_length() sets the key length of the cipher ctx. If the cipher is a fixed
length cipher then attempting to set the key length to any value other than the fixed value is an error.
EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV length of a cipher when
passed an EVP_CIPHER or EVP_CIPHER_CTX. It will return zero if the cipher does not use an IV.
The constant EVP_MAX_IV_LENGTH is the maximum IV length for all ciphers.
EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block size of a cipher
when passed an EVP_CIPHER or EVP_CIPHER_CTX structure. The constant
EVP_MAX_IV_LENGTH is also the maximum block length for all ciphers.
EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the type of the passed cipher or context.
This "type" is the actual NID of the cipher OBJECT IDENTIFIER as such it ignores the cipher
parameters and 40 bit RC2 and 128 bit RC2 have the same NID. If the cipher does not have an object
identifier or does not have ASN1 support this function will return NID_undef.
EVP_CIPHER_CTX_cipher() returns the EVP_CIPHER structure when passed an
EVP_CIPHER_CTX structure.
EVP_CIPHER_mode() and EVP_CIPHER_CTX_mode() return the block cipher mode:
EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE or
EVP_CIPH_OFB_MODE. If the cipher is a stream cipher then EVP_CIPH_STREAM_CIPHER is
returned.
EVP_CIPHER_param_to_asn1() sets the AlgorithmIdentifier "parameter" based on the passed cipher.
This will typically include any parameters and an IV. The cipher IV (if any) must be set when this call is
made. This call should be made before the cipher is actually "used" (before any EVP_EncryptUpdate(),
EVP_DecryptUpdate() calls for example). This function may fail if the cipher does not have any ASN1
support.
EVP_CIPHER_asn1_to_param() sets the cipher parameters based on an ASN1 AlgorithmIdentifier
"parameter". The precise effect depends on the cipher In the case of RC2, for example, it will set the IV
and effective key length. This function should be called after the base cipher type is set but before the
key is set. For example EVP_CipherInit() will be called with the IV and key set to NULL,
EVP_CIPHER_asn1_to_param() will be called and finally EVP_CipherInit() again with all parameters
except the key set to NULL. It is possible for this function to fail if the cipher does not have any ASN1
support or the parameters cannot be set (for example the RC2 effective key length is not supported.
EVP_CIPHER_CTX_ctrl() allows various cipher specific parameters to be determined and set.
Currently only the RC2 effective key length and the number of rounds of RC5 can be set.
RETURN VALUES
EVP_CIPHER_CTX_init, EVP_EncryptInit_ex(), EVP_EncryptUpdate() and EVP_EncryptFinal_ex()
return 1 for success and 0 for failure.
EVP_enc_null()
Null cipher: does nothing.
EVP_des_cbc(void), EVP_des_ecb(void), EVP_des_cfb(void), EVP_des_ofb(void)
DES in CBC, ECB, CFB and OFB modes respectively.
EVP_des_ede_cbc(void), EVP_des_ede(), EVP_des_ede_ofb(void), EVP_des_ede_cfb(void)
Two key triple DES in CBC, ECB, CFB and OFB modes respectively.
EVP_des_ede3_cbc(void), EVP_des_ede3(), EVP_des_ede3_ofb(void),
EVP_des_ede3_cfb(void)
Three key triple DES in CBC, ECB, CFB and OFB modes respectively.
EVP_desx_cbc(void)
DESX algorithm in CBC mode.
EVP_rc4(void)
RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.
EVP_rc4_40(void)
RC4 stream cipher with 40 bit key length. This is obsolete and new code should use EVP_rc4()
and the EVP_CIPHER_CTX_set_key_length() function.
EVP_idea_cbc() EVP_idea_ecb(void), EVP_idea_cfb(void), EVP_idea_ofb(void),
EVP_idea_cbc(void)
IDEA encryption algorithm in CBC, ECB, CFB and OFB modes respectively.
EVP_rc2_cbc(void), EVP_rc2_ecb(void), EVP_rc2_cfb(void), EVP_rc2_ofb(void)
RC2 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key
length cipher with an additional parameter called "effective key bits" or "effective key length". By
default both are set to 128 bits.
EVP_rc2_40_cbc(void), EVP_rc2_64_cbc(void)
RC2 algorithm in CBC mode with a default key length and effective key length of 40 and 64 bits.
These are obsolete and new code should use EVP_rc2_cbc(),
EVP_CIPHER_CTX_set_key_length() and EVP_CIPHER_CTX_ctrl() to set the key length and
effective key length.
EVP_bf_cbc(void), EVP_bf_ecb(void), EVP_bf_cfb(void), EVP_bf_ofb(void);
Blowfish encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable
key length cipher.
EVP_cast5_cbc(void), EVP_cast5_ecb(void), EVP_cast5_cfb(void), EVP_cast5_ofb(void)
CAST encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable
key length cipher.
EVP_rc5_32_12_16_cbc(void), EVP_rc5_32_12_16_ecb(void), EVP_rc5_32_12_16_cfb(void),
EVP_rc5_32_12_16_ofb(void)
RC5 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key
length cipher with an additional "number of rounds" parameter. By default the key length is set to
128 bits and 12 rounds.
NOTES
Where possible the EVP interface to symmetric ciphers should be used in preference to the low level
interfaces. This is because the code then becomes transparent to the cipher used and much more flexible.
PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted
data a multiple of the block size. Padding is always added so if the data is already a multiple of the block
size n will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5
padding bytes of value 5 will be added.
When decrypting the final block is checked to see if it has the correct form.
Although the decryption operation can produce an error if padding is enabled, it is not a strong test that
the input data or key is correct. A random block has better than 1 in 256 chance of being of the correct
format and problems with the input data earlier on will not produce a final decrypt error.
If padding is disabled then the decryption operation will always succeed if the total amount of data
decrypted is a multiple of the block size.
The functions EVP_EncryptInit(), EVP_EncryptFinal(), EVP_DecryptInit(), EVP_CipherInit() and
EVP_CipherFinal() are obsolete but are retained for compatibility with existing code. New code should
use EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(),
EVP_CipherInit_ex() and EVP_CipherFinal_ex() because they can reuse an existing context without
allocating and freeing it up on each call.
BUGS
For RC5 the number of rounds can currently only be set to 8, 12 or 16. This is a limitation of the current
RC5 code rather than the EVP interface.
EVP_MAX_KEY_LENGTH and EVP_MAX_IV_LENGTH only refer to the internal ciphers with
default key lengths. If custom ciphers exceed these values the results are unpredictable. This is because
it has become standard practice to define a generic key as a fixed unsigned char array containing
EVP_MAX_KEY_LENGTH bytes.
The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested for certain common
S/MIME ciphers (RC2, DES, triple DES) in CBC mode.
EXAMPLES
Get the number of rounds used in RC5:
int nrounds;
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GET_RC5_ROUNDS, 0, &nrounds);
* another source.
*/
unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
unsigned char iv[] = {1,2,3,4,5,6,7,8};
char intext[] = "Some Crypto Text";
EVP_CIPHER_CTX ctx;
FILE *out;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_bf_cbc(), NULL, key, iv);
The ciphertext from the above example can be decrypted using the openssl utility with the command
line:
S<openssl bf -in cipher.bin -K 000102030405060708090A0B0C0D0E0F
-iv 0102030405060708 -d> General encryption, decryption function example using FILE I/O
and RC2 with an 80 bit key:
int do_crypt(FILE *in, FILE *out, int do_encrypt)
{
/* Allow enough space in output buffer for additional block */
inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
/* Bogus key and IV: we’d normally set these from
* another source.
*/
unsigned char key[] = "0123456789";
unsigned char iv[] = "12345678";
/* Don’t set key or IV because we will modify the parameters */
EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, EVP_rc2(), NULL, NULL, NULL, do_encrypt);
EVP_CIPHER_CTX_set_key_length(&ctx, 10);
/* We finished modifying parameters so now we can set key and IV */
EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, do_encrypt);
for(;;)
{
inlen = fread(inbuf, 1, 1024, in);
if(inlen <= 0) break;
if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen))
{
/* Error */
return 0;
}
fwrite(outbuf, 1, outlen, out);
}
if(!EVP_CipherFinal_ex(&ctx, outbuf, &outlen))
{
/* Error */
return 0;
}
fwrite(outbuf, 1, outlen, out);
EVP_CIPHER_CTX_cleanup(&ctx);
return 1;
}
SEE ALSO
evp(3)|evp(3)
HISTORY
EVP_CIPHER_CTX_init(), EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(),
EVP_DecryptFinal_ex(), EVP_CipherInit_ex(), EVP_CipherFinal_ex() and
EVP_CIPHER_CTX_set_padding() appeared in OpenSSL 0.9.7.
EVP_PKEY allocation
EVP_PKEY_new, EVP_PKEY_free - private key allocation functions.
SYNOPSIS
#include <openssl/evp.h>
EVP_PKEY *EVP_PKEY_new(void);
void EVP_PKEY_free(EVP_PKEY *key);
DESCRIPTION
The EVP_PKEY_new() function allocates an empty EVP_PKEY structure which is used by OpenSSL
to store private keys.
EVP_PKEY_free() frees up the private key key.
NOTES
The EVP_PKEY structure is used by various OpenSSL functions which require a general private key
without reference to any particular algorithm.
The structure returned by EVP_PKEY_new() is empty. To add a private key to this empty structure the
functions described in EVP_PKEY_set1_RSA(3)|EVP_PKEY_set1_RSA(3) should be used.
RETURN VALUES
EVP_PKEY_new() returns either the newly allocated EVP_PKEY structure of NULL if an error
occurred.
EVP_PKEY_free() does not return a value.
SEE ALSO
EVP_PKEY_set1_RSA(3)|EVP_PKEY_set1_RSA(3)
HISTORY
TBA
EVP_PKEY assignment
EVP_PKEY_set1_RSA, EVP_PKEY_set1_DSA, EVP_PKEY_set1_DH, EVP_PKEY_set1_EC_KEY,
EVP_PKEY_get1_RSA, EVP_PKEY_get1_DSA, EVP_PKEY_get1_DH, EVP_PKEY_get1_EC_KEY,
EVP_PKEY_assign_RSA, EVP_PKEY_assign_DSA, EVP_PKEY_assign_DH,
EVP_PKEY_assign_EC_KEY, EVP_PKEY_type - EVP_PKEY assignment functions.
SYNOPSIS
#include <openssl/evp.h>
It is possible to call EVP_SealInit() twice in the same way as EVP_EncryptInit(). The first call should
have npubk set to 0 and (after setting any cipher parameters) it should be called again with type set to
NULL.
SEE ALSO
evp(3)|evp(3), rand(3)|rand(3), EVP_EncryptInit(3)|EVP_EncryptInit(3),
EVP_OpenInit(3)|EVP_OpenInit(3)
HISTORY
EVP_SealFinal() did not return a value before OpenSSL 0.9.7.
EVP signing
EVP_SignInit, EVP_SignUpdate, EVP_SignFinal - EVP signing functions
SYNOPSIS
#include <openssl/evp.h>
RFC 2104
SEE ALSO
sha(3)|sha(3), evp(3)|evp(3)
HISTORY
HMAC(), HMAC_Init(), HMAC_Update(), HMAC_Final() and HMAC_cleanup() are available since
SSLeay 0.9.0.
HMAC_CTX_init(), HMAC_Init_ex() and HMAC_CTX_cleanup() are available since OpenSSL 0.9.7.
#define DECLARE_LHASH_COMP_FN(f_name,o_type) \
int f_name##_LHASH_COMP(const void *, const void *);
#define IMPLEMENT_LHASH_COMP_FN(f_name,o_type) \
int f_name##_LHASH_COMP(const void *arg1, const void *arg2) { \
o_type a = (o_type)arg1; \
o_type b = (o_type)arg2; \
return f_name(a,b); }
#define LHASH_COMP_FN(f_name) f_name##_LHASH_COMP
#define DECLARE_LHASH_DOALL_FN(f_name,o_type) \
void f_name##_LHASH_DOALL(const void *);
#define IMPLEMENT_LHASH_DOALL_FN(f_name,o_type) \
void f_name##_LHASH_DOALL(const void *arg) { \
o_type a = (o_type)arg; \
f_name(a); }
#define LHASH_DOALL_FN(f_name) f_name##_LHASH_DOALL
#define DECLARE_LHASH_DOALL_ARG_FN(f_name,o_type,a_type) \
void f_name##_LHASH_DOALL_ARG(const void *, const void *);
#define IMPLEMENT_LHASH_DOALL_ARG_FN(f_name,o_type,a_type) \
void f_name##_LHASH_DOALL_ARG(const void *arg1, const void *arg2) { \
o_type a = (o_type)arg1; \
a_type b = (a_type)arg2; \
f_name(a,b); }
#define LHASH_DOALL_ARG_FN(f_name) f_name##_LHASH_DOALL_ARG
An example of a hash table storing (pointers to) structures of type ‘STUFF’ could be defined as follows;
/* Calculates the hash value of ’tohash’ (implemented elsewhere) */
unsigned long STUFF_hash(const STUFF *tohash);
/* Orders ’arg1’ and ’arg2’ (implemented elsewhere) */
int STUFF_cmp(const STUFF *arg1, const STUFF *arg2);
/* Create the type-safe wrapper functions for use in the LHASH internals */
static IMPLEMENT_LHASH_HASH_FN(STUFF_hash, const STUFF *)
static IMPLEMENT_LHASH_COMP_FN(STUFF_cmp, const STUFF *);
/* ... */
int main(int argc, char *argv[]) {
/* Create the new hash table using the hash/compare wrappers */
LHASH *hashtable = lh_new(LHASH_HASH_FN(STUFF_hash),
LHASH_COMP_FN(STUFF_cmp));
/* ... */
}
lh_free() frees the LHASH structure table. Allocated hash table entries will not be freed; consider using
lh_doall() to deallocate any remaining entries in the hash table (see below).
lh_insert() inserts the structure pointed to by data into table. If there already is an entry with the same
key, the old value is replaced. Note that lh_insert() stores pointers, the data are not copied.
lh_delete() deletes an entry from table.
lh_retrieve() looks up an entry in table. Normally, data is a structure with the key field(s) set; the
function will return a pointer to a fully populated structure.
lh_doall() will, for every entry in the hash table, call func with the data item as its parameter. For
lh_doall() and lh_doall_arg(), function pointer casting should be avoided in the callbacks (see NOTE) -
instead, either declare the callbacks to match the prototype required in lh_new() or use the
declare/implement macros to create type-safe wrappers that cast variables prior to calling your
type-specific callbacks. An example of this is illustrated here where the callback is used to cleanup
resources for items in the hash table prior to the hashtable itself being deallocated:
/* Cleans up resources belonging to ’a’ (this is implemented elsewhere) */
void STUFF_cleanup(STUFF *a);
/* Implement a prototype-compatible wrapper for "STUFF_cleanup" */
IMPLEMENT_LHASH_DOALL_FN(STUFF_cleanup, STUFF *)
/* ... then later in the code ... */
/* So to run "STUFF_cleanup" against all items in a hash table ... */
lh_doall(hashtable, LHASH_DOALL_FN(STUFF_cleanup));
/* Then the hash table itself can be deallocated */
lh_free(hashtable);
When doing this, be careful if you delete entries from the hash table in your callbacks: the table may
decrease in size, moving the item that you are currently on down lower in the hash table - this could
cause some entries to be skipped during the iteration. The second best solution to this problem is to set
hash-down_load=0 before you start (which will stop the hash table ever decreasing in size). The best
solution is probably to avoid deleting items from the hash table inside a "doall" callback!
lh_doall_arg() is the same as lh_doall() except that func will be called with arg as the second argument
and func should be of type LHASH_DOALL_ARG_FN_TYPE (a callback prototype that is passed
both the table entry and an extra argument). As with lh_doall(), you can instead choose to declare your
callback with a prototype matching the types you are dealing with and use the declare/implement macros
to create compatible wrappers that cast variables before calling your type-specific callbacks. An
example of this is demonstrated here (printing all hash table entries to a BIO that is provided by the
caller):
/* Prints item ’a’ to ’output_bio’ (this is implemented elsewhere) */
void STUFF_print(const STUFF *a, BIO *output_bio);
/* Implement a prototype-compatible wrapper for "STUFF_print" */
static IMPLEMENT_LHASH_DOALL_ARG_FN(STUFF_print, const STUFF *, BIO *)
/* ... then later in the code ... */
/* Print out the entire hashtable to a particular BIO */
lh_doall_arg(hashtable, LHASH_DOALL_ARG_FN(STUFF_print), logging_bio);
lh_error() can be used to determine if an error occurred in the last operation. lh_error() is a macro.
RETURN VALUES
lh_new() returns NULL on error, otherwise a pointer to the new LHASH structure.
When a hash table entry is replaced, lh_insert() returns the value being replaced. NULL is returned on
normal operation and on error.
lh_delete() returns the entry being deleted. NULL is returned if there is no such value in the hash table.
lh_retrieve() returns the hash table entry if it has been found, NULL otherwise.
lh_error() returns 1 if an error occurred in the last operation, 0 otherwise.
lh_free(), lh_doall() and lh_doall_arg() return no values.
NOTE
The various LHASH macros and callback types exist to make it possible to write type-safe code without
resorting to function-prototype casting - an evil that makes application code much harder to audit/verify
and also opens the window of opportunity for stack corruption and other hard-to-find bugs. It also,
apparently, violates ANSI-C.
The LHASH code regards table entries as constant data. As such, it internally represents lh_insert()‘d
items with a "const void *" pointer type. This is why callbacks such as those used by lh_doall() and
lh_doall_arg() declare their prototypes with "const", even for the parameters that pass back the table
items’ data pointers - for consistency, user-provided data is "const" at all times as far as the LHASH
code is concerned. However, as callers are themselves providing these pointers, they can choose
whether they too should be treating all such parameters as constant.
As an example, a hash table may be maintained by code that, for reasons of encapsulation, has only
"const" access to the data being indexed in the hash table (ie. it is returned as "const" from elsewhere in
their code) - in this case the LHASH prototypes are appropriate as-is. Conversely, if the caller is
responsible for the life-time of the data in question, then they may well wish to make modifications to
table item passed back in the lh_doall() or lh_doall_arg() callbacks (see the "STUFF_cleanup" example
above). If so, the caller can either cast the "const" away (if they‘re providing the raw callbacks
themselves) or use the macros to declare/implement the wrapper functions without "const" types.
Callers that only have "const" access to data they‘re indexing in a table, yet declare callbacks without
constant types (or cast the "const" away themselves), are therefore creating their own risks/bugs without
being encouraged to do so by the API. On a related note, those auditing code should pay special
attention to any instances of DECLARE/IMPLEMENT_LHASH_DOALL_[ARG_]_FN macros that
provide types without any "const" qualifiers.
BUGS
lh_insert() returns NULL both for success and error.
INTERNALS
The following description is based on the SSLeay documentation:
The lhash library implements a hash table described in the Communications of the ACM in 1991. What
makes this hash table different is that as the table fills, the hash table is increased (or decreased) in size
via OPENSSL_realloc(). When a ‘resize’ is done, instead of all hashes being redistributed over twice as
many ‘buckets‘, one bucket is split. So when an ‘expand’ is done, there is only a minimal cost to
redistribute some values. Subsequent inserts will cause more single ‘bucket’ redistributions but there
will never be a sudden large cost due to redistributing all the ‘buckets’.
The state for a particular hash table is kept in the LHASH structure. The decision to increase or decrease
the hash table size is made depending on the ‘load’ of the hash table. The load is the number of items in
the hash table divided by the size of the hash table. The default values are as follows. If (hash-up_load
< load) => expand. if (hash-down_load load) = contract. The up_load has a default value of 1 and
down_load has a default value of 2. These numbers can be modified by the application by just playing
with the up_load and down_load variables. The ‘load’ is kept in a form which is multiplied by 256. So
hash-up_load=8*256; will cause a load of 8 to be set.
If you are interested in performance the field to watch is num_comp_calls. The hash library keeps track
of the ‘hash’ value for each item so when a lookup is done, the ‘hashes’ are compared, if there is a
match, then a full compare is done, and hash-num_comp_calls is incremented. If num_comp_calls is not
equal to num_delete plus num_retrieve it means that your hash function is generating hashes that are the
same for different values. It is probably worth changing your hash function if this is the case because
even if your hash table has 10 items in a ‘bucket‘, it can be searched with 10 unsigned long compares
and 10 linked list traverses. This will be much less expensive that 10 calls to your compare function.
lh_strhash() is a demo string hashing function:
unsigned long lh_strhash(const char *c);
Since the LHASH routines would normally be passed structures, this routine would not normally be
passed to lh_new(), rather it would be used in the function passed to lh_new().
SEE ALSO
lh_stats(3)|lh_stats(3)
HISTORY
The lhash library is available in all versions of SSLeay and OpenSSL. lh_error() was added in SSLeay
0.9.1b.
This manpage is derived from the SSLeay documentation.
In OpenSSL 0.9.7, all lhash functions that were passed function pointers were changed for better type
safety, and the function types LHASH_COMP_FN_TYPE, LHASH_HASH_FN_TYPE,
LHASH_DOALL_FN_TYPE and LHASH_DOALL_ARG_FN_TYPE became available.
LH statistics
lh_stats, lh_node_stats, lh_node_usage_stats, lh_stats_bio, lh_node_stats_bio, lh_node_usage_stats_bio -
LHASH statistics
SYNOPSIS
#include <openssl/lhash.h>
#include <openssl/md4.h>
#include <openssl/md5.h>
CONFORMING TO
RFC 1319, RFC 1320, RFC 1321
SEE ALSO
sha(3)|sha(3), ripemd(3)|ripemd(3), EVP_DigestInit(3)|EVP_DigestInit(3)
HISTORY
MD2(), MD2_Init(), MD2_Update() MD2_Final(), MD5(), MD5_Init(), MD5_Update() and
MD5_Final() are available in all versions of SSLeay and OpenSSL.
MD4(), MD4_Init(), and MD4_Update() are available in OpenSSL 0.9.6 and above.
MDC2 hash
MDC2, MDC2_Init, MDC2_Update, MDC2_Final - MDC2 hash function
SYNOPSIS
#include <openssl/mdc2.h>
obj = OBJ_nid2obj(new_nid);
void OpenSSL_add_all_algorithms(void);
void OpenSSL_add_all_ciphers(void);
void OpenSSL_add_all_digests(void);
void EVP_cleanup(void);
DESCRIPTION
OpenSSL keeps an internal table of digest algorithms and ciphers. It uses this table to lookup ciphers via
functions such as EVP_get_cipher_byname().
OpenSSL_add_all_digests() adds all digest algorithms to the table.
OpenSSL_add_all_algorithms() adds all algorithms to the table (digests and ciphers).
OpenSSL_add_all_ciphers() adds all encryption algorithms to the table including password based
encryption algorithms.
EVP_cleanup() removes all ciphers and digests from the table.
RETURN VALUES
None of the functions return a value.
NOTES
A typical application will will call OpenSSL_add_all_algorithms() initially and EVP_cleanup() before
exiting.
An application does not need to add algorithms to use them explicitly, for example by EVP_sha1(). It
just needs to add them if it (or any of the functions it calls) needs to lookup algorithms.
The cipher and digest lookup functions are used in many parts of the library. If the table is not initialized
several functions will misbehave and complain they cannot find algorithms. This includes the PEM,
PKCS#12, SSL and S/MIME libraries. This is a common query in the OpenSSL mailing lists.
Calling OpenSSL_add_all_algorithms() links in all algorithms: as a result a statically linked executable
can be quite large. If this is important it is possible to just add the required ciphers and digests.
BUGS
Although the functions do not return error codes it is possible for them to fail. This will only happen as a
result of a memory allocation failure so this is not too much of a problem in practice.
SEE ALSO
evp(3)|evp(3), EVP_DigestInit(3)|EVP_DigestInit(3), EVP_EncryptInit(3)|EVP_EncryptInit(3)
#include <openssl/crypto.h>
long SSLeay(void);
const char *SSLeay_version(int t);
DESCRIPTION
OPENSSL_VERSION_NUMBER is a numeric release version identifier:
MMNNFFPPS: major minor fix patch status
The status nibble has one of the values 0 for development, 1 to e for betas 1 to 14, and f for release.
for example
0x000906000 == 0.9.6 dev
0x000906023 == 0.9.6b beta 3
0x00090605f == 0.9.6e release
Versions prior to 0.9.3 have identifiers < 0x0930. Versions between 0.9.3 and 0.9.5 had a version
identifier with this interpretation:
MMNNFFRBB major minor fix final beta/patch
for example
0x000904100 == 0.9.4 release
0x000905000 == 0.9.5 dev
Version 0.9.5a had an interim interpretation that is like the current one, except the patch level got the
highest bit set, to keep continuity. The number was therefore 0x0090581f.
SSLEAY_VERSION
The text variant of the version number and the release date. For example, "OpenSSL 0.9.5a 1 Apr
2000".
SSLEAY_CFLAGS
The compiler flags set for the compilation process in the form "compiler: ..." if available or
"compiler: information not available" otherwise.
SSLEAY_BUILT_ON
The date of the build process in the form "built on: ..." if available or "built on: date not available"
otherwise.
SSLEAY_PLATFORM
The "Configure" target of the library build in the form "platform: ..." if available or "platform:
information not available" otherwise.
SSLEAY_DIR
The "OPENSSLDIR" setting of the library build in the form "OPENSSLDIR: "..."" if available or
"OPENSSLDIR: N/A" otherwise.
SEE ALSO
crypto(3)|crypto(3)
HISTORY
SSLeay() and SSLEAY_VERSION_NUMBER are available in all versions of SSLeay and OpenSSL.
OPENSSL_VERSION_NUMBER is available in all versions of OpenSSL. SSLEAY_DIR was added in
OpenSSL 0.9.7.
PEM routines
PEM - PEM routines
SYNOPSIS
#include <openssl/pem.h>
DESCRIPTION
The PEM functions read or write structures in PEM format. In this sense PEM format is simply base64
encoded data surrounded by header lines.
For more details about the meaning of arguments see the PEM FUNCTION ARGUMENTS section.
Each operation has four functions associated with it. For clarity the term "foobar functions" will be used
to collectively refer to the PEM_read_bio_foobar(), PEM_read_foobar(), PEM_write_bio_foobar() and
PEM_write_foobar() functions.
The PrivateKey functions read or write a private key in PEM format using an EVP_PKEY structure.
The write routines use "traditional" private key format and can handle both RSA and DSA private keys.
The read functions can additionally transparently handle PKCS#8 format encrypted and unencrypted
keys too.
PEM_write_bio_PKCS8PrivateKey() and PEM_write_PKCS8PrivateKey() write a private key in an
EVP_PKEY structure in PKCS#8 EncryptedPrivateKeyInfo format using PKCS#5 v2.0 password based
encryption algorithms. The cipher argument specifies the encryption algoritm to use: unlike all other
PEM routines the encryption is applied at the PKCS#8 level and not in the PEM headers. If cipher is
NULL then no encryption is used and a PKCS#8 PrivateKeyInfo structure is used instead.
PEM_write_bio_PKCS8PrivateKey_nid() and PEM_write_PKCS8PrivateKey_nid() also write out a
private key as a PKCS#8 EncryptedPrivateKeyInfo however it uses PKCS#5 v1.5 or PKCS#12
encryption algorithms instead. The algorithm to use is specified in the nid parameter and should be the
NID of the corresponding OBJECT IDENTIFIER (see NOTES section).
The PUBKEY functions process a public key using an EVP_PKEY structure. The public key is encoded
as a SubjectPublicKeyInfo structure.
The RSAPrivateKey functions process an RSA private key using an RSA structure. It handles the same
formats as the PrivateKey functions but an error occurs if the private key is not RSA.
The RSAPublicKey functions process an RSA public key using an RSA structure. The public key is
encoded using a PKCS#1 RSAPublicKey structure.
The RSA_PUBKEY functions also process an RSA public key using an RSA structure. However the
public key is encoded using a SubjectPublicKeyInfo structure and an error occurs if the public key is not
RSA.
The DSAPrivateKey functions process a DSA private key using a DSA structure. It handles the same
formats as the PrivateKey functions but an error occurs if the private key is not DSA.
The DSA_PUBKEY functions process a DSA public key using a DSA structure. The public key is
encoded using a SubjectPublicKeyInfo structure and an error occurs if the public key is not DSA.
The DSAparams functions process DSA parameters using a DSA structure. The parameters are encoded
using a foobar structure.
The DHparams functions process DH parameters using a DH structure. The parameters are encoded
using a PKCS#3 DHparameter structure.
The X509 functions process an X509 certificate using an X509 structure. They will also process a
trusted X509 certificate but any trust settings are discarded.
The X509_AUX functions process a trusted X509 certificate using an X509 structure.
The X509_REQ and X509_REQ_NEW functions process a PKCS#10 certificate request using an
X509_REQ structure. The X509_REQ write functions use CERTIFICATE REQUEST in the header
whereas the X509_REQ_NEW functions use NEW CERTIFICATE REQUEST (as required by some
CAs). The X509_REQ read functions will handle either form so there are no X509_REQ_NEW read
functions.
The X509_CRL functions process an X509 CRL using an X509_CRL structure.
The PKCS7 functions process a PKCS#7 ContentInfo using a PKCS7 structure.
The NETSCAPE_CERT_SEQUENCE functions process a Netscape Certificate Sequence using a
NETSCAPE_CERT_SEQUENCE structure.
PEM FUNCTION ARGUMENTS
The PEM functions have many common arguments.
The bp BIO parameter (if present) specifies the BIO to read from or write to.
The fp FILE parameter (if present) specifies the FILE pointer to read from or write to.
The PEM read functions all take an argument TYPE **x and return a TYPE * pointer. Where TYPE is
whatever structure the function uses. If x is NULL then the parameter is ignored. If x is not NULL but
*x is NULL then the structure returned will be written to *x. If neither x nor *x is NULL then an attempt
is made to reuse the structure at *x (but see BUGS and EXAMPLES sections). Irrespective of the value
of x a pointer to the structure is always returned (or NULL if an error occurred).
The PEM functions which write private keys take an enc parameter which specifies the encryption
algorithm to use, encryption is done at the PEM level. If this parameter is set to NULL then the private
key is written in unencrypted form.
The cb argument is the callback to use when querying for the pass phrase used for encrypted PEM
structures (normally only private keys).
For the PEM write routines if the kstr parameter is not NULL then klen bytes at kstr are used as the
passphrase and cb is ignored.
If the cb parameters is set to NULL and the u parameter is not NULL then the u parameter is interpreted
as a null terminated string to use as the passphrase. If both cb and u are NULL then the default callback
routine is used which will typically prompt for the passphrase on the current terminal with echoing
turned off.
The default passphrase callback is sometimes inappropriate (for example in a GUI application) so an
alternative can be supplied. The callback routine has the following form:
int cb(char *buf, int size, int rwflag, void *u);
buf is the buffer to write the passphrase to. size is the maximum length of the passphrase (i.e. the size of
buf). rwflag is a flag which is set to 0 when reading and 1 when writing. A typical routine will ask the
user to verify the passphrase (for example by prompting for it twice) if rwflag is 1. The u parameter has
the same value as the u parameter passed to the PEM routine. It allows arbitrary data to be passed to the
callback by the application (for example a window handle in a GUI application). The callback must
return the number of characters in the passphrase or 0 if an error occurred.
EXAMPLES
Although the PEM routines take several arguments in almost all applications most of them are set to 0 or
NULL.
Read a certificate in PEM format from a BIO:
X509 *x;
x = PEM_read_bio(bp, NULL, 0, NULL);
if (x == NULL)
{
/* Error */
}
Alternative method:
X509 *x = NULL;
if (!PEM_read_bio_X509(bp, &x, 0, NULL))
{
/* Error */
}
Write a private key (using traditional format) to a BIO using triple DES encryption, the pass phrase is
prompted for:
if (!PEM_write_bio_PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, NULL))
{
/* Error */
}
Write a private key (using PKCS#8 format) to a BIO using triple DES encryption, using the pass phrase
"hello":
if (!PEM_write_bio_PKCS8PrivateKey(bp, key, EVP_des_ede3_cbc(),
NULL, 0, 0, "hello"))
{
/* Error */
}
Read a private key from a BIO using the pass phrase "hello":
key = PEM_read_bio_PrivateKey(bp, NULL, 0, "hello");
if (key == NULL)
{
/* Error */
}
this is a bug because an attempt will be made to reuse the data at x which is an uninitialised pointer.
PEM ENCRYPTION FORMAT
This old PrivateKey routines use a non standard technique for encryption.
The private key (or other data) takes the following form:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,3F17F5316E2BAC89
The line beginning DEK-Info contains two comma separated pieces of information: the encryption
algorithm name as used by EVP_get_cipherbyname() and an 8 byte salt encoded as a set of hexadecimal
digits.
After this is the base64 encoded encrypted data.
The encryption key is determined using EVP_bytestokey(), using salt and an iteration count of 1. The IV
used is the value of salt and *not* the IV returned by EVP_bytestokey().
BUGS
The PEM read routines in some versions of OpenSSL will not correctly reuse an existing structure.
Therefore the following:
PEM_read_bio(bp, &x, 0, NULL);
is guaranteed to work.
RETURN CODES
The read routines return either a pointer to the structure read or NULL is an error occurred.
The write routines return 1 for success or 0 for failure.
PKCS12_create
PKCS12_create - create a PKCS#12 structure
SYNOPSIS
#include <openssl/pkcs12.h>
PKCS12_parse
PKCS12_parse - parse a PKCS#12 structure
SYNOPSIS
#include <openssl/pkcs12.h>
int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert,
STACK_OF(X509) **ca);
DESCRIPTION
PKCS12_parse() parses a PKCS12 structure.
p12 is the PKCS12 structure to parse. pass is the passphrase to use. If successful the private key will be
written to *pkey, the corresponding certificate to *cert and any additional certificates to *ca.
NOTES
The parameters pkey and cert cannot be NULL. ca can be <NULL> in which case additional
certificates will be discarded. *ca can also be a valid STACK in which case additional certificates are
appended to *ca. If *ca is NULL a new STACK will be allocated.
The friendlyName and localKeyID attributes (if present) on each certificate will be stored in the alias
and keyid attributes of the X509 structure.
BUGS
Only a single private key and corresponding certificate is returned by this function. More complex
PKCS#12 files with multiple private keys will only return the first match.
Only friendlyName and localKeyID attributes are currently stored in certificates. Other attributes are
discarded.
Attributes currently cannot be store in the private key EVP_PKEY structure.
SEE ALSO
d2i_PKCS12(3)|d2i_PKCS12(3)
HISTORY
PKCS12_parse was added in OpenSSL 0.9.3
PKCS7_decrypt
PKCS7_decrypt - decrypt content from a PKCS#7 envelopedData structure
SYNOPSIS
int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags);
DESCRIPTION
PKCS7_decrypt() extracts and decrypts the content from a PKCS#7 envelopedData structure. pkey is
the private key of the recipient, cert is the recipients certificate, data is a BIO to write the content to and
flags is an optional set of flags.
NOTES
OpenSSL_add_all_algorithms() (or equivalent) should be called before using this function or errors
about unknown algorithms will occur.
Although the recipients certificate is not needed to decrypt the data it is needed to locate the appropriate
(of possible several) recipients in the PKCS#7 structure.
The following flags can be passed in the flags parameter.
If the PKCS7_TEXT flag is set MIME headers for type text/plain are deleted from the content. If the
content is not of type text/plain then an error is returned.
RETURN VALUES
PKCS7_decrypt() returns either 1 for success or 0 for failure. The error can be obtained from
ERR_get_error(3)
BUGS
PKCS7_decrypt() must be passed the correct recipient key and certificate. It would be better if it could
look up the correct key and certificate from a database.
The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign()
also applies to PKCS7_verify().
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_encrypt(3)|PKCS7_encrypt(3)
HISTORY
PKCS7_decrypt() was added to OpenSSL 0.9.5
PKCS7_encrypt
PKCS7_encrypt - create a PKCS#7 envelopedData structure
SYNOPSIS
PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, int flags);
DESCRIPTION
PKCS7_encrypt() creates and returns a PKCS#7 envelopedData structure. certs is a list of recipient
certificates. in is the content to be encrypted. cipher is the symmetric cipher to use. flags is an optional
set of flags.
NOTES
Only RSA keys are supported in PKCS#7 and envelopedData so the recipient certificates supplied to this
function must all contain RSA public keys, though they do not have to be signed using the RSA
algorithm.
EVP_des_ede3_cbc() (triple DES) is the algorithm of choice for S/MIME use because most clients will
support it.
Some old "export grade" clients may only support weak encryption using 40 or 64 bit RC2. These can be
used by passing EVP_rc2_40_cbc() and EVP_rc2_64_cbc() respectively.
The algorithm passed in the cipher parameter must support ASN1 encoding of its parameters.
Many browsers implement a "sign and encrypt" option which is simply an S/MIME envelopedData
containing an S/MIME signed message. This can be readily produced by storing the S/MIME signed
message in a memory BIO and passing it to PKCS7_encrypt().
The following flags can be passed in the flags parameter.
If the PKCS7_TEXT flag is set MIME headers for type text/plain are prepended to the data.
Normally the supplied content is translated into MIME canonical format (as required by the S/MIME
specifications) if PKCS7_BINARY is set no translation occurs. This option should be used if the
supplied data is in binary format otherwise the translation will corrupt it. If PKCS7_BINARY is set then
PKCS7_TEXT is ignored.
RETURN VALUES
PKCS7_encrypt() returns either a valid PKCS7 structure or NULL if an error occurred. The error can be
obtained from ERR_get_error(3).
BUGS
The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign()
also applies to PKCS7_verify().
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_decrypt(3)|PKCS7_decrypt(3)
HISTORY
PKCS7_decrypt() was added to OpenSSL 0.9.5
PKCS7_sign
PKCS7_sign - create a PKCS#7 signedData structure
SYNOPSIS
PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
BIO *data, int flags);
DESCRIPTION
PKCS7_sign() creates and returns a PKCS#7 signedData structure. signcert is the certificate to sign
with, pkey is the corresponsding private key. certs is an optional additional set of certificates to include
in the PKCS#7 structure (for example any intermediate CAs in the chain).
The data to be signed is read from BIO data.
flags is an optional set of flags.
NOTES
Any of the following flags (ored together) can be passed in the flags parameter.
Many S/MIME clients expect the signed content to include valid MIME headers. If the PKCS7_TEXT
flag is set MIME headers for type text/plain are prepended to the data.
If PKCS7_NOCERTS is set the signer‘s certificate will not be included in the PKCS7 structure, the
signer‘s certificate must still be supplied in the signcert parameter though. This can reduce the size of
the signature if the signers certificate can be obtained by other means: for example a previously signed
message.
The data being signed is included in the PKCS7 structure, unless PKCS7_DETACHED is set in which
case it is omitted. This is used for PKCS7 detached signatures which are used in S/MIME plaintext
signed messages for example.
Normally the supplied content is translated into MIME canonical format (as required by the S/MIME
specifications) if PKCS7_BINARY is set no translation occurs. This option should be used if the
supplied data is in binary format otherwise the translation will corrupt it.
The signedData structure includes several PKCS#7 autenticatedAttributes including the signing time, the
PKCS#7 content type and the supported list of ciphers in an SMIMECapabilities attribute. If
PKCS7_NOATTR is set then no authenticatedAttributes will be used. If PKCS7_NOSMIMECAP is
set then just the SMIMECapabilities are omitted.
If present the SMIMECapabilities attribute indicates support for the following algorithms: triple DES,
128 bit RC2, 64 bit RC2, DES and 40 bit RC2. If any of these algorithms is disabled then it will not be
included.
BUGS
PKCS7_sign() is somewhat limited. It does not support multiple signers, some advanced attributes such
as counter signatures are not supported.
The SHA1 digest algorithm is currently always used.
When the signed data is not detached it will be stored in memory within the PKCS7 structure. This
effectively limits the size of messages which can be signed due to memory restraints. There should be a
way to sign data without having to hold it all in memory, this would however require fairly major
revisions of the OpenSSL ASN1 code.
Clear text signing does not store the content in memory but the way PKCS7_sign() operates means that
two passes of the data must typically be made: one to compute the signatures and a second to output the
data along with the signature. There should be a way to process the data with only a single pass.
RETURN VALUES
PKCS7_sign() returns either a valid PKCS7 structure or NULL if an error occurred. The error can be
obtained from ERR_get_error(3).
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_verify(3)|PKCS7_verify(3)
HISTORY
PKCS7_sign() was added to OpenSSL 0.9.5
PKCS7_verify
PKCS7_verify - verify a PKCS#7 signedData structure
SYNOPSIS
int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store,
BIO *indata, BIO *out, int flags);
int PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags);
DESCRIPTION
PKCS7_verify() verifies a PKCS#7 signedData structure. p7 is the PKCS7 structure to verify. certs is a
set of certificates in which to search for the signer‘s certificate. store is a trusted certficate store (used
for chain verification). indata is the signed data if the content is not present in p7 (that is it is detached).
The content is written to out if it is not NULL.
flags is an optional set of flags, which can be used to modify the verify operation.
PKCS7_get0_signers() retrieves the signer‘s certificates from p7, it does not check their validity or
whether any signatures are valid. The certs and flags parameters have the same meanings as in
PKCS7_verify().
VERIFY PROCESS
Normally the verify process proceeds as follows.
Initially some sanity checks are performed on p7. The type of p7 must be signedData. There must be at
least one signature on the data and if the content is detached indata cannot be NULL.
An attempt is made to locate all the signer‘s certificates, first looking in the certs parameter (if it is not
NULL) and then looking in any certificates contained in the p7 structure itself. If any signer‘s
certificates cannot be located the operation fails.
Each signer‘s certificate is chain verified using the smimesign purpose and the supplied trusted
certificate store. Any internal certificates in the message are used as untrusted CAs. If any chain verify
fails an error code is returned.
Finally the signed content is read (and written to out is it is not NULL) and the signature‘s checked.
If all signature‘s verify correctly then the function is successful.
Any of the following flags (ored together) can be passed in the flags parameter to change the default
verify behaviour. Only the flag PKCS7_NOINTERN is meaningful to PKCS7_get0_signers().
If PKCS7_NOINTERN is set the certificates in the message itself are not searched when locating the
signer‘s certificate. This means that all the signers certificates must be in the certs parameter.
If the PKCS7_TEXT flag is set MIME headers for type text/plain are deleted from the content. If the
content is not of type text/plain then an error is returned.
If PKCS7_NOVERIFY is set the signer‘s certificates are not chain verified.
If PKCS7_NOCHAIN is set then the certificates contained in the message are not used as untrusted
CAs. This means that the whole verify chain (apart from the signer‘s certificate) must be contained in
the trusted store.
If PKCS7_NOSIGS is set then the signatures on the data are not checked.
NOTES
One application of PKCS7_NOINTERN is to only accept messages signed by a small number of
certificates. The acceptable certificates would be passed in the certs parameter. In this case if the signer
is not one of the certificates supplied in certs then the verify will fail because the signer cannot be found.
Care should be taken when modifying the default verify behaviour, for example setting
PKCS7_NOVERIFY|PKCS7_NOSIGS will totally disable all verification and any signed message
will be considered valid. This combination is however useful if one merely wishes to write the content to
out and its validity is not considered important.
Chain verification should arguably be performed using the signing time rather than the current time.
However since the signing time is supplied by the signer it cannot be trusted without additional evidence
(such as a trusted timestamp).
RETURN VALUES
PKCS7_verify() returns 1 for a successful verification and zero or a negative value if an error occurs.
PKCS7_get0_signers() returns all signers or NULL if an error occurred.
The error can be obtained from ERR_get_error(3)|ERR_get_error(3)
BUGS
The trusted certificate store is not searched for the signers certificate, this is primarily due to the
inadequacies of the current X509_STORE functionality.
The lack of single pass processing and need to hold all data in memory as mentioned in PKCS7_sign()
also applies to PKCS7_verify().
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_sign(3)|PKCS7_sign(3)
HISTORY
PKCS7_verify() was added to OpenSSL 0.9.5
void RAND_cleanup(void);
1 A good hashing algorithm to mix things up and to convert the RNG ‘state’ to random numbers.
2 An initial source of random ‘state’.
3 The state should be very large. If the RNG is being used to generate 4096 bit RSA keys, 2 2048
bit random strings are required (at a minimum). If your RNG state only has 128 bits, you are
obviously limiting the search space to 128 bits, not 2048. I‘m probably getting a little carried
away on this last point but it does indicate that it may not be a bad idea to keep quite a lot of RNG
state. It should be easier to break a cipher than guess the RNG seed data.
4 Any RNG seed data should influence all subsequent random numbers generated. This implies that
any random seed data entered will have an influence on all subsequent random numbers generated.
5 When using data to seed the RNG state, the data used should not be extractable from the RNG
state. I believe this should be a requirement because one possible source of ‘secret’ semi random
data would be a private key or a password. This data must not be disclosed by either subsequent
random numbers or a ‘core’ dump left by a program crash.
6 Given the same initial ‘state‘, 2 systems should deviate in their RNG state (and hence the random
numbers generated) over time if at all possible.
7 Given the random number output stream, it should not be possible to determine the RNG state or
the next random number.
RAND entropy
RAND_add, RAND_seed, RAND_status, RAND_event, RAND_screen - add entropy to the PRNG
SYNOPSIS
#include <openssl/rand.h>
int RAND_status(void);
RAND cleanup
RAND_cleanup - erase the PRNG state
SYNOPSIS
#include <openssl/rand.h>
void RAND_cleanup(void);
DESCRIPTION
RAND_cleanup() erases the memory used by the PRNG.
RETURN VALUE
RAND_cleanup() returns no value.
SEE ALSO
rand(3)|rand(3)
HISTORY
RAND_cleanup() is available in all versions of SSLeay and OpenSSL.
RAND_METHOD *RAND_SSLeay(void);
DESCRIPTION
A RAND_METHOD specifies the functions that OpenSSL uses for random number generation. By
modifying the method, alternative implementations such as hardware RNGs may be used.
IMPORTANT: See the NOTES section for important information about how these RAND API functions
are affected by the use of ENGINE API calls.
Initially, the default RAND_METHOD is the OpenSSL internal implementation, as returned by
RAND_SSLeay().
RAND_set_default_method() makes meth the method for PRNG use. NB: This is true only whilst no
ENGINE has been set as a default for RAND, so this function is no longer recommended.
RAND_get_default_method() returns a pointer to the current RAND_METHOD. However, the
meaningfulness of this result is dependant on whether the ENGINE API is being used, so this function is
no longer recommended.
THE RAND_METHOD STRUCTURE
typedef struct rand_meth_st
{
void (*seed)(const void *buf, int num);
int (*bytes)(unsigned char *buf, int num);
void (*cleanup)(void);
void (*add)(const void *buf, int num, int entropy);
int (*pseudorand)(unsigned char *buf, int num);
int (*status)(void);
} RAND_METHOD;
RC4 encryption
RC4_set_key, RC4 - RC4 encryption
SYNOPSIS
#include <openssl/rc4.h>
void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
unsigned char *outdata);
DESCRIPTION
This library implements the Alleged RC4 cipher, which is described for example in Applied
Cryptography. It is believed to be compatible with RC4[TM], a proprietary cipher of RSA Security Inc.
RC4 is a stream cipher with variable key length. Typically, 128 bit (16 byte) keys are used for strong
encryption, but shorter insecure key sizes have been widely used due to export restrictions.
RC4 consists of a key setup phase and the actual encryption or decryption phase.
RC4_set_key() sets up the RC4_KEY key using the len bytes long key at data.
RC4() encrypts or decrypts the len bytes of data at indata using key and places the result at outdata.
Repeated RC4() calls with the same key yield a continuous key stream.
Since RC4 is a stream cipher (the input is XORed with a pseudo-random key stream to produce the
output), decryption uses the same function calls as encryption.
Applications should use the higher level functions EVP_EncryptInit(3)|EVP_EncryptInit(3) etc. instead
of calling the RC4 functions directly.
RETURN VALUES
RC4_set_key() and RC4() do not return values.
NOTE
Certain conditions have to be observed to securely use stream ciphers. It is not permissible to perform
multiple encryptions using the same key stream.
SEE ALSO
blowfish(3)|blowfish(3), des(3)|des(3), rc2(3)|rc2(3)
HISTORY
RC4_set_key() and RC4() are available in all versions of SSLeay and OpenSSL.
RIPEMD-160 hash
RIPEMD160, RIPEMD160_Init, RIPEMD160_Update, RIPEMD160_Final - RIPEMD-160 hash
function
SYNOPSIS
#include <openssl/ripemd.h>
RSA * RSA_new(void);
void RSA_free(RSA *rsa);
DESCRIPTION
These functions implement RSA public key encryption and signatures as defined in PKCS #1 v2.0 [RFC
2437].
The RSA structure consists of several BIGNUM components. It can contain public as well as private
RSA keys:
struct
{
BIGNUM *n; // public modulus
BIGNUM *e; // public exponent
BIGNUM *d; // private exponent
BIGNUM *p; // secret prime factor
BIGNUM *q; // secret prime factor
BIGNUM *dmp1; // d mod (p-1)
BIGNUM *dmq1; // d mod (q-1)
BIGNUM *iqmp; // q^-1 mod p
// ...
};
RSA
In public keys, the private exponent and the related secret values are NULL.
p, q, dmp1, dmq1 and iqmp may be NULL in private keys, but the RSA operations are much faster
when these values are available.
Note that RSA keys may use non-standard RSA_METHOD implementations, either directly or by the
use of ENGINE modules. In some cases (eg. an ENGINE providing support for hardware-embedded
keys), these BIGNUM values will not be used by the implementation or may be used for alternative data
storage. For this reason, applications should generally avoid using RSA structure elements directly and
instead use API functions to query or modify keys.
CONFORMING TO
SSL, PKCS #1 v2.0
PATENTS
RSA was covered by a US patent which expired in September 2000.
SEE ALSO
rsa(1)|rsa(1), bn(3)|bn(3), dsa(3)|dsa(3), dh(3)|dh(3), rand(3)|rand(3), engine(3)|engine(3),
RSA_new(3)|RSA_new(3), RSA_public_encrypt(3)|RSA_public_encrypt(3), RSA_sign(3)|RSA_sign(3),
RSA_size(3)|RSA_size(3), RSA_generate_key(3)|RSA_generate_key(3),
RSA_check_key(3)|RSA_check_key(3), RSA_blinding_on(3)|RSA_blinding_on(3),
RSA_set_method(3)|RSA_set_method(3), RSA_print(3)|RSA_print(3),
RSA_get_ex_new_index(3)|RSA_get_ex_new_index(3),
RSA_private_encrypt(3)|RSA_private_encrypt(3),
RSA_sign_ASN1_OCTET_STRING(3)|RSA_sign_ASN1_OCTET_STRING(3),
RSA_padding_add_PKCS1_type_1(3)|RSA_padding_add_PKCS1_type_1(3)
RSA allocation
RSA_new, RSA_free - allocate and free RSA objects
SYNOPSIS
#include <openssl/rsa.h>
RSA * RSA_new(void);
PKCS1_type_1
PKCS #1 v2.0 EMSA-PKCS1-v1_5 (PKCS #1 v1.5 block type 1); used for signatures
PKCS1_type_2
PKCS #1 v2.0 EME-PKCS1-v1_5 (PKCS #1 v1.5 block type 2)
PKCS1_OAEP
PKCS #1 v2.0 EME-OAEP
SSLv23
#include <openssl/dsa.h>
#include <openssl/dh.h>
RSA_PKCS1_PADDING
PKCS #1 v1.5 padding. This function does not handle the algorithmIdentifier specified in PKCS
#1. When generating or verifying PKCS #1 signatures, RSA_sign(3)|RSA_sign(3) and
RSA_verify(3)|RSA_verify(3) should be used.
RSA_NO_PADDING
Raw RSA signature. This mode should only be used to implement cryptographically sound
padding modes in the application code. Signing user data directly with RSA is insecure.
RSA_public_decrypt() recovers the message digest from the flen bytes long signature at from using the
signer‘s public key rsa. to must point to a memory section large enough to hold the message digest
(which is smaller than RSA_size(rsa) - 11). padding is the padding mode that was used to sign the data.
RETURN VALUES
RSA_private_encrypt() returns the size of the signature (i.e., RSA_size(rsa)). RSA_public_decrypt()
returns the size of the recovered message digest.
On error, -1 is returned; the error codes can be obtained by ERR_get_error(3)|ERR_get_error(3).
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), rsa(3)|rsa(3), RSA_sign(3)|RSA_sign(3),
RSA_verify(3)|RSA_verify(3)
HISTORY
The padding argument was added in SSLeay 0.8. RSA_NO_PADDING is available since SSLeay 0.9.0.
RSA_PKCS1_PADDING
PKCS #1 v1.5 padding. This currently is the most widely used mode.
RSA_PKCS1_OAEP_PADDING
EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty encoding parameter.
This mode is recommended for all new applications.
RSA_SSLV23_PADDING
PKCS #1 v1.5 padding with an SSL-specific modification that denotes that the server is SSL3
capable.
RSA_NO_PADDING
Raw RSA encryption. This mode should only be used to implement cryptographically sound
padding modes in the application code. Encrypting user data directly with RSA is insecure.
flen must be less than RSA_size(rsa) - 11 for the PKCS #1 v1.5 based padding modes, and less than
RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING. The random number generator must be
seeded prior to calling RSA_public_encrypt().
RSA_private_decrypt() decrypts the flen bytes at from using the private key rsa and stores the plaintext
in to. to must point to a memory section large enough to hold the decrypted data (which is smaller than
RSA_size(rsa)). padding is the padding mode that was used to encrypt the data.
RETURN VALUES
RSA_public_encrypt() returns the size of the encrypted data (i.e., RSA_size(rsa)).
RSA_private_decrypt() returns the size of the recovered plaintext.
On error, -1 is returned; the error codes can be obtained by ERR_get_error(3)|ERR_get_error(3).
CONFORMING TO
SSL, PKCS #1 v2.0
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), rand(3)|rand(3), rsa(3)|rsa(3), RSA_size(3)|RSA_size(3)
HISTORY
The padding argument was added in SSLeay 0.8. RSA_NO_PADDING is available since SSLeay 0.9.0,
OAEP was added in OpenSSL 0.9.2b.
RSA_METHOD *RSA_get_default_method(void);
RSA_METHOD *RSA_PKCS1_SSLeay(void);
RSA_METHOD *RSA_null_method(void);
/* encrypt */
int (*rsa_pub_enc)(int flen, unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
/* decrypt */
int (*rsa_priv_dec)(int flen, unsigned char *from,
unsigned char *to, RSA *rsa, int padding);
/* called at RSA_new */
int (*init)(RSA *rsa);
/* called at RSA_free */
int (*finish)(RSA *rsa);
char *app_data; /* ?? */
} RSA_METHOD;
RETURN VALUES
RSA_PKCS1_SSLeay(), RSA_PKCS1_null_method(), RSA_get_default_method() and
RSA_get_method() return pointers to the respective RSA_METHODs.
RSA_set_default_method() returns no value.
RSA_set_method() returns a pointer to the old RSA_METHOD implementation that was replaced.
However, this return value should probably be ignored because if it was supplied by an ENGINE, the
pointer could be invalidated at any time if the ENGINE is unloaded (in fact it could be unloaded as a
result of the RSA_set_method() function releasing its handle to the ENGINE). For this reason, the return
type may be replaced with a void declaration in a future release.
RSA_new_method() returns NULL and sets an error code that can be obtained by
ERR_get_error(3)|ERR_get_error(3) if the allocation fails. Otherwise it returns a pointer to the newly
allocated structure.
NOTES
As of version 0.9.7, RSA_METHOD implementations are grouped together with other algorithmic APIs
(eg. DSA_METHOD, EVP_CIPHER, etc) into ENGINE modules. If a default ENGINE is specified for
RSA functionality using an ENGINE API function, that will override any RSA defaults set using the
RSA API (ie. RSA_set_default_method()). For this reason, the ENGINE API is the recommended way
to control default implementations for use in RSA and other cryptographic algorithms.
BUGS
The behaviour of RSA_flags() is a mis-feature that is left as-is for now to avoid creating compatibility
problems. RSA functionality, such as the encryption functions, are controlled by the flags value in the
RSA key itself, not by the flags value in the RSA_METHOD attached to the RSA key (which is what
this function returns). If the flags element of an RSA key is changed, the changes will be honoured by
RSA functionality but will not be reflected in the return value of the RSA_flags() function - in effect
RSA_flags() behaves more like an RSA_default_flags() function (which does not currently exist).
SEE ALSO
rsa(3)|rsa(3), RSA_new(3)|RSA_new(3)
HISTORY
RSA_new_method() and RSA_set_default_method() appeared in SSLeay 0.8.
RSA_get_default_method(), RSA_set_method() and RSA_get_method() as well as the rsa_sign and
rsa_verify components of RSA_METHOD were added in OpenSSL 0.9.4.
RSA_set_default_openssl_method() and RSA_get_default_openssl_method() replaced
RSA_set_default_method() and RSA_get_default_method() respectively, and RSA_set_method() and
RSA_new_method() were altered to use ENGINEs rather than RSA_METHODs during development
of the engine version of OpenSSL 0.9.6. For 0.9.7, the handling of defaults in the ENGINE API was
restructured so that this change was reversed, and behaviour of the other functions resembled more
closely the previous behaviour. The behaviour of defaults in the ENGINE API now transparently
overrides the behaviour of defaults in the RSA API without requiring changing these function
prototypes.
RSA signatures
RSA_sign, RSA_verify - RSA signatures
SYNOPSIS
#include <openssl/rsa.h>
RSA size
RSA_size - get RSA modulus size
SYNOPSIS
#include <openssl/rsa.h>
SMIME parse
SMIME_read_PKCS7 - parse S/MIME message.
SYNOPSIS
PKCS7 *SMIME_read_PKCS7(BIO *in, BIO **bcont);
DESCRIPTION
SMIME_read_PKCS7() parses a message in S/MIME format.
in is a BIO to read the message from.
If cleartext signing is used then the content is saved in a memory bio which is written to *bcont,
otherwise *bcont is set to NULL.
The parsed PKCS#7 structure is returned or NULL if an error occurred.
NOTES
If *bcont is not NULL then the message is clear text signed. *bcont can then be passed to
PKCS7_verify() with the PKCS7_DETACHED flag set.
Otherwise the type of the returned structure can be determined using PKCS7_type().
To support future functionality if bcont is not NULL *bcont should be initialized to NULL. For
example:
BIO *cont = NULL;
PKCS7 *p7;
p7 = SMIME_read_PKCS7(in, &cont);
BUGS
The MIME parser used by SMIME_read_PKCS7() is somewhat primitive. While it will handle most
S/MIME messages more complex compound formats may not work.
The parser assumes that the PKCS7 structure is always base64 encoded and will not handle the case
where it is in binary format or uses quoted printable format.
The use of a memory BIO to hold the signed content limits the size of message which can be processed
due to memory restraints: a streaming single pass option should be available.
RETURN VALUES
SMIME_read_PKCS7() returns a valid PKCS7 structure or NULL is an error occurred. The error can be
obtained from ERR_get_error(3).
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_type(3)|PKCS7_type(3)
SMIME_read_PKCS7(3)|SMIME_read_PKCS7(3), PKCS7_sign(3)|PKCS7_sign(3),
PKCS7_verify(3)|PKCS7_verify(3), PKCS7_encrypt(3)|PKCS7_encrypt(3)
PKCS7_decrypt(3)|PKCS7_decrypt(3)
HISTORY
SMIME_read_PKCS7() was added to OpenSSL 0.9.5
SMIME_write_PKCS7
SMIME_write_PKCS7 - convert PKCS#7 structure to S/MIME format.
SYNOPSIS
int SMIME_write_PKCS7(BIO *out, PKCS7 *p7, BIO *data, int flags);
DESCRIPTION
SMIME_write_PKCS7() adds the appropriate MIME headers to a PKCS#7 structure to produce an
S/MIME message.
out is the BIO to write the data to. p7 is the appropriate PKCS7 structure. If cleartext signing
(multipart/signed) is being used then the signed data must be supplied in the data argument. flags is an
optional set of flags.
NOTES
The following flags can be passed in the flags parameter.
If PKCS7_DETACHED is set then cleartext signing will be used, this option only makes sense for
signedData where PKCS7_DETACHED is also set when PKCS7_sign() is also called.
If the PKCS7_TEXT flag is set MIME headers for type text/plain are added to the content, this only
makes sense if PKCS7_DETACHED is also set.
If cleartext signing is being used then the data must be read twice: once to compute the signature in
PKCS7_sign() and once to output the S/MIME message.
BUGS
SMIME_write_PKCS7() always base64 encodes PKCS#7 structures, there should be an option to
disable this.
There should really be a way to produce cleartext signing using only a single pass of the data.
RETURN VALUES
SMIME_write_PKCS7() returns 1 for success or 0 for failure.
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), PKCS7_sign(3)|PKCS7_sign(3),
PKCS7_verify(3)|PKCS7_verify(3), PKCS7_encrypt(3)|PKCS7_encrypt(3)
PKCS7_decrypt(3)|PKCS7_decrypt(3)
HISTORY
SMIME_write_PKCS7() was added to OpenSSL 0.9.5
int CRYPTO_num_locks(void);
int CRYPTO_get_new_dynlockid(void);
#define CRYPTO_w_lock(type) \
CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_w_unlock(type) \
CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
#define CRYPTO_r_lock(type) \
CRYPTO_lock(CRYPTO_LOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_r_unlock(type) \
CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_READ,type,__FILE__,__LINE__)
#define CRYPTO_add(addr,amount,type) \
CRYPTO_add_lock(addr,amount,type,__FILE__,__LINE__)
DESCRIPTION
OpenSSL can safely be used in multi-threaded applications provided that at least two callback functions
are set.
locking_function(int mode, int n, const char *file, int line) is needed to perform locking on shared data
structures. (Note that OpenSSL uses a number of global data structures that will be implicitly shared
whenever multiple threads use OpenSSL.) Multi-threaded applications will crash at random if it is not
set.
locking_function() must be able to handle up to CRYPTO_num_locks() different mutex locks. It sets the
n-th lock if mode & CRYPTO_LOCK, and releases it otherwise.
file and line are the file number of the function setting the lock. They can be useful for debugging.
id_function(void) is a function that returns a thread ID. It is not needed on Windows nor on platforms
where getpid() returns a different ID for each thread (most notably Linux).
Additionally, OpenSSL supports dynamic locks, and sometimes, some parts of OpenSSL need it for
better performance. To enable this, the following is required:
Also, dynamic locks are currently not used internally by OpenSSL, but may do so in the future.
EXAMPLES
crypto/threads/mttest.c shows examples of the callback functions on Solaris, Irix and Win32.
HISTORY
CRYPTO_set_locking_callback() and CRYPTO_set_id_callback() are available in all versions of
SSLeay and OpenSSL. CRYPTO_num_locks() was added in OpenSSL 0.9.4. All functions dealing with
dynamic locks were added in OpenSSL 0.9.5b-dev.
SEE ALSO
crypto(3)|crypto(3)
UI *UI_new(void);
UI *UI_new_method(const UI_METHOD *method);
void UI_free(UI *ui);
int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)());
#define UI_CTRL_PRINT_ERRORS 1
#define UI_CTRL_IS_REDOABLE 2
UI_METHOD *UI_OpenSSL(void);
DESCRIPTION
UI stands for User Interface, and is general purpose set of routines to prompt the user for text-based
information. Through user-written methods (see ui_create(3)|ui_create(3)), prompting can be done in
any way imaginable, be it plain text prompting, through dialog boxes or from a cell phone.
All the functions work through a context of the type UI. This context contains all the information
needed to prompt correctly as well as a reference to a UI_METHOD, which is an ordered vector of
functions that carry out the actual prompting.
The first thing to do is to create a UI with UI_new() or UI_new_method(), then add information to it
with the UI_add or UI_dup functions. Also, user-defined random data can be passed down to the
underlying method through calls to UI_add_user_data. The default UI method doesn‘t care about these
data, but other methods might. Finally, use UI_process() to actually perform the prompting and
UI_get0_result() to find the result to the prompt.
A UI can contain more than one prompt, which are performed in the given sequence. Each prompt gets
an index number which is returned by the UI_add and UI_dup functions, and has to be used to get the
corresponding result with UI_get0_result().
The functions are as follows:
UI_new() creates a new UI using the default UI method. When done with this UI, it should be freed
using UI_free().
UI_new_method() creates a new UI using the given UI method. When done with this UI, it should be
freed using UI_free().
UI_OpenSSL() returns the built-in UI method (note: not the default one, since the default can be
changed. See further on). This method is the most machine/OS dependent part of OpenSSL and
normally generates the most problems when porting.
UI_free() removes a UI from memory, along with all other pieces of memory that‘s connected to it, like
duplicated input strings, results and others.
UI_add_input_string() and UI_add_verify_string() add a prompt to the UI, as well as flags and a result
buffer and the desired minimum and maximum sizes of the result. The given information is used to
prompt for information, for example a password, and to verify a password (i.e. having the user enter it
twice and check that the same string was entered twice). UI_add_verify_string() takes and extra
argument that should be a pointer to the result buffer of the input string that it‘s supposed to verify, or
verification will fail.
UI_add_input_boolean() adds a prompt to the UI that‘s supposed to be answered in a boolean way, with
a single character for yes and a different character for no. A set of characters that can be used to cancel
the prompt is given as well. The prompt itself is really divided in two, one part being the descriptive text
(given through the prompt argument) and one describing the possible answers (given through the
action_desc argument).
UI_add_info_string() and UI_add_error_string() add strings that are shown at the same time as the
prompt for extra information or to show an error string. The difference between the two is only
conceptual. With the builtin method, there‘s no technical difference between them. Other methods may
make a difference between them, however.
The flags currently supported are UI_INPUT_FLAG_ECHO, which is relevant for
UI_add_input_string() and will have the users response be echoed (when prompting for a password, this
flag should obviously not be used, and UI_INPUT_FLAG_DEFAULT_PWD, which means that a
default password of some sort will be used (completely depending on the application and the UI
method).
UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(), UI_dup_info_string() and
UI_dup_error_string() are basically the same as their UI_add counterparts, except that they make their
own copies of all strings.
UI_construct_prompt() is a helper function that can be used to create a prompt from two pieces of
information: an description and a name. The default constructor (if there is none provided by the method
used) creates a string "Enter description for name:". With the description "pass phrase" and the file
name "foo.key", that becomes "Enter pass phrase for foo.key:". Other methods may create whatever
string and may include encodings that will be processed by the other method functions.
UI_add_user_data() adds a piece of memory for the method to use at any time. The builtin UI method
doesn‘t care about this info. Note that several calls to this function doesn‘t add data, it replaces the
previous blob with the one given as argument.
UI_get0_user_data() retrieves the data that has last been given to the UI with UI_add_user_data().
UI_get0_result() returns a pointer to the result buffer associated with the information indexed by i.
UI_process() goes through the information given so far, does all the printing and prompting and returns.
UI_ctrl() adds extra control for the application author. For now, it understands two commands:
UI_CTRL_PRINT_ERRORS, which makes UI_process() print the OpenSSL error stack as part of
processing the UI, and UI_CTRL_IS_REDOABLE, which returns a flag saying if the used UI can be
used again or not.
UI_set_default_method() changes the default UI method to the one given.
UI_get_default_method() returns a pointer to the current default UI method.
UI_get_method() returns the UI method associated with a given UI.
UI_set_method() changes the UI method associated with a given UI.
SEE ALSO
ui_create(3)|ui_create(3), ui_compat(3)|ui_compat(3)
HISTORY
The UI section was first introduced in OpenSSL 0.9.7.
AUTHOR
Richard Levitte ([email protected]) for the OpenSSL project (http://www.openssl.org).
X509_NAME modification
X509_NAME_add_entry_by_txt, X509_NAME_add_entry_by_OBJ,
X509_NAME_add_entry_by_NID, X509_NAME_add_entry, X509_NAME_delete_entry -
X509_NAME modification functions
SYNOPSIS
int X509_NAME_add_entry_by_txt(X509_NAME *name, char *field, int type,
int X509_NAME_add_entry_by_OBJ(X509_NAME
unsigned
*name,
charASN1_OBJECT
*bytes, int len, int
*obj,
loc,int
inttype,
set);
int X509_NAME_add_entry_by_NID(X509_NAME
unsigned
*name,
charint
*bytes,
nid, int
inttype,
len, int loc, int set);
int X509_NAME_add_entry(X509_NAME *name,X509_NAME_ENTRY
unsigned char *bytes, int len,
*ne,
int int
loc,loc,
int int
set);
set);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
DESCRIPTION
X509_NAME_add_entry_by_txt(), X509_NAME_add_entry_by_OBJ() and
X509_NAME_add_entry_by_NID() add a field whose name is defined by a string field, an object obj or
a NID nid respectively. The field value to be added is in bytes of length len. If len is -1 then the field
length is calculated internally using strlen(bytes).
The type of field is determined by type which can either be a definition of the type of bytes (such as
MBSTRING_ASC) or a standard ASN1 type (such as V_ASN1_IA5STRING). The new entry is added
to a position determined by loc and set.
X509_NAME_add_entry() adds a copy of X509_NAME_ENTRY structure ne to name. The new entry
is added to a position determined by loc and set. Since a copy of ne is added ne must be freed up after
the call.
X509_NAME_delete_entry() deletes an entry from name at position loc. The deleted entry is returned
and must be freed up.
NOTES
The use of string types such as MBSTRING_ASC or MBSTRING_UTF8 is strongly recommened for
the type parameter. This allows the internal code to correctly determine the type of the field and to apply
length checks according to the relevant standards. This is done using ASN1_STRING_set_by_NID().
If instead an ASN1 type is used no checks are performed and the supplied data in bytes is used directly.
In X509_NAME_add_entry_by_txt() the field string represents the field name using OBJ_txt2obj(field,
0).
The loc and set parameters determine where a new entry should be added. For almost all applications loc
can be set to -1 and set to 0. This adds a new entry to the end of name as a single valued
RelativeDistinguishedName (RDN).
loc actually determines the index where the new entry is inserted: if it is -1 it is appended.
set determines how the new type is added. If it is zero a new RDN is created.
If set is -1 or 1 it is added to the previous or next RDN structure respectively. This will then be a
multivalued RDN: since multivalues RDNs are very seldom used set is almost always set to zero.
EXAMPLES
Create an X509_NAME structure:
"C=UK, O=Disorganized Organization, CN=Joe Bloggs"
X509_NAME *nm;
nm = X509_NAME_new();
if (nm == NULL)
/* Some error */
if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC,
"C", "UK", -1, -1, 0))
/* Error */
if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC,
"O", "Disorganized Organization", -1, -1, 0))
/* Error */
if (!X509_NAME_add_entry_by_txt(nm, MBSTRING_ASC,
"CN", "Joe Bloggs", -1, -1, 0))
/* Error */
RETURN VALUES
X509_NAME_add_entry_by_txt(), X509_NAME_add_entry_by_OBJ(),
X509_NAME_add_entry_by_NID() and X509_NAME_add_entry() return 1 for success of 0 if an error
occurred.
X509_NAME_delete_entry() returns either the deleted X509_NAME_ENTRY structure of NULL if an
error occurred.
BUGS
type can still be set to V_ASN1_APP_CHOOSE to use a different algorithm to determine field types.
Since this form does not understand multicharacter types, performs no length checks and can result in
invalid field types its use is strongly discouraged.
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), d2i_X509_NAME(3)|d2i_X509_NAME(3)
HISTORY
X509_NAME_ENTRY utility
X509_NAME_ENTRY_get_object, X509_NAME_ENTRY_get_data,
X509_NAME_ENTRY_set_object, X509_NAME_ENTRY_set_data,
X509_NAME_ENTRY_create_by_txt, X509_NAME_ENTRY_create_by_NID,
X509_NAME_ENTRY_create_by_OBJ - X509_NAME_ENTRY utility functions
SYNOPSIS
ASN1_OBJECT * X509_NAME_ENTRY_get_object(X509_NAME_ENTRY *ne); ASN1_STRING *
X509_NAME_ENTRY_get_data(X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, ASN1_OBJECT *obj); int
X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY
unsigned char *bytes, int len); **ne,
char *field, int type,
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY
unsigned char *bytes, int len); **ne,
int nid, int type,unsigned char *bytes,
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY
int len); **ne,
ASN1_OBJECT *obj, int type,
unsigned char *bytes, int len);
DESCRIPTION
X509_NAME_ENTRY_get_object() retrieves the field name of ne in and ASN1_OBJECT structure.
X509_NAME_ENTRY_get_data() retrieves the field value of ne in and ASN1_STRING structure.
X509_NAME_ENTRY_set_object() sets the field name of ne to obj.
X509_NAME_ENTRY_set_data() sets the field value of ne to string type type and value determined by
bytes and len.
X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID() and
X509_NAME_ENTRY_create_by_OBJ() create and return an X509_NAME_ENTRY structure.
NOTES
X509_NAME_ENTRY_get_object() and X509_NAME_ENTRY_get_data() can be used to examine an
X509_NAME_ENTRY function as returned by X509_NAME_get_entry() for example.
X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID(), and
X509_NAME_ENTRY_create_by_OBJ() create and return an
X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_OBJ(),
X509_NAME_ENTRY_create_by_NID() and X509_NAME_ENTRY_set_data() are seldom used in
practice because X509_NAME_ENTRY structures are almost always part of X509_NAME structures
and the corresponding X509_NAME functions are typically used to create and add new entries in a
single operation.
The arguments of these functions support similar options to the similarly named ones of the
corresponding X509_NAME functions such as X509_NAME_add_entry_by_txt(). So for example type
can be set to MBSTRING_ASC but in the case of X509_set_data() the field name must be set first so
the relevant field information can be looked up internally.
RETURN VALUES
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), d2i_X509_NAME(3)|d2i_X509_NAME(3),
OBJ_nid2obj(3),OBJ_nid2obj(3)
HISTORY
TBA
loc = -1;
for (;;)
{
lastpos = X509_NAME_get_index_by_NID(nm, NID_commonName, lastpos);
if (lastpos == -1)
break;
e = X509_NAME_get_entry(nm, lastpos);
/* Do something with e */
}
RETURN VALUES
X509_NAME_get_index_by_NID() and X509_NAME_get_index_by_OBJ() return the index of the
next matching entry or -1 if not found.
X509_NAME_entry_count() returns the total number of entries.
X509_NAME_get_entry() returns an X509_NAME pointer to the requested entry or NULL if the index
is invalid.
SEE ALSO
ERR_get_error(3)|ERR_get_error(3), d2i_X509_NAME(3)|d2i_X509_NAME(3)
HISTORY
TBA
X509_NAME printing
X509_NAME_print_ex, X509_NAME_print_ex_fp, X509_NAME_print, X509_NAME_oneline -
X509_NAME printing routines.
SYNOPSIS
#include <openssl/x509.h>