xref: /freebsd/crypto/openssl/doc/man7/crypto.pod (revision 95eb4b873b6a8b527c5bd78d7191975dfca38998)
1=pod
2
3=head1 NAME
4
5crypto - OpenSSL cryptographic library
6
7=head1 SYNOPSIS
8
9See the individual manual pages for details.
10
11=head1 DESCRIPTION
12
13The OpenSSL crypto library (C<libcrypto>) implements a wide range of
14cryptographic algorithms used in various Internet standards. The services
15provided by this library are used by the OpenSSL implementations of TLS and
16CMS, and they have also been used to implement many other third party products
17and protocols.
18
19The functionality includes symmetric encryption, public key cryptography, key
20agreement, certificate handling, cryptographic hash functions, cryptographic
21pseudo-random number generators, message authentication codes (MACs), key
22derivation functions (KDFs), and various utilities.
23
24=head2 Algorithms
25
26Cryptographic primitives such as the SHA256 digest, or AES encryption are
27referred to in OpenSSL as "algorithms". Each algorithm may have multiple
28implementations available for use. For example the RSA algorithm is available as
29a "default" implementation suitable for general use, and a "fips" implementation
30which has been validated to FIPS standards for situations where that is
31important. It is also possible that a third party could add additional
32implementations such as in a hardware security module (HSM).
33
34=head2 Operations
35
36Different algorithms can be grouped together by their purpose. For example there
37are algorithms for encryption, and different algorithms for digesting data.
38These different groups are known as "operations" in OpenSSL. Each operation
39has a different set of functions associated with it. For example to perform an
40encryption operation using AES (or any other encryption algorithm) you would use
41the encryption functions detailed on the L<EVP_EncryptInit(3)> page. Or to
42perform a digest operation using SHA256 then you would use the digesting
43functions on the L<EVP_DigestInit(3)> page.
44
45=head2 Providers
46
47A provider in OpenSSL is a component that collects together algorithm
48implementations. In order to use an algorithm you must have at least one
49provider loaded that contains an implementation of it. OpenSSL comes with a
50number of providers and they may also be obtained from third parties. If you
51don't load a provider explicitly (either in program code or via config) then the
52OpenSSL built-in "default" provider will be automatically loaded.
53
54=head2 Library contexts
55
56A library context can be thought of as a "scope" within which configuration
57options take effect. When a provider is loaded, it is only loaded within the
58scope of a given library context. In this way it is possible for different
59components of a complex application to each use a different library context and
60have different providers loaded with different configuration settings.
61
62If an application does not explicitly create a library context then the
63"default" library context will be used.
64
65Library contexts are represented by the B<OSSL_LIB_CTX> type. Many OpenSSL API
66functions take a library context as a parameter. Applications can always pass
67B<NULL> for this parameter to just use the default library context.
68
69The default library context is automatically created the first time it is
70needed. This will automatically load any available configuration file and will
71initialise OpenSSL for use. Unlike in earlier versions of OpenSSL (prior to
721.1.0) no explicit initialisation steps need to be taken.
73
74Similarly when the application exits the default library context is
75automatically destroyed. No explicit de-initialisation steps need to be taken.
76
77See L<OSSL_LIB_CTX(3)> for more information about library contexts.
78See also L</ALGORITHM FETCHING>.
79
80=head2 Multi-threaded applications
81
82As long as OpenSSL has been built with support for threads (the default case
83on most platforms) then most OpenSSL I<functions> are thread-safe in the sense
84that it is safe to call the same function from multiple threads at the same
85time. However most OpenSSL I<data structures> are not thread-safe. For example
86the L<BIO_write(3)> and L<BIO_read(3)> functions are thread safe. However it
87would not be thread safe to call BIO_write() from one thread while calling
88BIO_read() in another where both functions are passed the same B<BIO> object
89since both of them may attempt to make changes to the same B<BIO> object.
90
91There are exceptions to these rules. A small number of functions are not thread
92safe at all. Where this is the case this restriction should be noted in the
93documentation for the function. Similarly some data structures may be partially
94or fully thread safe. For example it is safe to use an B<OSSL_LIB_CTX> in
95multiple threads.
96
97See L<openssl-threads(7)> for a more detailed discussion on OpenSSL threading
98support.
99
100=head1 ALGORITHM FETCHING
101
102In order to use an algorithm an implementation for it must first be "fetched".
103Fetching is the process of looking through the available implementations,
104applying selection criteria (via a property query string), and finally choosing
105the implementation that will be used.
106
107Two types of fetching are supported by OpenSSL - explicit fetching and implicit
108fetching.
109
110=head2 Property query strings
111
112When fetching an algorithm it is possible to specify a property query string to
113guide the selection process. For example a property query string of
114"provider=default" could be used to force the selection to only consider
115algorithm implementations in the default provider.
116
117Property query strings can be specified explicitly as an argument to a function.
118It is also possible to specify a default property query string for the whole
119library context using the L<EVP_set_default_properties(3)> or
120L<EVP_default_properties_enable_fips(3)> functions. Where both
121default properties and function specific properties are specified then they are
122combined. Function specific properties will override default properties where
123there is a conflict.
124
125See L<property(7)> for more information about properties.
126
127=head2 Explicit fetching
128
129Users of the OpenSSL libraries never query a provider directly for an algorithm
130implementation. Instead, the diverse OpenSSL APIs often have explicit fetching
131functions that do the work, and they return an appropriate algorithm object back
132to the user. These functions usually have the name C<APINAME_fetch>, where
133C<APINAME> is the name of the operation. For example L<EVP_MD_fetch(3)> can
134be used to explicitly fetch a digest algorithm implementation. The user is
135responsible for freeing the object returned from the C<APINAME_fetch> function
136using C<APINAME_free> when it is no longer needed.
137
138These fetching functions follow a fairly common pattern, where three
139arguments are passed:
140
141=over 4
142
143=item The library context
144
145See L<OSSL_LIB_CTX(3)> for a more detailed description.
146This may be NULL to signify the default (global) library context, or a
147context created by the user. Only providers loaded in this library context (see
148L<OSSL_PROVIDER_load(3)>) will be considered by the fetching function. In case
149no provider has been loaded in this library context then the default provider
150will be loaded as a fallback (see L<OSSL_PROVIDER-default(7)>).
151
152=item An identifier
153
154For all currently implemented fetching functions this is the algorithm name.
155
156=item A property query string
157
158The property query string used to guide selection of the algorithm
159implementation.
160
161=back
162
163The algorithm implementation that is fetched can then be used with other diverse
164functions that use them. For example the L<EVP_DigestInit_ex(3)> function takes
165as a parameter an B<EVP_MD> object which may have been returned from an earlier
166call to L<EVP_MD_fetch(3)>.
167
168=head2 Implicit fetching
169
170OpenSSL has a number of functions that return an algorithm object with no
171associated implementation, such as L<EVP_sha256(3)>, L<EVP_aes_128_cbc(3)>,
172L<EVP_get_cipherbyname(3)> or L<EVP_get_digestbyname(3)>. These are present for
173compatibility with OpenSSL before version 3.0 where explicit fetching was not
174available.
175
176When they are used with functions like L<EVP_DigestInit_ex(3)> or
177L<EVP_CipherInit_ex(3)>, the actual implementation to be used is
178fetched implicitly using default search criteria.
179
180In some cases implicit fetching can also occur when a NULL algorithm parameter
181is supplied. In this case an algorithm implementation is implicitly fetched
182using default search criteria and an algorithm name that is consistent with
183the context in which it is being used.
184
185Functions that revolve around B<EVP_PKEY_CTX> and L<EVP_PKEY(3)>, such as
186L<EVP_DigestSignInit(3)> and friends, all fetch the implementations
187implicitly.  Because these functions involve both an operation type (such as
188L<EVP_SIGNATURE(3)>) and an L<EVP_KEYMGMT(3)> for the L<EVP_PKEY(3)>, they try
189the following:
190
191=over 4
192
193=item 1.
194
195Fetch the operation type implementation from any provider given a library
196context and property string stored in the B<EVP_PKEY_CTX>.
197
198If the provider of the operation type implementation is different from the
199provider of the L<EVP_PKEY(3)>'s L<EVP_KEYMGMT(3)> implementation, try to
200fetch a L<EVP_KEYMGMT(3)> implementation in the same provider as the operation
201type implementation and export the L<EVP_PKEY(3)> to it (effectively making a
202temporary copy of the original key).
203
204If anything in this step fails, the next step is used as a fallback.
205
206=item 2.
207
208As a fallback, try to fetch the operation type implementation from the same
209provider as the original L<EVP_PKEY(3)>'s L<EVP_KEYMGMT(3)>, still using the
210property string from the B<EVP_PKEY_CTX>.
211
212=back
213
214=head2 Performance
215
216If you perform the same operation many times then it is recommended to use
217L</Explicit fetching> to prefetch an algorithm once initially,
218and then pass this created object to any operations that are currently
219using L</Implicit fetching>.
220See an example of Explicit fetching in L</USING ALGORITHMS IN APPLICATIONS>.
221
222Prior to OpenSSL 3.0, constant method tables (such as EVP_sha256()) were used
223directly to access methods. If you pass one of these convenience functions
224to an operation the fixed methods are ignored, and only the name is used to
225internally fetch methods from a provider.
226
227If the prefetched object is not passed to operations, then any implicit
228fetch will use the internally cached prefetched object, but it will
229still be slower than passing the prefetched object directly.
230
231Fetching via a provider offers more flexibility, but it is slower than the
232old method, since it must search for the algorithm in all loaded providers,
233and then populate the method table using provider supplied methods.
234Internally OpenSSL caches similar algorithms on the first fetch
235(so loading a digest caches all digests).
236
237The following methods can be used for prefetching:
238
239=over 4
240
241=item L<EVP_MD_fetch(3)>
242
243=item L<EVP_CIPHER_fetch(3)>
244
245=item L<EVP_KDF_fetch(3)>
246
247=item L<EVP_MAC_fetch(3)>
248
249=item L<EVP_KEM_fetch(3)>
250
251=item L<OSSL_ENCODER_fetch(3)>
252
253=item L<OSSL_DECODER_fetch(3)>
254
255=item L<EVP_RAND_fetch(3)>
256
257=back
258
259The following methods are used internally when performing operations:
260
261=over 4
262
263=item L<EVP_KEYMGMT_fetch(3)>
264
265=item L<EVP_KEYEXCH_fetch(3)>
266
267=item L<EVP_SIGNATURE_fetch(3)>
268
269=item L<OSSL_STORE_LOADER_fetch(3)>
270
271=back
272
273See L<OSSL_PROVIDER-default(7)>, <OSSL_PROVIDER-fips(7)> and
274<OSSL_PROVIDER-legacy(7)>for a list of algorithm names that
275can be fetched.
276
277=head1 FETCHING EXAMPLES
278
279The following section provides a series of examples of fetching algorithm
280implementations.
281
282Fetch any available implementation of SHA2-256 in the default context. Note
283that some algorithms have aliases. So "SHA256" and "SHA2-256" are synonymous:
284
285 EVP_MD *md = EVP_MD_fetch(NULL, "SHA2-256", NULL);
286 ...
287 EVP_MD_free(md);
288
289Fetch any available implementation of AES-128-CBC in the default context:
290
291 EVP_CIPHER *cipher = EVP_CIPHER_fetch(NULL, "AES-128-CBC", NULL);
292 ...
293 EVP_CIPHER_free(cipher);
294
295Fetch an implementation of SHA2-256 from the default provider in the default
296context:
297
298 EVP_MD *md = EVP_MD_fetch(NULL, "SHA2-256", "provider=default");
299 ...
300 EVP_MD_free(md);
301
302Fetch an implementation of SHA2-256 that is not from the default provider in the
303default context:
304
305 EVP_MD *md = EVP_MD_fetch(NULL, "SHA2-256", "provider!=default");
306 ...
307 EVP_MD_free(md);
308
309Fetch an implementation of SHA2-256 from the default provider in the specified
310context:
311
312 EVP_MD *md = EVP_MD_fetch(ctx, "SHA2-256", "provider=default");
313 ...
314 EVP_MD_free(md);
315
316Load the legacy provider into the default context and then fetch an
317implementation of WHIRLPOOL from it:
318
319 /* This only needs to be done once - usually at application start up */
320 OSSL_PROVIDER *legacy = OSSL_PROVIDER_load(NULL, "legacy");
321
322 EVP_MD *md = EVP_MD_fetch(NULL, "WHIRLPOOL", "provider=legacy");
323 ...
324 EVP_MD_free(md);
325
326Note that in the above example the property string "provider=legacy" is optional
327since, assuming no other providers have been loaded, the only implementation of
328the "whirlpool" algorithm is in the "legacy" provider. Also note that the
329default provider should be explicitly loaded if it is required in addition to
330other providers:
331
332 /* This only needs to be done once - usually at application start up */
333 OSSL_PROVIDER *legacy = OSSL_PROVIDER_load(NULL, "legacy");
334 OSSL_PROVIDER *default = OSSL_PROVIDER_load(NULL, "default");
335
336 EVP_MD *md_whirlpool = EVP_MD_fetch(NULL, "whirlpool", NULL);
337 EVP_MD *md_sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL);
338 ...
339 EVP_MD_free(md_whirlpool);
340 EVP_MD_free(md_sha256);
341
342=head1 OPENSSL PROVIDERS
343
344OpenSSL comes with a set of providers.
345
346The algorithms available in each of these providers may vary due to build time
347configuration options. The L<openssl-list(1)> command can be used to list the
348currently available algorithms.
349
350The names of the algorithms shown from L<openssl-list(1)> can be used as an
351algorithm identifier to the appropriate fetching function. Also see the provider
352specific manual pages linked below for further details about using the
353algorithms available in each of the providers.
354
355As well as the OpenSSL providers third parties can also implement providers.
356For information on writing a provider see L<provider(7)>.
357
358=head2 Default provider
359
360The default provider is built in as part of the F<libcrypto> library and
361contains all of the most commonly used algorithm implementations. Should it be
362needed (if other providers are loaded and offer implementations of the same
363algorithms), the property query string "provider=default" can be used as a
364search criterion for these implementations.  The default provider includes all
365of the functionality in the base provider below.
366
367If you don't load any providers at all then the "default" provider will be
368automatically loaded. If you explicitly load any provider then the "default"
369provider would also need to be explicitly loaded if it is required.
370
371See L<OSSL_PROVIDER-default(7)>.
372
373=head2 Base provider
374
375The base provider is built in as part of the F<libcrypto> library and contains
376algorithm implementations for encoding and decoding for OpenSSL keys.
377Should it be needed (if other providers are loaded and offer
378implementations of the same algorithms), the property query string
379"provider=base" can be used as a search criterion for these implementations.
380Some encoding and decoding algorithm implementations are not FIPS algorithm
381implementations in themselves but support algorithms from the FIPS provider and
382are allowed for use in "FIPS mode". The property query string "fips=yes" can be
383used to select such algorithms.
384
385See L<OSSL_PROVIDER-base(7)>.
386
387=head2 FIPS provider
388
389The FIPS provider is a dynamically loadable module, and must therefore
390be loaded explicitly, either in code or through OpenSSL configuration
391(see L<config(5)>). It contains algorithm implementations that have been
392validated according to the FIPS 140-2 standard. Should it be needed (if other
393providers are loaded and offer implementations of the same algorithms), the
394property query string "provider=fips" can be used as a search criterion for
395these implementations. All approved algorithm implementations in the FIPS
396provider can also be selected with the property "fips=yes". The FIPS provider
397may also contain non-approved algorithm implementations and these can be
398selected with the property "fips=no".
399
400See L<OSSL_PROVIDER-FIPS(7)> and L<fips_module(7)>.
401
402=head2 Legacy provider
403
404The legacy provider is a dynamically loadable module, and must therefore
405be loaded explicitly, either in code or through OpenSSL configuration
406(see L<config(5)>). It contains algorithm implementations that are considered
407insecure, or are no longer in common use such as MD2 or RC4. Should it be needed
408(if other providers are loaded and offer implementations of the same algorithms),
409the property "provider=legacy" can be used as a search criterion for these
410implementations.
411
412See L<OSSL_PROVIDER-legacy(7)>.
413
414=head2 Null provider
415
416The null provider is built in as part of the F<libcrypto> library. It contains
417no algorithms in it at all. When fetching algorithms the default provider will
418be automatically loaded if no other provider has been explicitly loaded. To
419prevent that from happening you can explicitly load the null provider.
420
421See L<OSSL_PROVIDER-null(7)>.
422
423=head1 USING ALGORITHMS IN APPLICATIONS
424
425Cryptographic algorithms are made available to applications through use of the
426"EVP" APIs. Each of the various operations such as encryption, digesting,
427message authentication codes, etc., have a set of EVP function calls that can
428be invoked to use them. See the L<evp(7)> page for further details.
429
430Most of these follow a common pattern. A "context" object is first created. For
431example for a digest operation you would use an B<EVP_MD_CTX>, and for an
432encryption/decryption operation you would use an B<EVP_CIPHER_CTX>. The
433operation is then initialised ready for use via an "init" function - optionally
434passing in a set of parameters (using the L<OSSL_PARAM(3)> type) to configure how
435the operation should behave. Next data is fed into the operation in a series of
436"update" calls. The operation is finalised using a "final" call which will
437typically provide some kind of output. Finally the context is cleaned up and
438freed.
439
440The following shows a complete example for doing this process for digesting
441data using SHA256. The process is similar for other operations such as
442encryption/decryption, signatures, message authentication codes, etc.
443
444 #include <stdio.h>
445 #include <openssl/evp.h>
446 #include <openssl/bio.h>
447 #include <openssl/err.h>
448
449 int main(void)
450 {
451     EVP_MD_CTX *ctx = NULL;
452     EVP_MD *sha256 = NULL;
453     const unsigned char msg[] = {
454         0x00, 0x01, 0x02, 0x03
455     };
456     unsigned int len = 0;
457     unsigned char *outdigest = NULL;
458     int ret = 1;
459
460     /* Create a context for the digest operation */
461     ctx = EVP_MD_CTX_new();
462     if (ctx == NULL)
463         goto err;
464
465     /*
466      * Fetch the SHA256 algorithm implementation for doing the digest. We're
467      * using the "default" library context here (first NULL parameter), and
468      * we're not supplying any particular search criteria for our SHA256
469      * implementation (second NULL parameter). Any SHA256 implementation will
470      * do.
471      * In a larger application this fetch would just be done once, and could
472      * be used for multiple calls to other operations such as EVP_DigestInit_ex().
473      */
474     sha256 = EVP_MD_fetch(NULL, "SHA256", NULL);
475     if (sha256 == NULL)
476         goto err;
477
478    /* Initialise the digest operation */
479    if (!EVP_DigestInit_ex(ctx, sha256, NULL))
480        goto err;
481
482     /*
483      * Pass the message to be digested. This can be passed in over multiple
484      * EVP_DigestUpdate calls if necessary
485      */
486     if (!EVP_DigestUpdate(ctx, msg, sizeof(msg)))
487         goto err;
488
489     /* Allocate the output buffer */
490     outdigest = OPENSSL_malloc(EVP_MD_get_size(sha256));
491     if (outdigest == NULL)
492         goto err;
493
494     /* Now calculate the digest itself */
495     if (!EVP_DigestFinal_ex(ctx, outdigest, &len))
496         goto err;
497
498     /* Print out the digest result */
499     BIO_dump_fp(stdout, outdigest, len);
500
501     ret = 0;
502
503  err:
504     /* Clean up all the resources we allocated */
505     OPENSSL_free(outdigest);
506     EVP_MD_free(sha256);
507     EVP_MD_CTX_free(ctx);
508     if (ret != 0)
509        ERR_print_errors_fp(stderr);
510     return ret;
511 }
512
513=head1 CONFIGURATION
514
515By default OpenSSL will load a configuration file when it is first used. This
516will set up various configuration settings within the default library context.
517Applications that create their own library contexts may optionally configure
518them with a config file using the L<OSSL_LIB_CTX_load_config(3)> function.
519
520The configuration file can be used to automatically load providers and set up
521default property query strings.
522
523For information on the OpenSSL configuration file format see L<config(5)>.
524
525=head1 ENCODING AND DECODING KEYS
526
527Many algorithms require the use of a key. Keys can be generated dynamically
528using the EVP APIs (for example see L<EVP_PKEY_Q_keygen(3)>). However it is often
529necessary to save or load keys (or their associated parameters) to or from some
530external format such as PEM or DER (see L<openssl-glossary(7)>). OpenSSL uses
531encoders and decoders to perform this task.
532
533Encoders and decoders are just algorithm implementations in the same way as
534any other algorithm implementation in OpenSSL. They are implemented by
535providers. The OpenSSL encoders and decoders are available in the default
536provider. They are also duplicated in the base provider.
537
538For information about encoders see L<OSSL_ENCODER_CTX_new_for_pkey(3)>. For
539information about decoders see L<OSSL_DECODER_CTX_new_for_pkey(3)>.
540
541=head1 LIBRARY CONVENTIONS
542
543Many OpenSSL functions that "get" or "set" a value follow a naming convention
544using the numbers B<0> and B<1>, i.e. "get0", "get1", "set0" and "set1". This
545can also apply to some functions that "add" a value to an existing set, i.e.
546"add0" and "add1".
547
548For example the functions:
549
550 int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
551 int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj);
552
553In the B<0> version the ownership of the object is passed to (for an add or set)
554or retained by (for a get) the parent object. For example after calling the
555X509_CRL_add0_revoked() function above, ownership of the I<rev> object is passed
556to the I<crl> object. Therefore, after calling this function I<rev> should not
557be freed directly. It will be freed implicitly when I<crl> is freed.
558
559In the B<1> version the ownership of the object is not passed to or retained by
560the parent object. Instead a copy or "up ref" of the object is performed. So
561after calling the X509_add1_trust_object() function above the application will
562still be responsible for freeing the I<obj> value where appropriate.
563
564=head1 SEE ALSO
565
566L<openssl(1)>, L<ssl(7)>, L<evp(7)>, L<OSSL_LIB_CTX(3)>, L<openssl-threads(7)>,
567L<property(7)>, L<OSSL_PROVIDER-default(7)>, L<OSSL_PROVIDER-base(7)>,
568L<OSSL_PROVIDER-FIPS(7)>, L<OSSL_PROVIDER-legacy(7)>, L<OSSL_PROVIDER-null(7)>,
569L<openssl-glossary(7)>, L<provider(7)>
570
571=head1 COPYRIGHT
572
573Copyright 2000-2023 The OpenSSL Project Authors. All Rights Reserved.
574
575Licensed under the Apache License 2.0 (the "License").  You may not use
576this file except in compliance with the License.  You can obtain a copy
577in the file LICENSE in the source distribution or at
578L<https://www.openssl.org/source/license.html>.
579
580=cut
581