Fix "wierd" typo as submitted by Jeroen Ruigrok/Asmodai <asmodai@wxs.nl>.
[openssl.git] / doc / ssleay.txt
1
2 Bundle of old SSLeay documentation files [OBSOLETE!]
3
4 ==== readme ========================================================
5
6 This is the old 0.6.6 docuementation.  Most of the cipher stuff is still
7 relevent but I'm working (very slowly) on new docuemtation.
8 The current version can be found online at
9
10 http://www.cryptsoft.com/ssleay/doc
11
12 ==== API.doc ========================================================
13
14 SSL - SSLv2/v3/v23 etc.
15
16 BIO - methods and how they plug together
17
18 MEM - memory allocation callback
19
20 CRYPTO - locking for threads
21
22 EVP - Ciphers/Digests/signatures
23
24 RSA - methods
25
26 X509 - certificate retrieval
27
28 X509 - validation
29
30 X509 - X509v3 extensions
31
32 Objects - adding object identifiers
33
34 ASN.1 - parsing
35
36 PEM - parsing
37
38 ==== ssl/readme =====================================================
39
40 22 Jun 1996
41 This file belongs in ../apps, but I'll leave it here because it deals
42 with SSL :-)  It is rather dated but it gives you an idea of how
43 things work.
44 ===
45
46 17 Jul 1995
47 I have been changing things quite a bit and have not fully updated
48 this file, so take what you read with a grain of salt
49 eric
50 ===
51 The s_client and s_server programs can be used to test SSL capable
52 IP/port addresses and the verification of the X509 certificates in use
53 by these services.  I strongly advise having a look at the code to get
54 an idea of how to use the authentication under SSLeay.  Any feedback
55 on changes and improvements would be greatly accepted.
56
57 This file will probably be gibberish unless you have read
58 rfc1421, rfc1422, rfc1423 and rfc1424 which describe PEM
59 authentication.
60
61 A Brief outline (and examples) how to use them to do so.
62
63 NOTE:
64 The environment variable SSL_CIPER is used to specify the prefered
65 cipher to use, play around with setting it's value to combinations of
66 RC4-MD5, EXP-RC4-MD5, CBC-DES-MD5, CBC3-DES-MD5, CFB-DES-NULL
67 in a : separated list.
68
69 This directory contains 3 X509 certificates which can be used by these programs.
70 client.pem: a file containing a certificate and private key to be used
71         by s_client.
72 server.pem :a file containing a certificate and private key to be used
73         by s_server.
74 eay1024.pem:the certificate used to sign client.pem and server.pem.
75         This would be your CA's certificate.  There is also a link
76         from the file a8556381.0 to eay1024.PEM.  The value a8556381
77         is returned by 'x509 -hash -noout <eay1024.pem' and is the
78         value used by X509 verification routines to 'find' this
79         certificte when search a directory for it.
80         [the above is not true any more, the CA cert is 
81          ../certs/testca.pem which is signed by ../certs/mincomca.pem]
82
83 When testing the s_server, you may get
84 bind: Address already in use
85 errors.  These indicate the port is still being held by the unix
86 kernel and you are going to have to wait for it to let go of it.  If
87 this is the case, remember to use the port commands on the s_server and
88 s_client to talk on an alternative port.
89
90 =====
91 s_client.
92 This program can be used to connect to any IP/hostname:port that is
93 talking SSL.  Once connected, it will attempt to authenticate the
94 certificate it was passed and if everything works as expected, a 2
95 directional channel will be open.  Any text typed will be sent to the
96 other end.  type Q<cr> to exit.  Flags are as follows.
97 -host arg       : Arg is the host or IP address to connect to.
98 -port arg       : Arg is the port to connect to (https is 443).
99 -verify arg     : Turn on authentication of the server certificate.
100                 : Arg specifies the 'depth', this will covered below.
101 -cert arg       : The optional certificate to use.  This certificate
102                 : will be returned to the server if the server
103                 : requests it for client authentication.
104 -key arg        : The private key that matches the certificate
105                 : specified by the -cert option.  If this is not
106                 : specified (but -cert is), the -cert file will be
107                 : searched for the Private key.  Both files are
108                 : assumed to be in PEM format.
109 -CApath arg     : When to look for certificates when 'verifying' the
110                 : certificate from the server.
111 -CAfile arg     : A file containing certificates to be used for
112                 : 'verifying' the server certificate.
113 -reconnect      : Once a connection has been made, drop it and
114                 : reconnect with same session-id.  This is for testing :-).
115
116 The '-verify n' parameter specifies not only to verify the servers
117 certificate but to also only take notice of 'n' levels.  The best way
118 to explain is to show via examples.
119 Given
120 s_server -cert server.PEM is running.
121
122 s_client
123         CONNECTED
124         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
125         issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
126         verify error:num=1:unable to get issuer certificate
127         verify return:1
128         CIPHER is CBC-DES-MD5
129 What has happened is that the 'SSLeay demo server' certificate's
130 issuer ('CA') could not be found but because verify is not on, we
131 don't care and the connection has been made anyway.  It is now 'up'
132 using CBC-DES-MD5 mode.  This is an unauthenticate secure channel.
133 You may not be talking to the right person but the data going to them
134 is encrypted.
135
136 s_client -verify 0
137         CONNECTED
138         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
139         issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
140         verify error:num=1:unable to get issuer certificate
141         verify return:1
142         CIPHER is CBC-DES-MD5
143 We are 'verifying' but only to depth 0, so since the 'SSLeay demo server'
144 certificate passed the date and checksum, we are happy to proceed.
145
146 s_client -verify 1
147         CONNECTED
148         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
149         issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
150         verify error:num=1:unable to get issuer certificate
151         verify return:0
152         ERROR
153         verify error:unable to get issuer certificate
154 In this case we failed to make the connection because we could not
155 authenticate the certificate because we could not find the
156 'CA' certificate.
157
158 s_client -verify 1 -CAfile eay1024.PEM
159         CONNECTED
160         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
161         verify return:1
162         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
163         verify return:1
164         CIPHER is CBC-DES-MD5
165 We loaded the certificates from the file eay1024.PEM.  Everything
166 checked out and so we made the connection.
167
168 s_client -verify 1 -CApath .
169         CONNECTED
170         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
171         verify return:1
172         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
173         verify return:1
174         CIPHER is CBC-DES-MD5
175 We looked in out local directory for issuer certificates and 'found'
176 a8556381.0 and so everything is ok.
177
178 It is worth noting that 'CA' is a self certified certificate.  If you
179 are passed one of these, it will fail to 'verify' at depth 0 because
180 we need to lookup the certifier of a certificate from some information
181 that we trust and keep locally.
182
183 SSL_CIPHER=CBC3-DES-MD5:RC4-MD5
184 export SSL_CIPHER
185 s_client -verify 10 -CApath . -reconnect
186         CONNECTED
187         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
188         verify return:1
189         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
190         verify return:1
191         drop the connection and reconnect with the same session id
192         CIPHER is CBC3-DES-MD5
193 This has done a full connection and then re-estabished it with the
194 same session id but a new socket.  No RSA stuff occures on the second
195 connection.  Note that we said we would prefer to use CBC3-DES-MD5
196 encryption and so, since the server supports it, we are.
197
198 =====
199 s_server
200 This program accepts SSL connections on a specified port
201 Once connected, it will estabish an SSL connection and optionaly
202 attempt to authenticate the client.  A 2 directional channel will be
203 open.  Any text typed will be sent to the other end.  Type Q<cr> to exit.
204 Flags are as follows.
205 -port arg       : Arg is the port to listen on.
206 -verify arg     : Turn on authentication of the client if they have a
207                 : certificate.  Arg specifies the 'depth'.
208 -Verify arg     : Turn on authentication of the client. If they don't
209                 : have a valid certificate, drop the connection.
210 -cert arg       : The certificate to use.  This certificate
211                 : will be passed to the client.  If it is not
212                 : specified, it will default to server.PEM
213 -key arg        : The private key that matches the certificate
214                 : specified by the -cert option.  If this is not
215                 : specified (but -cert is), the -cert file will be
216                 : searched for the Private key.  Both files are
217                 : assumed to be in PEM format.  Default is server.PEM
218 -CApath arg     : When to look for certificates when 'verifying' the
219                 : certificate from the client.
220 -CAfile arg     : A file containing certificates to be used for
221                 : 'verifying' the client certificate.
222
223 For the following 'demo'  I will specify the s_server command and
224 the s_client command and then list the output from the s_server.
225 s_server
226 s_client
227         CONNECTED
228         CIPHER is CBC-DES-MD5
229 Everything up and running
230
231 s_server -verify 0
232 s_client  
233         CONNECTED
234         CIPHER is CBC-DES-MD5
235 Ok since no certificate was returned and we don't care.
236
237 s_server -verify 0
238 ./s_client -cert client.PEM
239         CONNECTED
240         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
241         issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
242         verify error:num=1:unable to get issuer certificate
243         verify return:1
244         CIPHER is CBC-DES-MD5
245 Ok since we were only verifying to level 0
246
247 s_server -verify 4
248 s_client -cert client.PEM
249         CONNECTED
250         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
251         issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
252         verify error:num=1:unable to get issuer certificate
253         verify return:0
254         ERROR
255         verify error:unable to get issuer certificate
256 Bad because we could not authenticate the returned certificate.
257
258 s_server -verify 4 -CApath .
259 s_client -cert client.PEM
260         CONNECTED
261         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
262         verify return:1
263         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
264         verify return:1
265         CIPHER is CBC-DES-MD5
266 Ok because we could authenticate the returned certificate :-).
267
268 s_server -Verify 0 -CApath .
269 s_client
270         CONNECTED
271         ERROR
272         SSL error:function is:REQUEST_CERTIFICATE
273                  :error is   :client end did not return a certificate
274 Error because no certificate returned.
275
276 s_server -Verify 4 -CApath .
277 s_client -cert client.PEM
278         CONNECTED
279         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
280         verify return:1
281         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
282         verify return:1
283         CIPHER is CBC-DES-MD5
284 Full authentication of the client.
285
286 So in summary to do full authentication of both ends
287 s_server -Verify 9 -CApath .
288 s_client -cert client.PEM -CApath . -verify 9
289 From the server side
290         CONNECTED
291         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
292         verify return:1
293         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
294         verify return:1
295         CIPHER is CBC-DES-MD5
296 From the client side
297         CONNECTED
298         depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
299         verify return:1
300         depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
301         verify return:1
302         CIPHER is CBC-DES-MD5
303
304 For general probing of the 'internet https' servers for the
305 distribution area, run
306 s_client -host www.netscape.com -port 443 -verify 4 -CApath ../rsa/hash
307 Then enter
308 GET /
309 and you should be talking to the https server on that host.
310
311 www.rsa.com was refusing to respond to connections on 443 when I was
312 testing.
313
314 have fun :-).
315
316 eric
317
318 ==== a_verify.doc ========================================================
319
320 From eay@mincom.com Fri Oct  4 18:29:06 1996
321 Received: by orb.mincom.oz.au id AA29080
322   (5.65c/IDA-1.4.4 for eay); Fri, 4 Oct 1996 08:29:07 +1000
323 Date: Fri, 4 Oct 1996 08:29:06 +1000 (EST)
324 From: Eric Young <eay@mincom.oz.au>
325 X-Sender: eay@orb
326 To: wplatzer <wplatzer@iaik.tu-graz.ac.at>
327 Cc: Eric Young <eay@mincom.oz.au>, SSL Mailing List <ssl-users@mincom.com>
328 Subject: Re: Netscape's Public Key
329 In-Reply-To: <19961003134837.NTM0049@iaik.tu-graz.ac.at>
330 Message-Id: <Pine.SOL.3.91.961004081346.8018K-100000@orb>
331 Mime-Version: 1.0
332 Content-Type: TEXT/PLAIN; charset=US-ASCII
333 Status: RO
334 X-Status: 
335
336 On Thu, 3 Oct 1996, wplatzer wrote:
337 > I get Public Key from Netscape (Gold 3.0b4), but cannot do anything
338 > with it... It looks like (asn1parse):
339
340 > 0:d=0 hl=3 l=180 cons: SEQUENCE
341 > 3:d=1 hl=2 l= 96 cons: SEQUENCE
342 > 5:d=2 hl=2 l= 92 cons: SEQUENCE
343 > 7:d=3 hl=2 l= 13 cons: SEQUENCE
344 > 9:d=4 hl=2 l= 9 prim: OBJECT :rsaEncryption
345 > 20:d=4 hl=2 l= 0 prim: NULL
346 > 22:d=3 hl=2 l= 75 prim: BIT STRING
347 > 99:d=2 hl=2 l= 0 prim: IA5STRING :
348 > 101:d=1 hl=2 l= 13 cons: SEQUENCE
349 > 103:d=2 hl=2 l= 9 prim: OBJECT :md5withRSAEncryption
350 > 114:d=2 hl=2 l= 0 prim: NULL
351 > 116:d=1 hl=2 l= 65 prim: BIT STRING
352
353 > The first BIT STRING is the public key and the second BIT STRING is 
354 > the signature.
355 > But a public key consists of the public exponent and the modulus. Are 
356 > both numbers in the first BIT STRING?
357 > Is there a document simply describing this coding stuff (checking 
358 > signature, get the public key, etc.)?
359
360 Minimal in SSLeay.  If you want to see what the modulus and exponent are,
361 try asn1parse -offset 25 -length 75 <key.pem
362 asn1parse will currently stuff up on the 'length 75' part (fixed in next 
363 release) but it will print the stuff.  If you are after more 
364 documentation on ASN.1, have a look at www.rsa.com and get their PKCS 
365 documents, most of my initial work on SSLeay was done using them.
366
367 As for SSLeay,
368 util/crypto.num and util/ssl.num are lists of all exported functions in 
369 the library (but not macros :-(.
370
371 The ones for extracting public keys from certificates and certificate 
372 requests are EVP_PKEY *      X509_REQ_extract_key(X509_REQ *req);
373 EVP_PKEY *      X509_extract_key(X509 *x509);
374
375 To verify a signature on a signed ASN.1 object
376 int X509_verify(X509 *a,EVP_PKEY *key);
377 int X509_REQ_verify(X509_REQ *a,EVP_PKEY *key);
378 int X509_CRL_verify(X509_CRL *a,EVP_PKEY *key);
379 int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a,EVP_PKEY *key);
380
381 I should mention that EVP_PKEY can be used to hold a public or a private key,
382 since for  things like RSA and DSS, a public key is just a subset of what 
383 is stored for the private key.
384
385 To sign any of the above structures
386
387 int X509_sign(X509 *a,EVP_PKEY *key,EVP_MD *md);
388 int X509_REQ_sign(X509_REQ *a,EVP_PKEY *key,EVP_MD *md);
389 int X509_CRL_sign(X509_CRL *a,EVP_PKEY *key,EVP_MD *md);
390 int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *a,EVP_PKEY *key,EVP_MD *md);
391
392 where md is the message digest to sign with.
393
394 There are all defined in x509.h and all the _sign and _verify functions are
395 actually macros to the ASN1_sign() and ASN1_verify() functions.
396 These functions will put the correct algorithm identifiers in the correct 
397 places in the structures.
398
399 eric
400 --
401 Eric Young                  | BOOL is tri-state according to Bill Gates.
402 AARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
403
404 ==== x509 =======================================================
405
406 X509_verify()
407 X509_sign()
408
409 X509_get_version()
410 X509_get_serialNumber()
411 X509_get_issuer()
412 X509_get_subject()
413 X509_get_notBefore()
414 X509_get_notAfter()
415 X509_get_pubkey()
416
417 X509_set_version()
418 X509_set_serialNumber()
419 X509_set_issuer()
420 X509_set_subject()
421 X509_set_notBefore()
422 X509_set_notAfter()
423 X509_set_pubkey()
424
425 X509_get_extensions()
426 X509_set_extensions()
427
428 X509_EXTENSIONS_clear()
429 X509_EXTENSIONS_retrieve()
430 X509_EXTENSIONS_add()
431 X509_EXTENSIONS_delete()
432
433 ==== x509 attribute ================================================
434
435 PKCS7
436         STACK of X509_ATTRIBUTES
437                 ASN1_OBJECT
438                 STACK of ASN1_TYPE
439
440 So it is
441
442 p7.xa[].obj
443 p7.xa[].data[]
444
445 get_obj_by_nid(STACK , nid)
446 get_num_by_nid(STACK , nid)
447 get_data_by_nid(STACK , nid, index)
448
449 X509_ATTRIBUTE *X509_ATTRIBUTE_new(void );
450 void            X509_ATTRIBUTE_free(X509_ATTRIBUTE *a);
451
452 X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **ex,
453                         int nid, STACK *value);
454
455 X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **ex,
456                         int nid, STACK *value);
457
458 int             X509_ATTRIBUTE_set_object(X509_ATTRIBUTE *ex,ASN1_OBJECT *obj);
459 int             X509_ATTRIBUTE_add_data(X509_ATTRIBUTE *ex, int index,
460                         ASN1_TYPE *value);
461
462 ASN1_OBJECT *   X509_ATTRIBUTE_get_object(X509_ATTRIBUTE *ex);
463 int             X509_ATTRIBUTE_get_num(X509_ATTRIBUTE *ne);
464 ASN1_TYPE *     X509_ATTRIBUTE_get_data(X509_ATTRIBUTE *ne,int index);
465
466 ASN1_TYPE *     X509_ATTRIBUTE_get_data_by_NID(X509_ATTRIBUTE *ne,
467                         ASN1_OBJECT *obj);
468
469 X509_ATTRIBUTE *PKCS7_get_s_att_by_NID(PKCS7 *p7,int nid);
470 X509_ATTRIBUTE *PKCS7_get_u_att_by_NID(PKCS7 *p7,int nid);
471
472 ==== x509 v3 ========================================================
473
474 The 'new' system.
475
476 The X509_EXTENSION_METHOD includes extensions and attributes and/or names. 
477 Basically everthing that can be added to an X509 with an OID identifying it.
478
479 It operates via 2 methods per object id.
480 int a2i_XXX(X509 *x,char *str,int len);
481 int i2a_XXX(BIO *bp,X509 *x);
482
483 The a2i_XXX function will add the object with a value converted from the
484 string into the X509.  Len can be -1 in which case the length is calculated
485 via strlen(str).   Applications can always use direct knowledge to load and
486 unload the relevent objects themselves.
487
488 i2a_XXX will print to the passed BIO, a text representation of the
489 relevet object.  Use a memory BIO if you want it printed to a buffer :-).
490
491 X509_add_by_NID(X509 *x,int nid,char *str,int len);
492 X509_add_by_OBJ(X509 *x,ASN1_OBJECT *obj,char *str,int len);
493
494 X509_print_by_name(BIO *bp,X509 *x);
495 X509_print_by_NID(BIO *bp,X509 *x);
496 X509_print_by_OBJ(BIO *bp,X509 *x);
497
498 ==== verify ========================================================
499
500 X509_verify_cert_chain(
501         CERT_STORE *cert_store,
502         STACK /* X509 */ *certs,
503         int *verify_result,
504         int (*verify_error_callback)()
505         char *argument_to_callback, /* SSL */
506
507 app_verify_callback(
508         char *app_verify_arg, /* from SSL_CTX */
509         STACK /* X509 */ *certs,
510         int *verify_result,
511         int (*verify_error_callback)()
512         SSL *s,
513
514 int X509_verify_cert(
515         CERT_STORE *cert_store,
516         X509 *x509,
517         int *verify_result,
518         int (*verify_error_callback)(),
519         char *arg,
520
521 ==== apps.doc ========================================================
522
523 The applications
524
525 Ok, where to begin....
526 In the begining, when SSLeay was small (April 1995), there
527 were but few applications, they did happily cohabit in
528 the one bin directory.  Then over time, they did multiply and grow,
529 and they started to look like microsoft software; 500k to print 'hello world'.
530 A new approach was needed.  They were coalessed into one 'Monolithic'
531 application, ssleay.  This one program is composed of many programs that
532 can all be compiled independantly.
533
534 ssleay has 3 modes of operation.
535 1) If the ssleay binaray has the name of one of its component programs, it
536 executes that program and then exits.  This can be achieve by using hard or
537 symbolic links, or failing that, just renaming the binary.
538 2) If the first argument to ssleay is the name of one of the component
539 programs, that program runs that program and then exits.
540 3) If there are no arguments, ssleay enters a 'command' mode.  Each line is
541 interpreted as a program name plus arguments.  After each 'program' is run,
542 ssleay returns to the comand line.
543
544 dgst    - message digests
545 enc     - encryption and base64 encoding
546
547 ans1parse - 'pulls' appart ASN.1 encoded objects like certificates.
548
549 dh      - Diffle-Hellman parameter manipulation.
550 rsa     - RSA manipulations.
551 crl     - Certificate revokion list manipulations
552 x509    - X509 cert fiddles, including signing.
553 pkcs7   - pkcs7 manipulation, only DER versions right now.
554
555 genrsa  - generate an RSA private key.
556 gendh   - Generate a set of Diffle-Hellman parameters.
557 req     - Generate a PKCS#10 object, a certificate request.
558
559 s_client - SSL client program
560 s_server - SSL server program
561 s_time   - A SSL protocol timing program
562 s_mult   - Another SSL server, but it multiplexes
563            connections.
564 s_filter - under development
565
566 errstr  - Convert SSLeay error numbers to strings.
567 ca      - Sign certificate requests, and generate
568           certificate revokion lists
569 crl2pkcs7 - put a crl and certifcates into a pkcs7 object.
570 speed   - Benchmark the ciphers.
571 verify  - Check certificates
572 hashdir - under development
573
574 [ there a now a few more options, play with the program to see what they
575   are ]
576
577 ==== asn1.doc ========================================================
578
579 The ASN.1 Routines.
580
581 ASN.1 is a specification for how to encode structured 'data' in binary form.
582 The approach I have take to the manipulation of structures and their encoding
583 into ASN.1 is as follows.
584
585 For each distinct structure there are 4 function of the following form
586 TYPE *TYPE_new(void);
587 void TYPE_free(TYPE *);
588 TYPE *d2i_TYPE(TYPE **a,unsigned char **pp,long length);
589 long i2d_TYPE(TYPE *a,unsigned char **pp);      /* CHECK RETURN VALUE */
590
591 where TYPE is the type of the 'object'.  The TYPE that have these functions
592 can be in one of 2 forms, either the internal C malloc()ed data structure
593 or in the DER (a variant of ASN.1 encoding) binary encoding which is just
594 an array of unsigned bytes.  The 'i2d' functions converts from the internal
595 form to the DER form and the 'd2i' functions convert from the DER form to
596 the internal form.
597
598 The 'new' function returns a malloc()ed version of the structure with all
599 substructures either created or left as NULL pointers.  For 'optional'
600 fields, they are normally left as NULL to indicate no value.  For variable
601 size sub structures (often 'SET OF' or 'SEQUENCE OF' in ASN.1 syntax) the
602 STACK data type is used to hold the values.  Have a read of stack.doc
603 and have a look at the relevant header files to see what I mean.  If there
604 is an error while malloc()ing the structure, NULL is returned.
605
606 The 'free' function will free() all the sub components of a particular
607 structure.  If any of those sub components have been 'removed', replace
608 them with NULL pointers, the 'free' functions are tolerant of NULL fields.
609
610 The 'd2i' function copies a binary representation into a C structure.  It
611 operates as follows.  'a' is a pointer to a pointer to
612 the structure to populate, 'pp' is a pointer to a pointer to where the DER
613 byte string is located and 'length' is the length of the '*pp' data.
614 If there are no errors, a pointer to the populated structure is returned.
615 If there is an error, NULL is returned.  Errors can occur because of
616 malloc() failures but normally they will be due to syntax errors in the DER
617 encoded data being parsed. It is also an error if there was an
618 attempt to read more that 'length' bytes from '*p'.  If
619 everything works correctly, the value in '*p' is updated
620 to point at the location just beyond where the DER
621 structure was read from.  In this way, chained calls to 'd2i' type
622 functions can be made, with the pointer into the 'data' array being
623 'walked' along the input byte array.
624 Depending on the value passed for 'a', different things will be done.  If
625 'a' is NULL, a new structure will be malloc()ed and returned.  If '*a' is
626 NULL, a new structure will be malloc()ed and put into '*a' and returned.
627 If '*a' is not NULL, the structure in '*a' will be populated, or in the
628 case of an error, free()ed and then returned.
629 Having these semantics means that a structure
630 can call a 'd2i' function to populate a field and if the field is currently
631 NULL, the structure will be created.
632
633 The 'i2d' function type is used to copy a C structure to a byte array.
634 The parameter 'a' is the structure to convert and '*p' is where to put it.
635 As for the 'd2i' type structure, 'p' is updated to point after the last
636 byte written.  If p is NULL, no data is written.  The function also returns
637 the number of bytes written.  Where this becomes useful is that if the
638 function is called with a NULL 'p' value, the length is returned.  This can
639 then be used to malloc() an array of bytes and then the same function can
640 be recalled passing the malloced array to be written to. e.g.
641
642 int len;
643 unsigned char *bytes,*p;
644 len=i2d_X509(x,NULL);   /* get the size of the ASN1 encoding of 'x' */
645 if ((bytes=(unsigned char *)malloc(len)) == NULL)
646         goto err;
647 p=bytes;
648 i2d_X509(x,&p);
649
650 Please note that a new variable, 'p' was passed to i2d_X509.  After the
651 call to i2d_X509 p has been incremented by len bytes.
652
653 Now the reason for this functional organisation is that it allows nested
654 structures to be built up by calling these functions as required.  There
655 are various macros used to help write the general 'i2d', 'd2i', 'new' and
656 'free' functions.  They are discussed in another file and would only be
657 used by some-one wanting to add new structures to the library.  As you
658 might be able to guess, the process of writing ASN.1 files can be a bit CPU
659 expensive for complex structures.  I'm willing to live with this since the
660 simpler library code make my life easier and hopefully most programs using
661 these routines will have their execution profiles dominated by cipher or
662 message digest routines.
663 What follows is a list of 'TYPE' values and the corresponding ASN.1
664 structure and where it is used.
665
666 TYPE                    ASN.1
667 ASN1_INTEGER            INTEGER
668 ASN1_BIT_STRING         BIT STRING
669 ASN1_OCTET_STRING       OCTET STRING
670 ASN1_OBJECT             OBJECT IDENTIFIER
671 ASN1_PRINTABLESTRING    PrintableString
672 ASN1_T61STRING          T61String
673 ASN1_IA5STRING          IA5String
674 ASN1_UTCTIME            UTCTime
675 ASN1_TYPE               Any of the above mentioned types plus SEQUENCE and SET
676
677 Most of the above mentioned types are actualled stored in the
678 ASN1_BIT_STRING type and macros are used to differentiate between them.
679 The 3 types used are
680
681 typedef struct asn1_object_st
682         {
683         /* both null if a dynamic ASN1_OBJECT, one is
684          * defined if a 'static' ASN1_OBJECT */
685         char *sn,*ln;
686         int nid;
687         int length;
688         unsigned char *data;
689         } ASN1_OBJECT;
690 This is used to store ASN1 OBJECTS.  Read 'objects.doc' for details ono
691 routines to manipulate this structure.  'sn' and 'ln' are used to hold text
692 strings that represent the object (short name and long or lower case name).
693 These are used by the 'OBJ' library.  'nid' is a number used by the OBJ
694 library to uniquely identify objects.  The ASN1 routines will populate the
695 'length' and 'data' fields which will contain the bit string representing
696 the object.
697
698 typedef struct asn1_bit_string_st
699         {
700         int length;
701         int type;
702         unsigned char *data;
703         } ASN1_BIT_STRING;
704 This structure is used to hold all the other base ASN1 types except for
705 ASN1_UTCTIME (which is really just a 'char *').  Length is the number of
706 bytes held in data and type is the ASN1 type of the object (there is a list
707 in asn1.h).
708
709 typedef struct asn1_type_st
710         {
711         int type;
712         union   {
713                 char *ptr;
714                 ASN1_INTEGER *          integer;
715                 ASN1_BIT_STRING *       bit_string;
716                 ASN1_OCTET_STRING *     octet_string;
717                 ASN1_OBJECT *           object;
718                 ASN1_PRINTABLESTRING *  printablestring;
719                 ASN1_T61STRING *        t61string;
720                 ASN1_IA5STRING *        ia5string;
721                 ASN1_UTCTIME *          utctime;
722                 ASN1_BIT_STRING *       set;
723                 ASN1_BIT_STRING *       sequence;
724                 } value;
725         } ASN1_TYPE;
726 This structure is used in a few places when 'any' type of object can be
727 expected.
728
729 X509                    Certificate
730 X509_CINF               CertificateInfo
731 X509_ALGOR              AlgorithmIdentifier
732 X509_NAME               Name                    
733 X509_NAME_ENTRY         A single sub component of the name.
734 X509_VAL                Validity
735 X509_PUBKEY             SubjectPublicKeyInfo
736 The above mentioned types are declared in x509.h. They are all quite
737 straight forward except for the X509_NAME/X509_NAME_ENTRY pair.
738 A X509_NAME is a STACK (see stack.doc) of X509_NAME_ENTRY's.
739 typedef struct X509_name_entry_st
740         {
741         ASN1_OBJECT *object;
742         ASN1_BIT_STRING *value;
743         int set;
744         int size;       /* temp variable */
745         } X509_NAME_ENTRY;
746 The size is a temporary variable used by i2d_NAME and set is the set number
747 for the particular NAME_ENTRY.  A X509_NAME is encoded as a sequence of
748 sequence of sets.  Normally each set contains only a single item.
749 Sometimes it contains more.  Normally throughout this library there will be
750 only one item per set.  The set field contains the 'set' that this entry is
751 a member of.  So if you have just created a X509_NAME structure and
752 populated it with X509_NAME_ENTRYs, you should then traverse the X509_NAME
753 (which is just a STACK) and set the 'set/' field to incrementing numbers.
754 For more details on why this is done, read the ASN.1 spec for Distinguished
755 Names.
756
757 X509_REQ                CertificateRequest
758 X509_REQ_INFO           CertificateRequestInfo
759 These are used to hold certificate requests.
760
761 X509_CRL                CertificateRevocationList
762 These are used to hold a certificate revocation list
763
764 RSAPrivateKey           PrivateKeyInfo
765 RSAPublicKey            PublicKeyInfo
766 Both these 'function groups' operate on 'RSA' structures (see rsa.doc).
767 The difference is that the RSAPublicKey operations only manipulate the m
768 and e fields in the RSA structure.
769
770 DSAPrivateKey           DSS private key
771 DSAPublicKey            DSS public key
772 Both these 'function groups' operate on 'DSS' structures (see dsa.doc).
773 The difference is that the RSAPublicKey operations only manipulate the 
774 XXX fields in the DSA structure.
775
776 DHparams                DHParameter
777 This is used to hold the p and g value for The Diffie-Hellman operation.
778 The function deal with the 'DH' strucure (see dh.doc).
779
780 Now all of these function types can be used with several other functions to give
781 quite useful set of general manipulation routines.  Normally one would
782 not uses these functions directly but use them via macros. 
783
784 char *ASN1_dup(int (*i2d)(),char *(*d2i)(),char *x);
785 'x' is the input structure case to a 'char *', 'i2d' is the 'i2d_TYPE'
786 function for the type that 'x' is and d2i is the 'd2i_TYPE' function for the
787 type that 'x' is.  As is obvious from the parameters, this function
788 duplicates the strucutre by transforming it into the DER form and then
789 re-loading it into a new strucutre and returning the new strucutre.  This
790 is obviously a bit cpu intensive but when faced with a complex dynamic
791 structure this is the simplest programming approach.  There are macros for
792 duplicating the major data types but is simple to add extras.
793
794 char *ASN1_d2i_fp(char *(*new)(),char *(*d2i)(),FILE *fp,unsigned char **x);
795 'x' is a pointer to a pointer of the 'desired type'.  new and d2i are the
796 corresponding 'TYPE_new' and 'd2i_TYPE' functions for the type and 'fp' is
797 an open file pointer to read from.  This function reads from 'fp' as much
798 data as it can and then uses 'd2i' to parse the bytes to load and return
799 the parsed strucutre in 'x' (if it was non-NULL) and to actually return the
800 strucutre.  The behavior of 'x' is as per all the other d2i functions.
801
802 char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
803 The 'BIO' is the new IO type being used in SSLeay (see bio.doc).  This
804 function is the same as ASN1_d2i_fp() except for the BIO argument.
805 ASN1_d2i_fp() actually calls this function.
806
807 int ASN1_i2d_fp(int (*i2d)(),FILE *out,unsigned char *x);
808 'x' is converted to bytes by 'i2d' and then written to 'out'.  ASN1_i2d_fp
809 and ASN1_d2i_fp are not really symetric since ASN1_i2d_fp will read all
810 available data from the file pointer before parsing a single item while
811 ASN1_i2d_fp can be used to write a sequence of data objects.  To read a
812 series of objects from a file I would sugest loading the file into a buffer
813 and calling the relevent 'd2i' functions.
814
815 char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
816 This function is the same as ASN1_i2d_fp() except for the BIO argument.
817 ASN1_i2d_fp() actually calls this function.
818
819 char *  PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
820 This function will read the next PEM encoded (base64) object of the same
821 type as 'x' (loaded by the d2i function).  'name' is the name that is in
822 the '-----BEGIN name-----' that designates the start of that object type.
823 If the data is encrypted, 'cb' will be called to prompt for a password.  If
824 it is NULL a default function will be used to prompt from the password.
825 'x' is delt with as per the standard 'd2i' function interface.  This
826 function can be used to read a series of objects from a file.  While any
827 data type can be encrypted (see PEM_ASN1_write) only RSA private keys tend
828 to be encrypted.
829
830 char *  PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *fp,
831         char **x,int (*cb)());
832 Same as PEM_ASN1_read() except using a BIO.  This is called by
833 PEM_ASN1_read().
834
835 int     PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,EVP_CIPHER *enc,
836                 unsigned char *kstr,int klen,int (*callback)());
837
838 int     PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *fp,
839                 char *x,EVP_CIPHER *enc,unsigned char *kstr,int klen,
840                 int (*callback)());
841
842 int ASN1_sign(int (*i2d)(), X509_ALGOR *algor1, X509_ALGOR *algor2,
843         ASN1_BIT_STRING *signature, char *data, RSA *rsa, EVP_MD *type);
844 int ASN1_verify(int (*i2d)(), X509_ALGOR *algor1,
845         ASN1_BIT_STRING *signature,char *data, RSA *rsa);
846
847 int ASN1_BIT_STRING_cmp(ASN1_BIT_STRING *a, ASN1_BIT_STRING *b);
848 ASN1_BIT_STRING *ASN1_BIT_STRING_type_new(int type );
849
850 int ASN1_UTCTIME_check(ASN1_UTCTIME *a);
851 void ASN1_UTCTIME_print(BIO *fp,ASN1_UTCTIME *a);
852 ASN1_UTCTIME *ASN1_UTCTIME_dup(ASN1_UTCTIME *a);
853
854 ASN1_BIT_STRING *d2i_asn1_print_type(ASN1_BIT_STRING **a,unsigned char **pp,
855                 long length,int type);
856
857 int             i2d_ASN1_SET(STACK *a, unsigned char **pp,
858                         int (*func)(), int ex_tag, int ex_class);
859 STACK *         d2i_ASN1_SET(STACK **a, unsigned char **pp, long length,
860                         char *(*func)(), int ex_tag, int ex_class);
861
862 int i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *object);
863 int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
864 int a2i_ASN1_INTEGER(BIO *bp,ASN1_INTEGER *bs,char *buf,int size);
865
866 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
867 long ASN1_INTEGER_get(ASN1_INTEGER *a);
868 ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
869 BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
870
871 /* given a string, return the correct type.  Max is the maximum number
872  * of bytes to parse.  It stops parsing when 'max' bytes have been
873  * processed or a '\0' is hit */
874 int ASN1_PRINTABLE_type(unsigned char *s,int max);
875
876 void ASN1_parse(BIO *fp,unsigned char *pp,long len);
877
878 int i2d_ASN1_bytes(ASN1_BIT_STRING *a, unsigned char **pp, int tag, int class);
879 ASN1_BIT_STRING *d2i_ASN1_bytes(ASN1_OCTET_STRING **a, unsigned char **pp,
880         long length, int Ptag, int Pclass);
881
882 /* PARSING */
883 int asn1_Finish(ASN1_CTX *c);
884
885 /* SPECIALS */
886 int ASN1_get_object(unsigned char **pp, long *plength, int *ptag,
887         int *pclass, long omax);
888 int ASN1_check_infinite_end(unsigned char **p,long len);
889 void ASN1_put_object(unsigned char **pp, int constructed, int length,
890         int tag, int class);
891 int ASN1_object_size(int constructed, int length, int tag);
892
893 X509 *  X509_get_cert(CERTIFICATE_CTX *ctx,X509_NAME * name,X509 *tmp_x509);
894 int     X509_add_cert(CERTIFICATE_CTX *ctx,X509 *);
895
896 char *  X509_cert_verify_error_string(int n);
897 int     X509_add_cert_file(CERTIFICATE_CTX *c,char *file, int type);
898 char *  X509_gmtime (char *s, long adj);
899 int     X509_add_cert_dir (CERTIFICATE_CTX *c,char *dir, int type);
900 int     X509_load_verify_locations (CERTIFICATE_CTX *ctx,
901                 char *file_env, char *dir_env);
902 int     X509_set_default_verify_paths(CERTIFICATE_CTX *cts);
903 X509 *  X509_new_D2i_X509(int len, unsigned char *p);
904 char *  X509_get_default_cert_area(void );
905 char *  X509_get_default_cert_dir(void );
906 char *  X509_get_default_cert_file(void );
907 char *  X509_get_default_cert_dir_env(void );
908 char *  X509_get_default_cert_file_env(void );
909 char *  X509_get_default_private_dir(void );
910 X509_REQ *X509_X509_TO_req(X509 *x, RSA *rsa);
911 int     X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)()); 
912
913 CERTIFICATE_CTX *CERTIFICATE_CTX_new();
914 void CERTIFICATE_CTX_free(CERTIFICATE_CTX *c);
915
916 void X509_NAME_print(BIO *fp, X509_NAME *name, int obase);
917 int             X509_print_fp(FILE *fp,X509 *x);
918 int             X509_print(BIO *fp,X509 *x);
919
920 X509_INFO *     X509_INFO_new(void);
921 void            X509_INFO_free(X509_INFO *a);
922
923 char *          X509_NAME_oneline(X509_NAME *a);
924
925 #define X509_verify(x,rsa)
926 #define X509_REQ_verify(x,rsa)
927 #define X509_CRL_verify(x,rsa)
928
929 #define X509_sign(x,rsa,md)
930 #define X509_REQ_sign(x,rsa,md)
931 #define X509_CRL_sign(x,rsa,md)
932
933 #define X509_dup(x509)
934 #define d2i_X509_fp(fp,x509)
935 #define i2d_X509_fp(fp,x509)
936 #define d2i_X509_bio(bp,x509)
937 #define i2d_X509_bio(bp,x509)
938
939 #define X509_CRL_dup(crl)
940 #define d2i_X509_CRL_fp(fp,crl)
941 #define i2d_X509_CRL_fp(fp,crl)
942 #define d2i_X509_CRL_bio(bp,crl)
943 #define i2d_X509_CRL_bio(bp,crl)
944
945 #define X509_REQ_dup(req)
946 #define d2i_X509_REQ_fp(fp,req)
947 #define i2d_X509_REQ_fp(fp,req)
948 #define d2i_X509_REQ_bio(bp,req)
949 #define i2d_X509_REQ_bio(bp,req)
950
951 #define RSAPrivateKey_dup(rsa)
952 #define d2i_RSAPrivateKey_fp(fp,rsa)
953 #define i2d_RSAPrivateKey_fp(fp,rsa)
954 #define d2i_RSAPrivateKey_bio(bp,rsa)
955 #define i2d_RSAPrivateKey_bio(bp,rsa)
956
957 #define X509_NAME_dup(xn)
958 #define X509_NAME_ENTRY_dup(ne)
959
960 void X509_REQ_print_fp(FILE *fp,X509_REQ *req);
961 void X509_REQ_print(BIO *fp,X509_REQ *req);
962
963 RSA *X509_REQ_extract_key(X509_REQ *req);
964 RSA *X509_extract_key(X509 *x509);
965
966 int             X509_issuer_and_serial_cmp(X509 *a, X509 *b);
967 unsigned long   X509_issuer_and_serial_hash(X509 *a);
968
969 X509_NAME *     X509_get_issuer_name(X509 *a);
970 int             X509_issuer_name_cmp(X509 *a, X509 *b);
971 unsigned long   X509_issuer_name_hash(X509 *a);
972
973 X509_NAME *     X509_get_subject_name(X509 *a);
974 int             X509_subject_name_cmp(X509 *a,X509 *b);
975 unsigned long   X509_subject_name_hash(X509 *x);
976
977 int             X509_NAME_cmp (X509_NAME *a, X509_NAME *b);
978 unsigned long   X509_NAME_hash(X509_NAME *x);
979
980
981 ==== bio.doc ========================================================
982
983 BIO Routines
984
985 This documentation is rather sparse, you are probably best 
986 off looking at the code for specific details.
987
988 The BIO library is a IO abstraction that was originally 
989 inspired by the need to have callbacks to perform IO to FILE 
990 pointers when using Windows 3.1 DLLs.  There are two types 
991 of BIO; a source/sink type and a filter type.
992 The source/sink methods are as follows:
993 -       BIO_s_mem()  memory buffer - a read/write byte array that
994         grows until memory runs out :-).
995 -       BIO_s_file()  FILE pointer - A wrapper around the normal 
996         'FILE *' commands, good for use with stdin/stdout.
997 -       BIO_s_fd()  File descriptor - A wrapper around file 
998         descriptors, often used with pipes.
999 -       BIO_s_socket()  Socket - Used around sockets.  It is 
1000         mostly in the Microsoft world that sockets are different 
1001         from file descriptors and there are all those ugly winsock 
1002         commands.
1003 -       BIO_s_null()  Null - read nothing and write nothing.; a 
1004         useful endpoint for filter type BIO's specifically things 
1005         like the message digest BIO.
1006
1007 The filter types are
1008 -       BIO_f_buffer()  IO buffering - does output buffering into 
1009         larger chunks and performs input buffering to allow gets() 
1010         type functions.
1011 -       BIO_f_md()  Message digest - a transparent filter that can 
1012         be asked to return a message digest for the data that has 
1013         passed through it.
1014 -       BIO_f_cipher()  Encrypt or decrypt all data passing 
1015         through the filter.
1016 -       BIO_f_base64()  Base64 decode on read and encode on write.
1017 -       BIO_f_ssl()  A filter that performs SSL encryption on the 
1018         data sent through it.
1019
1020 Base BIO functions.
1021 The BIO library has a set of base functions that are 
1022 implemented for each particular type.  Filter BIOs will 
1023 normally call the equivalent function on the source/sink BIO 
1024 that they are layered on top of after they have performed 
1025 some modification to the data stream.  Multiple filter BIOs 
1026 can be 'push' into a stack of modifers, so to read from a 
1027 file, unbase64 it, then decrypt it, a BIO_f_cipher, 
1028 BIO_f_base64 and a BIO_s_file would probably be used.  If a 
1029 sha-1 and md5 message digest needed to be generated, a stack 
1030 two BIO_f_md() BIOs and a BIO_s_null() BIO could be used.
1031 The base functions are
1032 -       BIO *BIO_new(BIO_METHOD *type); Create  a new BIO of  type 'type'.
1033 -       int BIO_free(BIO *a); Free a BIO structure.  Depending on 
1034         the configuration, this will free the underlying data 
1035         object for a source/sink BIO.
1036 -       int BIO_read(BIO *b, char *data, int len); Read upto 'len' 
1037         bytes into 'data'. 
1038 -       int BIO_gets(BIO *bp,char *buf, int size); Depending on 
1039         the BIO, this can either be a 'get special' or a get one 
1040         line of data, as per fgets();
1041 -       int BIO_write(BIO *b, char *data, int len); Write 'len' 
1042         bytes from 'data' to the 'b' BIO.
1043 -       int BIO_puts(BIO *bp,char *buf); Either a 'put special' or 
1044         a write null terminated string as per fputs().
1045 -       long BIO_ctrl(BIO *bp,int cmd,long larg,char *parg);  A 
1046         control function which is used to manipulate the BIO 
1047         structure and modify it's state and or report on it.  This 
1048         function is just about never used directly, rather it 
1049         should be used in conjunction with BIO_METHOD specific 
1050         macros.
1051 -       BIO *BIO_push(BIO *new_top, BIO *old); new_top is apped to the
1052         top of the 'old' BIO list.  new_top should be a filter BIO.
1053         All writes will go through 'new_top' first and last on read.
1054         'old' is returned.
1055 -       BIO *BIO_pop(BIO *bio); the new topmost BIO is returned, NULL if
1056         there are no more.
1057
1058 If a particular low level BIO method is not supported 
1059 (normally BIO_gets()), -2 will be returned if that method is 
1060 called.  Otherwise the IO methods (read, write, gets, puts) 
1061 will return the number of bytes read or written, and 0 or -1 
1062 for error (or end of input).  For the -1 case, 
1063 BIO_should_retry(bio) can be called to determine if it was a 
1064 genuine error or a temporary problem.  -2 will also be 
1065 returned if the BIO has not been initalised yet, in all 
1066 cases, the correct error codes are set (accessible via the 
1067 ERR library).
1068
1069
1070 The following functions are convenience functions:
1071 -       int BIO_printf(BIO *bio, char * format, ..);  printf but 
1072         to a BIO handle.
1073 -       long BIO_ctrl_int(BIO *bp,int cmd,long larg,int iarg); a 
1074         convenience function to allow a different argument types 
1075         to be passed to BIO_ctrl().
1076 -       int BIO_dump(BIO *b,char *bytes,int len); output 'len' 
1077         bytes from 'bytes' in a hex dump debug format.
1078 -       long BIO_debug_callback(BIO *bio, int cmd, char *argp, int 
1079         argi, long argl, long ret) - a default debug BIO callback, 
1080         this is mentioned below.  To use this one normally has to 
1081         use the BIO_set_callback_arg() function to assign an 
1082         output BIO for the callback to use.
1083 -       BIO *BIO_find_type(BIO *bio,int type); when there is a 'stack'
1084         of BIOs, this function scan the list and returns the first
1085         that is of type 'type', as listed in buffer.h under BIO_TYPE_XXX.
1086 -       void BIO_free_all(BIO *bio); Free the bio and all other BIOs
1087         in the list.  It walks the bio->next_bio list.
1088
1089
1090
1091 Extra commands are normally implemented as macros calling BIO_ctrl().
1092 -       BIO_number_read(BIO *bio) - the number of bytes processed 
1093         by BIO_read(bio,.).
1094 -       BIO_number_written(BIO *bio) - the number of bytes written 
1095         by BIO_write(bio,.).
1096 -       BIO_reset(BIO *bio) - 'reset' the BIO.
1097 -       BIO_eof(BIO *bio) - non zero if we are at the current end 
1098         of input.
1099 -       BIO_set_close(BIO *bio, int close_flag) - set the close flag.
1100 -       BIO_get_close(BIO *bio) - return the close flag.
1101         BIO_pending(BIO *bio) - return the number of bytes waiting 
1102         to be read (normally buffered internally).
1103 -       BIO_flush(BIO *bio) - output any data waiting to be output.
1104 -       BIO_should_retry(BIO *io) - after a BIO_read/BIO_write 
1105         operation returns 0 or -1, a call to this function will 
1106         return non zero if you should retry the call later (this 
1107         is for non-blocking IO).
1108 -       BIO_should_read(BIO *io) - we should retry when data can 
1109         be read.
1110 -       BIO_should_write(BIO *io) - we should retry when data can 
1111         be written.
1112 -       BIO_method_name(BIO *io) - return a string for the method name.
1113 -       BIO_method_type(BIO *io) - return the unique ID of the BIO method.
1114 -       BIO_set_callback(BIO *io,  long (*callback)(BIO *io, int 
1115         cmd, char *argp, int argi, long argl, long ret); - sets 
1116         the debug callback.
1117 -       BIO_get_callback(BIO *io) - return the assigned function 
1118         as mentioned above.
1119 -       BIO_set_callback_arg(BIO *io, char *arg)  - assign some 
1120         data against the BIO.  This is normally used by the debug 
1121         callback but could in reality be used for anything.  To 
1122         get an idea of how all this works, have a look at the code 
1123         in the default debug callback mentioned above.  The 
1124         callback can modify the return values.
1125
1126 Details of the BIO_METHOD structure.
1127 typedef struct bio_method_st
1128         {
1129         int type;
1130         char *name;
1131         int (*bwrite)();
1132         int (*bread)();
1133         int (*bputs)();
1134         int (*bgets)();
1135         long (*ctrl)();
1136         int (*create)();
1137         int (*destroy)();
1138         } BIO_METHOD;
1139
1140 The 'type' is the numeric type of the BIO, these are listed in buffer.h;
1141 'Name' is a textual representation of the BIO 'type'.
1142 The 7 function pointers point to the respective function 
1143 methods, some of which can be NULL if not implemented.
1144 The BIO structure
1145 typedef struct bio_st
1146         {
1147         BIO_METHOD *method;
1148         long (*callback)(BIO * bio, int mode, char *argp, int 
1149                 argi, long argl, long ret);
1150         char *cb_arg; /* first argument for the callback */
1151         int init;
1152         int shutdown;
1153         int flags;      /* extra storage */
1154         int num;
1155         char *ptr;
1156         struct bio_st *next_bio; /* used by filter BIOs */
1157         int references;
1158         unsigned long num_read;
1159         unsigned long num_write;
1160         } BIO;
1161
1162 -       'Method' is the BIO method.
1163 -       'callback', when configured, is called before and after 
1164         each BIO method is called for that particular BIO.  This 
1165         is intended primarily for debugging and of informational feedback.
1166 -       'init' is 0 when the BIO can be used for operation.  
1167         Often, after a BIO is created, a number of operations may 
1168         need to be performed before it is available for use.  An 
1169         example is for BIO_s_sock().  A socket needs to be 
1170         assigned to the BIO before it can be used.
1171 -       'shutdown', this flag indicates if the underlying 
1172         comunication primative being used should be closed/freed 
1173         when the BIO is closed.
1174 -       'flags' is used to hold extra state.  It is primarily used 
1175         to hold information about why a non-blocking operation 
1176         failed and to record startup protocol information for the 
1177         SSL BIO.
1178 -       'num' and 'ptr' are used to hold instance specific state 
1179         like file descriptors or local data structures.
1180 -       'next_bio' is used by filter BIOs to hold the pointer of the
1181         next BIO in the chain. written data is sent to this BIO and
1182         data read is taken from it.
1183 -       'references' is used to indicate the number of pointers to 
1184         this structure.  This needs to be '1' before a call to 
1185         BIO_free() is made if the BIO_free() function is to 
1186         actually free() the structure, otherwise the reference 
1187         count is just decreased.  The actual BIO subsystem does 
1188         not really use this functionality but it is useful when 
1189         used in more advanced applicaion.
1190 -       num_read and num_write are the total number of bytes 
1191         read/written via the 'read()' and 'write()' methods.
1192
1193 BIO_ctrl operations.
1194 The following is the list of standard commands passed as the 
1195 second parameter to BIO_ctrl() and should be supported by 
1196 all BIO as best as possible.  Some are optional, some are 
1197 manditory, in any case, where is makes sense, a filter BIO 
1198 should pass such requests to underlying BIO's.
1199 -       BIO_CTRL_RESET  - Reset the BIO back to an initial state.
1200 -       BIO_CTRL_EOF    - return 0 if we are not at the end of input, 
1201         non 0 if we are.
1202 -       BIO_CTRL_INFO   - BIO specific special command, normal
1203         information return.
1204 -       BIO_CTRL_SET    - set IO specific parameter.
1205 -       BIO_CTRL_GET    - get IO specific parameter.
1206 -       BIO_CTRL_GET_CLOSE - Get the close on BIO_free() flag, one 
1207         of BIO_CLOSE or BIO_NOCLOSE.
1208 -       BIO_CTRL_SET_CLOSE - Set the close on BIO_free() flag.
1209 -       BIO_CTRL_PENDING - Return the number of bytes available 
1210         for instant reading
1211 -       BIO_CTRL_FLUSH  - Output pending data, return number of bytes output.
1212 -       BIO_CTRL_SHOULD_RETRY - After an IO error (-1 returned) 
1213         should we 'retry' when IO is possible on the underlying IO object.
1214 -       BIO_CTRL_RETRY_TYPE - What kind of IO are we waiting on.
1215
1216 The following command is a special BIO_s_file() specific option.
1217 -       BIO_CTRL_SET_FILENAME - specify a file to open for IO.
1218
1219 The BIO_CTRL_RETRY_TYPE needs a little more explanation.  
1220 When performing non-blocking IO, or say reading on a memory 
1221 BIO, when no data is present (or cannot be written), 
1222 BIO_read() and/or BIO_write() will return -1.  
1223 BIO_should_retry(bio) will return true if this is due to an 
1224 IO condition rather than an actual error.  In the case of 
1225 BIO_s_mem(), a read when there is no data will return -1 and 
1226 a should retry when there is more 'read' data.
1227 The retry type is deduced from 2 macros
1228 BIO_should_read(bio) and BIO_should_write(bio).
1229 Now while it may appear obvious that a BIO_read() failure 
1230 should indicate that a retry should be performed when more 
1231 read data is available, this is often not true when using 
1232 things like an SSL BIO.  During the SSL protocol startup 
1233 multiple reads and writes are performed, triggered by any 
1234 SSL_read or SSL_write.
1235 So to write code that will transparently handle either a 
1236 socket or SSL BIO,
1237         i=BIO_read(bio,..)
1238         if (I == -1)
1239                 {
1240                 if (BIO_should_retry(bio))
1241                         {
1242                         if (BIO_should_read(bio))
1243                                 {
1244                                 /* call us again when BIO can be read */
1245                                 }
1246                         if (BIO_should_write(bio))
1247                                 {
1248                                 /* call us again when BIO can be written */
1249                                 }
1250                         }
1251                 }
1252
1253 At this point in time only read and write conditions can be 
1254 used but in the future I can see the situation for other 
1255 conditions, specifically with SSL there could be a condition 
1256 of a X509 certificate lookup taking place and so the non-
1257 blocking BIO_read would require a retry when the certificate 
1258 lookup subsystem has finished it's lookup.  This is all 
1259 makes more sense and is easy to use in a event loop type 
1260 setup.
1261 When using the SSL BIO, either SSL_read() or SSL_write()s 
1262 can be called during the protocol startup and things will 
1263 still work correctly.
1264 The nice aspect of the use of the BIO_should_retry() macro 
1265 is that all the errno codes that indicate a non-fatal error 
1266 are encapsulated in one place.  The Windows specific error 
1267 codes and WSAGetLastError() calls are also hidden from the 
1268 application.
1269
1270 Notes on each BIO method.
1271 Normally buffer.h is just required but depending on the 
1272 BIO_METHOD, ssl.h or evp.h will also be required.
1273
1274 BIO_METHOD *BIO_s_mem(void);
1275 -       BIO_set_mem_buf(BIO *bio, BUF_MEM *bm, int close_flag) - 
1276         set the underlying BUF_MEM structure for the BIO to use.
1277 -       BIO_get_mem_ptr(BIO *bio, char **pp) - if pp is not NULL, 
1278         set it to point to the memory array and return the number 
1279         of bytes available.
1280 A read/write BIO.  Any data written is appended to the 
1281 memory array and any read is read from the front.  This BIO 
1282 can be used for read/write at the same time. BIO_gets() is 
1283 supported in the fgets() sense.
1284 BIO_CTRL_INFO can be used to retrieve pointers to the memory 
1285 buffer and it's length.
1286
1287 BIO_METHOD *BIO_s_file(void);
1288 -       BIO_set_fp(BIO *bio, FILE *fp, int close_flag) - set 'FILE *' to use.
1289 -       BIO_get_fp(BIO *bio, FILE **fp) - get the 'FILE *' in use.
1290 -       BIO_read_filename(BIO *bio, char *name) - read from file.
1291 -       BIO_write_filename(BIO *bio, char *name) - write to file.
1292 -       BIO_append_filename(BIO *bio, char *name) - append to file.
1293 This BIO sits over the normal system fread()/fgets() type 
1294 functions. Gets() is supported.  This BIO in theory could be 
1295 used for read and write but it is best to think of each BIO 
1296 of this type as either a read or a write BIO, not both.
1297
1298 BIO_METHOD *BIO_s_socket(void);
1299 BIO_METHOD *BIO_s_fd(void);
1300 -       BIO_sock_should_retry(int i) - the underlying function 
1301         used to determine if a call should be retried; the 
1302         argument is the '0' or '-1' returned by the previous BIO 
1303         operation.
1304 -       BIO_fd_should_retry(int i) - same as the 
1305 -       BIO_sock_should_retry() except that it is different internally.
1306 -       BIO_set_fd(BIO *bio, int fd, int close_flag) - set the 
1307         file descriptor to use
1308 -       BIO_get_fd(BIO *bio, int *fd) - get the file descriptor.
1309 These two methods are very similar.  Gets() is not 
1310 supported, if you want this functionality, put a 
1311 BIO_f_buffer() onto it.  This BIO is bi-directional if the 
1312 underlying file descriptor is.  This is normally the case 
1313 for sockets but not the case for stdio descriptors.
1314
1315 BIO_METHOD *BIO_s_null(void);
1316 Read and write as much data as you like, it all disappears 
1317 into this BIO.
1318
1319 BIO_METHOD *BIO_f_buffer(void);
1320 -       BIO_get_buffer_num_lines(BIO *bio) - return the number of 
1321         complete lines in the buffer.
1322 -       BIO_set_buffer_size(BIO *bio, long size) - set the size of 
1323         the buffers.
1324 This type performs input and output buffering.  It performs 
1325 both at the same time.  The size of the buffer can be set 
1326 via the set buffer size option.  Data buffered for output is 
1327 only written when the buffer fills.
1328
1329 BIO_METHOD *BIO_f_ssl(void);
1330 -       BIO_set_ssl(BIO *bio, SSL *ssl, int close_flag) - the SSL 
1331         structure to use.
1332 -       BIO_get_ssl(BIO *bio, SSL **ssl) - get the SSL structure 
1333         in use.
1334 The SSL bio is a little different from normal BIOs because 
1335 the underlying SSL structure is a little different.  A SSL 
1336 structure performs IO via a read and write BIO.  These can 
1337 be different and are normally set via the
1338 SSL_set_rbio()/SSL_set_wbio() calls.  The SSL_set_fd() calls 
1339 are just wrappers that create socket BIOs and then call 
1340 SSL_set_bio() where the read and write BIOs are the same.  
1341 The BIO_push() operation makes the SSLs IO BIOs the same, so 
1342 make sure the BIO pushed is capable of two directional 
1343 traffic.  If it is not, you will have to install the BIOs 
1344 via the more conventional SSL_set_bio() call.  BIO_pop() will retrieve
1345 the 'SSL read' BIO.
1346
1347 BIO_METHOD *BIO_f_md(void);
1348 -       BIO_set_md(BIO *bio, EVP_MD *md) - set the message digest 
1349         to use.
1350 -       BIO_get_md(BIO *bio, EVP_MD **mdp) - return the digest 
1351         method in use in mdp, return 0 if not set yet.
1352 -       BIO_reset() reinitializes the digest (EVP_DigestInit()) 
1353         and passes the reset to the underlying BIOs.
1354 All data read or written via BIO_read() or BIO_write() to 
1355 this BIO will be added to the calculated digest.  This 
1356 implies that this BIO is only one directional.  If read and 
1357 write operations are performed, two separate BIO_f_md() BIOs 
1358 are reuqired to generate digests on both the input and the 
1359 output.  BIO_gets(BIO *bio, char *md, int size) will place the 
1360 generated digest into 'md' and return the number of bytes.  
1361 The EVP_MAX_MD_SIZE should probably be used to size the 'md' 
1362 array.  Reading the digest will also reset it.
1363
1364 BIO_METHOD *BIO_f_cipher(void);
1365 -       BIO_reset() reinitializes the cipher.
1366 -       BIO_flush() should be called when the last bytes have been 
1367         output to flush the final block of block ciphers.
1368 -       BIO_get_cipher_status(BIO *b), when called after the last 
1369         read from a cipher BIO, returns non-zero if the data 
1370         decrypted correctly, otherwise, 0.
1371 -       BIO_set_cipher(BIO *b, EVP_CIPHER *c, unsigned char *key, 
1372         unsigned char *iv, int encrypt)   This function is used to 
1373         setup a cipher BIO.  The length of key and iv are 
1374         specified by the choice of EVP_CIPHER.  Encrypt is 1 to 
1375         encrypt and 0 to decrypt.
1376
1377 BIO_METHOD *BIO_f_base64(void);
1378 -       BIO_flush() should be called when the last bytes have been output.
1379 This BIO base64 encodes when writing and base64 decodes when 
1380 reading.  It will scan the input until a suitable begin line 
1381 is found.  After reading data, BIO_reset() will reset the 
1382 BIO to start scanning again.  Do not mix reading and writing 
1383 on the same base64 BIO.  It is meant as a single stream BIO.
1384
1385 Directions      type
1386 both            BIO_s_mem()
1387 one/both        BIO_s_file()
1388 both            BIO_s_fd()
1389 both            BIO_s_socket() 
1390 both            BIO_s_null()
1391 both            BIO_f_buffer()
1392 one             BIO_f_md()  
1393 one             BIO_f_cipher()  
1394 one             BIO_f_base64()  
1395 both            BIO_f_ssl()
1396
1397 It is easy to mix one and two directional BIOs, all one has 
1398 to do is to keep two separate BIO pointers for reading and 
1399 writing and be careful about usage of underlying BIOs.  The 
1400 SSL bio by it's very nature has to be two directional but 
1401 the BIO_push() command will push the one BIO into the SSL 
1402 BIO for both reading and writing.
1403
1404 The best example program to look at is apps/enc.c and/or perhaps apps/dgst.c.
1405
1406
1407 ==== blowfish.doc ========================================================
1408
1409 The Blowfish library.
1410
1411 Blowfish is a block cipher that operates on 64bit (8 byte) quantities.  It
1412 uses variable size key, but 128bit (16 byte) key would normally be considered
1413 good.  It can be used in all the modes that DES can be used.  This
1414 library implements the ecb, cbc, cfb64, ofb64 modes.
1415
1416 Blowfish is quite a bit faster that DES, and much faster than IDEA or
1417 RC2.  It is one of the faster block ciphers.
1418
1419 For all calls that have an 'input' and 'output' variables, they can be the
1420 same.
1421
1422 This library requires the inclusion of 'blowfish.h'.
1423
1424 All of the encryption functions take what is called an BF_KEY as an 
1425 argument.  An BF_KEY is an expanded form of the Blowfish key.
1426 For all modes of the Blowfish algorithm, the BF_KEY used for
1427 decryption is the same one that was used for encryption.
1428
1429 The define BF_ENCRYPT is passed to specify encryption for the functions
1430 that require an encryption/decryption flag. BF_DECRYPT is passed to
1431 specify decryption.
1432
1433 Please note that any of the encryption modes specified in my DES library
1434 could be used with Blowfish.  I have only implemented ecb, cbc, cfb64 and
1435 ofb64 for the following reasons.
1436 - ecb is the basic Blowfish encryption.
1437 - cbc is the normal 'chaining' form for block ciphers.
1438 - cfb64 can be used to encrypt single characters, therefore input and output
1439   do not need to be a multiple of 8.
1440 - ofb64 is similar to cfb64 but is more like a stream cipher, not as
1441   secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
1442 - If you want triple Blowfish, thats 384 bits of key and you must be totally
1443   obsessed with security.  Still, if you want it, it is simple enough to
1444   copy the function from the DES library and change the des_encrypt to
1445   BF_encrypt; an exercise left for the paranoid reader :-).
1446
1447 The functions are as follows:
1448
1449 void BF_set_key(
1450 BF_KEY *ks;
1451 int len;
1452 unsigned char *key;
1453         BF_set_key converts an 'len' byte key into a BF_KEY.
1454         A 'ks' is an expanded form of the 'key' which is used to
1455         perform actual encryption.  It can be regenerated from the Blowfish key
1456         so it only needs to be kept when encryption or decryption is about
1457         to occur.  Don't save or pass around BF_KEY's since they
1458         are CPU architecture dependent, 'key's are not.  Blowfish is an
1459         interesting cipher in that it can be used with a variable length
1460         key.  'len' is the length of 'key' to be used as the key.
1461         A 'len' of 16 is recomended by me, but blowfish can use upto
1462         72 bytes.  As a warning, blowfish has a very very slow set_key
1463         function, it actually runs BF_encrypt 521 times.
1464         
1465 void BF_encrypt(unsigned long *data, BF_KEY *key);
1466 void BF_decrypt(unsigned long *data, BF_KEY *key);
1467         These are the Blowfish encryption function that gets called by just
1468         about every other Blowfish routine in the library.  You should not
1469         use this function except to implement 'modes' of Blowfish.
1470         I say this because the
1471         functions that call this routine do the conversion from 'char *' to
1472         long, and this needs to be done to make sure 'non-aligned' memory
1473         access do not occur.
1474         Data is a pointer to 2 unsigned long's and key is the
1475         BF_KEY to use. 
1476
1477 void BF_ecb_encrypt(
1478 unsigned char *in,
1479 unsigned char *out,
1480 BF_KEY *key,
1481 int encrypt);
1482         This is the basic Electronic Code Book form of Blowfish (in DES this
1483         mode is called Electronic Code Book so I'm going to use the term
1484         for blowfish as well.
1485         Input is encrypted into output using the key represented by
1486         key.  Depending on the encrypt, encryption or
1487         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
1488         
1489 void BF_cbc_encrypt(
1490 unsigned char *in,
1491 unsigned char *out,
1492 long length,
1493 BF_KEY *ks,
1494 unsigned char *ivec,
1495 int encrypt);
1496         This routine implements Blowfish in Cipher Block Chaining mode.
1497         Input, which should be a multiple of 8 bytes is encrypted
1498         (or decrypted) to output which will also be a multiple of 8 bytes.
1499         The number of bytes is in length (and from what I've said above,
1500         should be a multiple of 8).  If length is not a multiple of 8, bad 
1501         things will probably happen.  ivec is the initialisation vector.
1502         This function updates iv after each call so that it can be passed to
1503         the next call to BF_cbc_encrypt().
1504         
1505 void BF_cfb64_encrypt(
1506 unsigned char *in,
1507 unsigned char *out,
1508 long length,
1509 BF_KEY *schedule,
1510 unsigned char *ivec,
1511 int *num,
1512 int encrypt);
1513         This is one of the more useful functions in this Blowfish library, it
1514         implements CFB mode of Blowfish with 64bit feedback.
1515         This allows you to encrypt an arbitrary number of bytes,
1516         you do not require 8 byte padding.  Each call to this
1517         routine will encrypt the input bytes to output and then update ivec
1518         and num.  Num contains 'how far' we are though ivec.
1519         'Encrypt' is used to indicate encryption or decryption.
1520         CFB64 mode operates by using the cipher to generate a stream
1521         of bytes which is used to encrypt the plain text.
1522         The cipher text is then encrypted to generate the next 64 bits to
1523         be xored (incrementally) with the next 64 bits of plain
1524         text.  As can be seen from this, to encrypt or decrypt,
1525         the same 'cipher stream' needs to be generated but the way the next
1526         block of data is gathered for encryption is different for
1527         encryption and decryption.
1528         
1529 void BF_ofb64_encrypt(
1530 unsigned char *in,
1531 unsigned char *out,
1532 long length,
1533 BF_KEY *schedule,
1534 unsigned char *ivec,
1535 int *num);
1536         This functions implements OFB mode of Blowfish with 64bit feedback.
1537         This allows you to encrypt an arbitrary number of bytes,
1538         you do not require 8 byte padding.  Each call to this
1539         routine will encrypt the input bytes to output and then update ivec
1540         and num.  Num contains 'how far' we are though ivec.
1541         This is in effect a stream cipher, there is no encryption or
1542         decryption mode.
1543         
1544 For reading passwords, I suggest using des_read_pw_string() from my DES library.
1545 To generate a password from a text string, I suggest using MD5 (or MD2) to
1546 produce a 16 byte message digest that can then be passed directly to
1547 BF_set_key().
1548
1549 =====
1550 For more information about the specific Blowfish modes in this library
1551 (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
1552 documentation on my DES library.  What is said about DES is directly
1553 applicable for Blowfish.
1554
1555
1556 ==== bn.doc ========================================================
1557
1558 The Big Number library.
1559
1560 #include "bn.h" when using this library.
1561
1562 This big number library was written for use in implementing the RSA and DH
1563 public key encryption algorithms.  As such, features such as negative
1564 numbers have not been extensively tested but they should work as expected.
1565 This library uses dynamic memory allocation for storing its data structures
1566 and so there are no limit on the size of the numbers manipulated by these
1567 routines but there is always the requirement to check return codes from
1568 functions just in case a memory allocation error has occurred.
1569
1570 The basic object in this library is a BIGNUM.  It is used to hold a single
1571 large integer.  This type should be considered opaque and fields should not
1572 be modified or accessed directly.
1573 typedef struct bignum_st
1574         {
1575         int top;        /* Index of last used d. */
1576         BN_ULONG *d;    /* Pointer to an array of 'BITS2' bit chunks. */
1577         int max;        /* Size of the d array. */
1578         int neg;
1579         } BIGNUM;
1580 The big number is stored in a malloced array of BN_ULONG's.  A BN_ULONG can
1581 be either 16, 32 or 64 bits in size, depending on the 'number of  bits'
1582 specified in bn.h. 
1583 The 'd' field is this array.  'max' is the size of the 'd' array that has
1584 been allocated.  'top' is the 'last' entry being used, so for a value of 4,
1585 bn.d[0]=4 and bn.top=1.  'neg' is 1 if the number is negative.
1586 When a BIGNUM is '0', the 'd' field can be NULL and top == 0.
1587
1588 Various routines in this library require the use of 'temporary' BIGNUM
1589 variables during their execution.  Due to the use of dynamic memory
1590 allocation to create BIGNUMs being rather expensive when used in
1591 conjunction with repeated subroutine calls, the BN_CTX structure is
1592 used.  This structure contains BN_CTX BIGNUMs.  BN_CTX
1593 is the maximum number of temporary BIGNUMs any publicly exported 
1594 function will use.
1595
1596 #define BN_CTX  12
1597 typedef struct bignum_ctx
1598         {
1599         int tos;                        /* top of stack */
1600         BIGNUM *bn[BN_CTX];     /* The variables */
1601         } BN_CTX;
1602
1603 The functions that follow have been grouped according to function.  Most
1604 arithmetic functions return a result in the first argument, sometimes this
1605 first argument can also be an input parameter, sometimes it cannot.  These
1606 restrictions are documented.
1607
1608 extern BIGNUM *BN_value_one;
1609 There is one variable defined by this library, a BIGNUM which contains the
1610 number 1.  This variable is useful for use in comparisons and assignment.
1611
1612 Get Size functions.
1613
1614 int BN_num_bits(BIGNUM *a);
1615         This function returns the size of 'a' in bits.
1616         
1617 int BN_num_bytes(BIGNUM *a);
1618         This function (macro) returns the size of 'a' in bytes.
1619         For conversion of BIGNUMs to byte streams, this is the number of
1620         bytes the output string will occupy.  If the output byte
1621         format specifies that the 'top' bit indicates if the number is
1622         signed, so an extra '0' byte is required if the top bit on a
1623         positive number is being written, it is upto the application to
1624         make this adjustment.  Like I said at the start, I don't
1625         really support negative numbers :-).
1626
1627 Creation/Destruction routines.
1628
1629 BIGNUM *BN_new();
1630         Return a new BIGNUM object.  The number initially has a value of 0.  If
1631         there is an error, NULL is returned.
1632         
1633 void    BN_free(BIGNUM *a);
1634         Free()s a BIGNUM.
1635         
1636 void    BN_clear(BIGNUM *a);
1637         Sets 'a' to a value of 0 and also zeros all unused allocated
1638         memory.  This function is used to clear a variable of 'sensitive'
1639         data that was held in it.
1640         
1641 void    BN_clear_free(BIGNUM *a);
1642         This function zeros the memory used by 'a' and then free()'s it.
1643         This function should be used to BN_free() BIGNUMS that have held
1644         sensitive numeric values like RSA private key values.  Both this
1645         function and BN_clear tend to only be used by RSA and DH routines.
1646
1647 BN_CTX *BN_CTX_new(void);
1648         Returns a new BN_CTX.  NULL on error.
1649         
1650 void    BN_CTX_free(BN_CTX *c);
1651         Free a BN_CTX structure.  The BIGNUMs in 'c' are BN_clear_free()ed.
1652         
1653 BIGNUM *bn_expand(BIGNUM *b, int bits);
1654         This is an internal function that should not normally be used.  It
1655         ensures that 'b' has enough room for a 'bits' bit number.  It is
1656         mostly used by the various BIGNUM routines.  If there is an error,
1657         NULL is returned. if not, 'b' is returned.
1658         
1659 BIGNUM *BN_copy(BIGNUM *to, BIGNUM *from);
1660         The 'from' is copied into 'to'.  NULL is returned if there is an
1661         error, otherwise 'to' is returned.
1662
1663 BIGNUM *BN_dup(BIGNUM *a);
1664         A new BIGNUM is created and returned containing the value of 'a'.
1665         NULL is returned on error.
1666
1667 Comparison and Test Functions.
1668
1669 int BN_is_zero(BIGNUM *a)
1670         Return 1 if 'a' is zero, else 0.
1671
1672 int BN_is_one(a)
1673         Return 1 is 'a' is one, else 0.
1674
1675 int BN_is_word(a,w)
1676         Return 1 if 'a' == w, else 0.  'w' is a BN_ULONG.
1677
1678 int BN_cmp(BIGNUM *a, BIGNUM *b);
1679         Return -1 if 'a' is less than 'b', 0 if 'a' and 'b' are the same
1680         and 1 is 'a' is greater than 'b'.  This is a signed comparison.
1681         
1682 int BN_ucmp(BIGNUM *a, BIGNUM *b);
1683         This function is the same as BN_cmp except that the comparison
1684         ignores the sign of the numbers.
1685         
1686 Arithmetic Functions
1687 For all of these functions, 0 is returned if there is an error and 1 is
1688 returned for success.  The return value should always be checked.  eg.
1689 if (!BN_add(r,a,b)) goto err;
1690 Unless explicitly mentioned, the 'return' value can be one of the
1691 'parameters' to the function.
1692
1693 int BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1694         Add 'a' and 'b' and return the result in 'r'.  This is r=a+b.
1695         
1696 int BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1697         Subtract 'a' from 'b' and put the result in 'r'. This is r=a-b.
1698         
1699 int BN_lshift(BIGNUM *r, BIGNUM *a, int n);
1700         Shift 'a' left by 'n' bits.  This is r=a*(2^n).
1701         
1702 int BN_lshift1(BIGNUM *r, BIGNUM *a);
1703         Shift 'a' left by 1 bit.  This form is more efficient than
1704         BN_lshift(r,a,1).  This is r=a*2.
1705         
1706 int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
1707         Shift 'a' right by 'n' bits.  This is r=int(a/(2^n)).
1708         
1709 int BN_rshift1(BIGNUM *r, BIGNUM *a);
1710         Shift 'a' right by 1 bit.  This form is more efficient than
1711         BN_rshift(r,a,1).  This is r=int(a/2).
1712         
1713 int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1714         Multiply a by b and return the result in 'r'. 'r' must not be
1715         either 'a' or 'b'.  It has to be a different BIGNUM.
1716         This is r=a*b.
1717
1718 int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
1719         Multiply a by a and return the result in 'r'. 'r' must not be
1720         'a'.  This function is alot faster than BN_mul(r,a,a).  This is r=a*a.
1721
1722 int BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
1723         Divide 'm' by 'd' and return the result in 'dv' and the remainder
1724         in 'rem'.  Either of 'dv' or 'rem' can be NULL in which case that
1725         value is not returned.  'ctx' needs to be passed as a source of
1726         temporary BIGNUM variables.
1727         This is dv=int(m/d), rem=m%d.
1728         
1729 int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
1730         Find the remainder of 'm' divided by 'd' and return it in 'rem'.
1731         'ctx' holds the temporary BIGNUMs required by this function.
1732         This function is more efficient than BN_div(NULL,rem,m,d,ctx);
1733         This is rem=m%d.
1734
1735 int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *m,BN_CTX *ctx);
1736         Multiply 'a' by 'b' and return the remainder when divided by 'm'.
1737         'ctx' holds the temporary BIGNUMs required by this function.
1738         This is r=(a*b)%m.
1739
1740 int BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx);
1741         Raise 'a' to the 'p' power and return the remainder when divided by
1742         'm'.  'ctx' holds the temporary BIGNUMs required by this function.
1743         This is r=(a^p)%m.
1744
1745 int BN_reciprocal(BIGNUM *r, BIGNUM *m, BN_CTX *ctx);
1746         Return the reciprocal of 'm'.  'ctx' holds the temporary variables
1747         required.  This function returns -1 on error, otherwise it returns
1748         the number of bits 'r' is shifted left to make 'r' into an integer.
1749         This number of bits shifted is required in BN_mod_mul_reciprocal().
1750         This is r=(1/m)<<(BN_num_bits(m)+1).
1751         
1752 int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *x, BIGNUM *y, BIGNUM *m, 
1753         BIGNUM *i, int nb, BN_CTX *ctx);
1754         This function is used to perform an efficient BN_mod_mul()
1755         operation.  If one is going to repeatedly perform BN_mod_mul() with
1756         the same modulus is worth calculating the reciprocal of the modulus
1757         and then using this function.  This operation uses the fact that
1758         a/b == a*r where r is the reciprocal of b.  On modern computers
1759         multiplication is very fast and big number division is very slow.
1760         'x' is multiplied by 'y' and then divided by 'm' and the remainder
1761         is returned.  'i' is the reciprocal of 'm' and 'nb' is the number
1762         of bits as returned from BN_reciprocal().  Normal usage is as follows.
1763         bn=BN_reciprocal(i,m);
1764         for (...)
1765                 { BN_mod_mul_reciprocal(r,x,y,m,i,bn,ctx); }
1766         This is r=(x*y)%m.  Internally it is approximately
1767         r=(x*y)-m*(x*y/m) or r=(x*y)-m*((x*y*i) >> bn)
1768         This function is used in BN_mod_exp() and BN_is_prime().
1769
1770 Assignment Operations
1771
1772 int BN_one(BIGNUM *a)
1773         Set 'a' to hold the value one.
1774         This is a=1.
1775         
1776 int BN_zero(BIGNUM *a)
1777         Set 'a' to hold the value zero.
1778         This is a=0.
1779         
1780 int BN_set_word(BIGNUM *a, unsigned long w);
1781         Set 'a' to hold the value of 'w'.  'w' is an unsigned long.
1782         This is a=w.
1783
1784 unsigned long BN_get_word(BIGNUM *a);
1785         Returns 'a' in an unsigned long.  Not remarkably, often 'a' will
1786         be biger than a word, in which case 0xffffffffL is returned.
1787
1788 Word Operations
1789 These functions are much more efficient that the normal bignum arithmetic
1790 operations.
1791
1792 BN_ULONG BN_mod_word(BIGNUM *a, unsigned long w);
1793         Return the remainder of 'a' divided by 'w'.
1794         This is return(a%w).
1795         
1796 int BN_add_word(BIGNUM *a, unsigned long w);
1797         Add 'w' to 'a'.  This function does not take the sign of 'a' into
1798         account.  This is a+=w;
1799         
1800 Bit operations.
1801
1802 int BN_is_bit_set(BIGNUM *a, int n);
1803         This function return 1 if bit 'n' is set in 'a' else 0.
1804
1805 int BN_set_bit(BIGNUM *a, int n);
1806         This function sets bit 'n' to 1 in 'a'. 
1807         This is a&= ~(1<<n);
1808
1809 int BN_clear_bit(BIGNUM *a, int n);
1810         This function sets bit 'n' to zero in 'a'.  Return 0 if less
1811         than 'n' bits in 'a' else 1.  This is a&= ~(1<<n);
1812
1813 int BN_mask_bits(BIGNUM *a, int n);
1814         Truncate 'a' to n bits long.  This is a&= ~((~0)<<n)
1815
1816 Format conversion routines.
1817
1818 BIGNUM *BN_bin2bn(unsigned char *s, int len,BIGNUM *ret);
1819         This function converts 'len' bytes in 's' into a BIGNUM which
1820         is put in 'ret'.  If ret is NULL, a new BIGNUM is created.
1821         Either this new BIGNUM or ret is returned.  The number is
1822         assumed to be in bigendian form in 's'.  By this I mean that
1823         to 'ret' is created as follows for 'len' == 5.
1824         ret = s[0]*2^32 + s[1]*2^24 + s[2]*2^16 + s[3]*2^8 + s[4];
1825         This function cannot be used to convert negative numbers.  It
1826         is always assumed the number is positive.  The application
1827         needs to diddle the 'neg' field of th BIGNUM its self.
1828         The better solution would be to save the numbers in ASN.1 format
1829         since this is a defined standard for storing big numbers.
1830         Look at the functions
1831
1832         ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
1833         BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
1834         int i2d_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp);
1835         ASN1_INTEGER *d2i_ASN1_INTEGER(ASN1_INTEGER **a,unsigned char **pp,
1836                 long length;
1837
1838 int BN_bn2bin(BIGNUM *a, unsigned char *to);
1839         This function converts 'a' to a byte string which is put into
1840         'to'.  The representation is big-endian in that the most
1841         significant byte of 'a' is put into to[0].  This function
1842         returns the number of bytes used to hold 'a'.  BN_num_bytes(a)
1843         would return the same value and can be used to determine how
1844         large 'to' needs to be.  If the number is negative, this
1845         information is lost.  Since this library was written to
1846         manipulate large positive integers, the inability to save and
1847         restore them is not considered to be a problem by me :-).
1848         As for BN_bin2bn(), look at the ASN.1 integer encoding funtions
1849         for SSLeay.  They use BN_bin2bn() and BN_bn2bin() internally.
1850         
1851 char *BN_bn2ascii(BIGNUM *a);
1852         This function returns a malloc()ed string that contains the
1853         ascii hexadecimal encoding of 'a'.  The number is in bigendian
1854         format with a '-' in front if the number is negative.
1855
1856 int BN_ascii2bn(BIGNUM **bn, char *a);
1857         The inverse of BN_bn2ascii.  The function returns the number of
1858         characters from 'a' were processed in generating a the bignum.
1859         error is inticated by 0 being returned.  The number is a
1860         hex digit string, optionally with a leading '-'.  If *bn
1861         is null, a BIGNUM is created and returned via that variable.
1862         
1863 int BN_print_fp(FILE *fp, BIGNUM *a);
1864         'a' is printed to file pointer 'fp'.  It is in the same format
1865         that is output from BN_bn2ascii().  0 is returned on error,
1866         1 if things are ok.
1867
1868 int BN_print(BIO *bp, BIGNUM *a);
1869         Same as BN_print except that the output is done to the SSLeay libraries
1870         BIO routines.  BN_print_fp() actually calls this function.
1871
1872 Miscellaneous Routines.
1873
1874 int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
1875         This function returns in 'rnd' a random BIGNUM that is bits
1876         long.  If bottom is 1, the number returned is odd.  If top is set,
1877         the top 2 bits of the number are set.  This is useful because if
1878         this is set, 2 'n; bit numbers multiplied together will return a 2n
1879         bit number.  If top was not set, they could produce a 2n-1 bit
1880         number.
1881
1882 BIGNUM *BN_mod_inverse(BIGNUM *a, BIGNUM *n,BN_CTX *ctx);
1883         This function create a new BIGNUM and returns it.  This number
1884         is the inverse mod 'n' of 'a'.  By this it is meant that the
1885         returned value 'r' satisfies (a*r)%n == 1.  This function is
1886         used in the generation of RSA keys.  'ctx', as per usual,
1887         is used to hold temporary variables that are required by the
1888         function.  NULL is returned on error.
1889
1890 int BN_gcd(BIGNUM *r,BIGNUM *a,BIGNUM *b,BN_CTX *ctx);
1891         'r' has the greatest common divisor of 'a' and 'b'.  'ctx' is
1892         used for temporary variables and 0 is returned on error.
1893
1894 int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(),BN_CTX *ctx,
1895         char *cb_arg);
1896         This function is used to check if a BIGNUM ('p') is prime.
1897         It performs this test by using the Miller-Rabin randomised
1898         primality test.  This is a probalistic test that requires a
1899         number of rounds to ensure the number is prime to a high
1900         degree of probability.  Since this can take quite some time, a
1901         callback function can be passed and it will be called each
1902         time 'p' passes a round of the prime testing.  'callback' will
1903         be called as follows, callback(1,n,cb_arg) where n is the number of
1904         the round, just passed.  As per usual 'ctx' contains temporary
1905         variables used.  If ctx is NULL, it does not matter, a local version
1906         will be malloced.  This parameter is present to save some mallocing
1907         inside the function but probably could be removed.
1908         0 is returned on error.
1909         'ncheck' is the number of Miller-Rabin tests to run.  It is
1910         suggested to use the value 'BN_prime_checks' by default.
1911
1912 BIGNUM *BN_generate_prime(
1913 int bits,
1914 int strong,
1915 BIGNUM *a,
1916 BIGNUM *rems,
1917 void (*callback)());
1918 char *cb_arg
1919         This function is used to generate prime numbers.  It returns a
1920         new BIGNUM that has a high probability of being a prime.
1921         'bits' is the number of bits that
1922         are to be in the prime.  If 'strong' is true, the returned prime
1923         will also be a strong prime ((p-1)/2 is also prime).
1924         While searching for the prime ('p'), we
1925         can add the requirement that the prime fill the following
1926         condition p%a == rem.  This can be used to help search for
1927         primes with specific features, which is required when looking
1928         for primes suitable for use with certain 'g' values in the
1929         Diffie-Hellman key exchange algorithm.  If 'a' is NULL,
1930         this condition is not checked.  If rem is NULL, rem is assumed
1931         to be 1.  Since this search for a prime
1932         can take quite some time, if callback is not NULL, it is called
1933         in the following situations.
1934         We have a suspected prime (from a quick sieve),
1935         callback(0,sus_prime++,cb_arg). Each item to be passed to BN_is_prime().
1936         callback(1,round++,cb_arg).  Each successful 'round' in BN_is_prime().
1937         callback(2,round,cb_arg). For each successful BN_is_prime() test.
1938
1939 Hints
1940 -----
1941
1942 DSA wants 64*32 to use word mont mul, but RSA wants to use full.
1943
1944 ==== callback.doc ========================================================
1945
1946 Callback functions used in SSLeay.
1947
1948 --------------------------
1949 The BIO library.  
1950
1951 Each BIO structure can have a callback defined against it.  This callback is
1952 called 2 times for each BIO 'function'.  It is passed 6 parameters.
1953 BIO_debug_callback() is an example callback which is defined in
1954 crypto/buffer/bio_cb.c and is used in apps/dgst.c  This is intended mostly
1955 for debuging or to notify the application of IO.
1956
1957 long BIO_debug_callback(BIO *bio,int cmd,char *argp,int argi,long argl,
1958         long ret);
1959 bio is the BIO being called, cmd is the type of BIO function being called.
1960 Look at the BIO_CB_* defines in buffer.h.  Argp and argi are the arguments
1961 passed to BIO_read(), BIO_write, BIO_gets(), BIO_puts().  In the case of
1962 BIO_ctrl(), argl is also defined.  The first time the callback is called,
1963 before the underlying function has been executed, 0 is passed as 'ret', and
1964 if the return code from the callback is not > 0, the call is aborted
1965 and the returned <= 0 value is returned.
1966 The second time the callback is called, the 'cmd' value also has
1967 BIO_CB_RETURN logically 'or'ed with it.  The 'ret' value is the value returned
1968 from the actuall function call and whatever the callback returns is returned
1969 from the BIO function.
1970
1971 BIO_set_callback(b,cb) can be used to set the callback function
1972 (b is a BIO), and BIO_set_callback_arg(b,arg) can be used to
1973 set the cb_arg argument in the BIO strucutre.  This field is only intended
1974 to be used by application, primarily in the callback function since it is
1975 accessable since the BIO is passed.
1976
1977 --------------------------
1978 The PEM library.
1979
1980 The pem library only really uses one type of callback,
1981 static int def_callback(char *buf, int num, int verify);
1982 which is used to return a password string if required.
1983 'buf' is the buffer to put the string in.  'num' is the size of 'buf'
1984 and 'verify' is used to indicate that the password should be checked.
1985 This last flag is mostly used when reading a password for encryption.
1986
1987 For all of these functions, a NULL callback will call the above mentioned
1988 default callback.  This default function does not work under Windows 3.1.
1989 For other machines, it will use an application defined prompt string
1990 (EVP_set_pw_prompt(), which defines a library wide prompt string)
1991 if defined, otherwise it will use it's own PEM password prompt.
1992 It will then call EVP_read_pw_string() to get a password from the console.
1993 If your application wishes to use nice fancy windows to retrieve passwords,
1994 replace this function.  The callback should return the number of bytes read
1995 into 'buf'.  If the number of bytes <= 0, it is considered an error.
1996
1997 Functions that take this callback are listed below.  For the 'read' type
1998 functions, the callback will only be required if the PEM data is encrypted.
1999
2000 For the Write functions, normally a password can be passed in 'kstr', of
2001 'klen' bytes which will be used if the 'enc' cipher is not NULL.  If
2002 'kstr' is NULL, the callback will be used to retrieve a password.
2003
2004 int PEM_do_header (EVP_CIPHER_INFO *cipher, unsigned char *data,long *len,
2005         int (*callback)());
2006 char *PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *bp,char **x,int (*cb)());
2007 char *PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
2008 int PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *bp,char *x,
2009         EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
2010 int PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,
2011         EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
2012 STACK *PEM_X509_INFO_read(FILE *fp, STACK *sk, int (*cb)());
2013 STACK *PEM_X509_INFO_read_bio(BIO *fp, STACK *sk, int (*cb)());
2014
2015 #define PEM_write_RSAPrivateKey(fp,x,enc,kstr,klen,cb)
2016 #define PEM_write_DSAPrivateKey(fp,x,enc,kstr,klen,cb)
2017 #define PEM_write_bio_RSAPrivateKey(bp,x,enc,kstr,klen,cb)
2018 #define PEM_write_bio_DSAPrivateKey(bp,x,enc,kstr,klen,cb)
2019 #define PEM_read_SSL_SESSION(fp,x,cb)
2020 #define PEM_read_X509(fp,x,cb)
2021 #define PEM_read_X509_REQ(fp,x,cb)
2022 #define PEM_read_X509_CRL(fp,x,cb)
2023 #define PEM_read_RSAPrivateKey(fp,x,cb)
2024 #define PEM_read_DSAPrivateKey(fp,x,cb)
2025 #define PEM_read_PrivateKey(fp,x,cb)
2026 #define PEM_read_PKCS7(fp,x,cb)
2027 #define PEM_read_DHparams(fp,x,cb)
2028 #define PEM_read_bio_SSL_SESSION(bp,x,cb)
2029 #define PEM_read_bio_X509(bp,x,cb)
2030 #define PEM_read_bio_X509_REQ(bp,x,cb)
2031 #define PEM_read_bio_X509_CRL(bp,x,cb)
2032 #define PEM_read_bio_RSAPrivateKey(bp,x,cb)
2033 #define PEM_read_bio_DSAPrivateKey(bp,x,cb)
2034 #define PEM_read_bio_PrivateKey(bp,x,cb)
2035 #define PEM_read_bio_PKCS7(bp,x,cb)
2036 #define PEM_read_bio_DHparams(bp,x,cb)
2037 int i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
2038 RSA *d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
2039
2040 Now you will notice that macros like
2041 #define PEM_write_X509(fp,x) \
2042                 PEM_ASN1_write((int (*)())i2d_X509,PEM_STRING_X509,fp, \
2043                                         (char *)x, NULL,NULL,0,NULL)
2044 Don't do encryption normally.  If you want to PEM encrypt your X509 structure,
2045 either just call PEM_ASN1_write directly or just define you own
2046 macro variant.  As you can see, this macro just sets all encryption related
2047 parameters to NULL.
2048
2049
2050 --------------------------
2051 The SSL library.
2052
2053 #define SSL_set_info_callback(ssl,cb)
2054 #define SSL_CTX_set_info_callback(ctx,cb)
2055 void callback(SSL *ssl,int location,int ret)
2056 This callback is called each time around the SSL_connect()/SSL_accept() 
2057 state machine.  So it will be called each time the SSL protocol progresses.
2058 It is mostly present for use when debugging.  When SSL_connect() or
2059 SSL_accept() return, the location flag is SSL_CB_ACCEPT_EXIT or
2060 SSL_CB_CONNECT_EXIT and 'ret' is the value about to be returned.
2061 Have a look at the SSL_CB_* defines in ssl.h.  If an info callback is defined
2062 against the SSL_CTX, it is called unless there is one set against the SSL.
2063 Have a look at
2064 void client_info_callback() in apps/s_client() for an example.
2065
2066 Certificate verification.
2067 void SSL_set_verify(SSL *s, int mode, int (*callback) ());
2068 void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*callback)());
2069 This callback is used to help verify client and server X509 certificates.
2070 It is actually passed to X509_cert_verify(), along with the SSL structure
2071 so you have to read about X509_cert_verify() :-).  The SSL_CTX version is used
2072 if the SSL version is not defined.  X509_cert_verify() is the function used
2073 by the SSL part of the library to verify certificates.  This function is
2074 nearly always defined by the application.
2075
2076 void SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx, int (*cb)(),char *arg);
2077 int callback(char *arg,SSL *s,X509 *xs,STACK *cert_chain);
2078 This call is used to replace the SSLeay certificate verification code.
2079 The 'arg' is kept in the SSL_CTX and is passed to the callback.
2080 If the callback returns 0, the certificate is rejected, otherwise it
2081 is accepted.  The callback is replacing the X509_cert_verify() call.
2082 This feature is not often used, but if you wished to implement
2083 some totally different certificate authentication system, this 'hook' is
2084 vital.
2085
2086 SSLeay keeps a cache of session-ids against each SSL_CTX.  These callbacks can
2087 be used to notify the application when a SSL_SESSION is added to the cache
2088 or to retrieve a SSL_SESSION that is not in the cache from the application.
2089 #define SSL_CTX_sess_set_get_cb(ctx,cb)
2090 SSL_SESSION *callback(SSL *s,char *session_id,int session_id_len,int *copy);
2091 If defined, this callback is called to return the SESSION_ID for the
2092 session-id in 'session_id', of 'session_id_len' bytes.  'copy' is set to 1
2093 if the server is to 'take a copy' of the SSL_SESSION structure.  It is 0
2094 if the SSL_SESSION is being 'passed in' so the SSLeay library is now
2095 responsible for 'free()ing' the structure.  Basically it is used to indicate
2096 if the reference count on the SSL_SESSION structure needs to be incremented.
2097
2098 #define SSL_CTX_sess_set_new_cb(ctx,cb)
2099 int callback(SSL *s, SSL_SESSION *sess);
2100 When a new connection is established, if the SSL_SESSION is going to be added
2101 to the cache, this callback is called.  Return 1 if a 'copy' is required,
2102 otherwise, return 0.  This return value just causes the reference count
2103 to be incremented (on return of a 1), this means the application does
2104 not need to worry about incrementing the refernece count (and the
2105 locking that implies in a multi-threaded application).
2106
2107 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)());
2108 This sets the SSL password reading function.
2109 It is mostly used for windowing applications
2110 and used by PEM_read_bio_X509() and PEM_read_bio_RSAPrivateKey()
2111 calls inside the SSL library.   The only reason this is present is because the
2112 calls to PEM_* functions is hidden in the SSLeay library so you have to
2113 pass in the callback some how.
2114
2115 #define SSL_CTX_set_client_cert_cb(ctx,cb)
2116 int callback(SSL *s,X509 **x509, EVP_PKEY **pkey);
2117 Called when a client certificate is requested but there is not one set
2118 against the SSL_CTX or the SSL.  If the callback returns 1, x509 and
2119 pkey need to point to valid data.  The library will free these when
2120 required so if the application wants to keep these around, increment
2121 their reference counts.  If 0 is returned, no client cert is
2122 available.  If -1 is returned, it is assumed that the callback needs
2123 to be called again at a later point in time.  SSL_connect will return
2124 -1 and SSL_want_x509_lookup(ssl) returns true.  Remember that
2125 application data can be attached to an SSL structure via the
2126 SSL_set_app_data(SSL *ssl,char *data) call.
2127
2128 --------------------------
2129 The X509 library.
2130
2131 int X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)(),
2132         int *error,char *arg,STACK *cert_chain);
2133 int verify_callback(int ok,X509 *xs,X509 *xi,int depth,int error,char *arg,
2134         STACK *cert_chain);
2135
2136 X509_cert_verify() is used to authenticate X509 certificates.  The 'ctx' holds
2137 the details of the various caches and files used to locate certificates.
2138 'xs' is the certificate to verify and 'cb' is the application callback (more
2139 detail later).  'error' will be set to the error code and 'arg' is passed
2140 to the 'cb' callback.  Look at the VERIFY_* defines in crypto/x509/x509.h
2141
2142 When ever X509_cert_verify() makes a 'negative' decision about a
2143 certitificate, the callback is called.  If everything checks out, the
2144 callback is called with 'VERIFY_OK' or 'VERIFY_ROOT_OK' (for a self
2145 signed cert that is not the passed certificate).
2146
2147 The callback is passed the X509_cert_verify opinion of the certificate 
2148 in 'ok', the certificate in 'xs', the issuer certificate in 'xi',
2149 the 'depth' of the certificate in the verification 'chain', the
2150 VERIFY_* code in 'error' and the argument passed to X509_cert_verify()
2151 in 'arg'. cert_chain is a list of extra certs to use if they are not
2152 in the cache.
2153
2154 The callback can be used to look at the error reason, and then return 0
2155 for an 'error' or '1' for ok.  This will override the X509_cert_verify()
2156 opinion of the certificates validity.  Processing will continue depending on
2157 the return value.  If one just wishes to use the callback for informational
2158 reason, just return the 'ok' parameter.
2159
2160 --------------------------
2161 The BN and DH library.
2162
2163 BIGNUM *BN_generate_prime(int bits,int strong,BIGNUM *add,
2164         BIGNUM *rem,void (*callback)(int,int));
2165 int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(int,int),
2166
2167 Read doc/bn.doc for the description of these 2.
2168
2169 DH *DH_generate_parameters(int prime_len,int generator,
2170         void (*callback)(int,int));
2171 Read doc/bn.doc for the description of the callback, since it is just passed
2172 to BN_generate_prime(), except that it is also called as
2173 callback(3,0) by this function.
2174
2175 --------------------------
2176 The CRYPTO library.
2177
2178 void CRYPTO_set_locking_callback(void (*func)(int mode,int type,char *file,
2179         int line));
2180 void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,
2181         int type,char *file, int line));
2182 void CRYPTO_set_id_callback(unsigned long (*func)(void));
2183
2184 Read threads.doc for info on these ones.
2185
2186
2187 ==== cipher.doc ========================================================
2188
2189 The Cipher subroutines.
2190
2191 These routines require "evp.h" to be included.
2192
2193 These functions are a higher level interface to the various cipher
2194 routines found in this library.  As such, they allow the same code to be
2195 used to encrypt and decrypt via different ciphers with only a change
2196 in an initial parameter.  These routines also provide buffering for block
2197 ciphers.
2198
2199 These routines all take a pointer to the following structure to specify
2200 which cipher to use.  If you wish to use a new cipher with these routines,
2201 you would probably be best off looking an how an existing cipher is
2202 implemented and copying it.  At this point in time, I'm not going to go
2203 into many details.  This structure should be considered opaque
2204
2205 typedef struct pem_cipher_st
2206         {
2207         int type;
2208         int block_size;
2209         int key_len;
2210         int iv_len;
2211         void (*enc_init)();     /* init for encryption */
2212         void (*dec_init)();     /* init for decryption */
2213         void (*do_cipher)();    /* encrypt data */
2214         } EVP_CIPHER;
2215         
2216 The type field is the object NID of the cipher type
2217 (read the section on Objects for an explanation of what a NID is).
2218 The cipher block_size is how many bytes need to be passed
2219 to the cipher at a time.  Key_len is the
2220 length of the key the cipher requires and iv_len is the length of the
2221 initialisation vector required.  enc_init is the function
2222 called to initialise the ciphers context for encryption and dec_init is the
2223 function to initialise for decryption (they need to be different, especially
2224 for the IDEA cipher).
2225
2226 One reason for specifying the Cipher via a pointer to a structure
2227 is that if you only use des-cbc, only the des-cbc routines will
2228 be included when you link the program.  If you passed an integer
2229 that specified which cipher to use, the routine that mapped that
2230 integer to a set of cipher functions would cause all the ciphers
2231 to be link into the code.  This setup also allows new ciphers
2232 to be added by the application (with some restrictions).
2233
2234 The thirteen ciphers currently defined in this library are
2235
2236 EVP_CIPHER *EVP_des_ecb();     /* DES in ecb mode,     iv=0, block=8, key= 8 */
2237 EVP_CIPHER *EVP_des_ede();     /* DES in ecb ede mode, iv=0, block=8, key=16 */
2238 EVP_CIPHER *EVP_des_ede3();    /* DES in ecb ede mode, iv=0, block=8, key=24 */
2239 EVP_CIPHER *EVP_des_cfb();     /* DES in cfb mode,     iv=8, block=1, key= 8 */
2240 EVP_CIPHER *EVP_des_ede_cfb(); /* DES in ede cfb mode, iv=8, block=1, key=16 */
2241 EVP_CIPHER *EVP_des_ede3_cfb();/* DES in ede cfb mode, iv=8, block=1, key=24 */
2242 EVP_CIPHER *EVP_des_ofb();     /* DES in ofb mode,     iv=8, block=1, key= 8 */
2243 EVP_CIPHER *EVP_des_ede_ofb(); /* DES in ede ofb mode, iv=8, block=1, key=16 */
2244 EVP_CIPHER *EVP_des_ede3_ofb();/* DES in ede ofb mode, iv=8, block=1, key=24 */
2245 EVP_CIPHER *EVP_des_cbc();     /* DES in cbc mode,     iv=8, block=8, key= 8 */
2246 EVP_CIPHER *EVP_des_ede_cbc(); /* DES in cbc ede mode, iv=8, block=8, key=16 */
2247 EVP_CIPHER *EVP_des_ede3_cbc();/* DES in cbc ede mode, iv=8, block=8, key=24 */
2248 EVP_CIPHER *EVP_desx_cbc();    /* DES in desx cbc mode,iv=8, block=8, key=24 */
2249 EVP_CIPHER *EVP_rc4();         /* RC4,                 iv=0, block=1, key=16 */
2250 EVP_CIPHER *EVP_idea_ecb();    /* IDEA in ecb mode,    iv=0, block=8, key=16 */
2251 EVP_CIPHER *EVP_idea_cfb();    /* IDEA in cfb mode,    iv=8, block=1, key=16 */
2252 EVP_CIPHER *EVP_idea_ofb();    /* IDEA in ofb mode,    iv=8, block=1, key=16 */
2253 EVP_CIPHER *EVP_idea_cbc();    /* IDEA in cbc mode,    iv=8, block=8, key=16 */
2254 EVP_CIPHER *EVP_rc2_ecb();     /* RC2 in ecb mode,     iv=0, block=8, key=16 */
2255 EVP_CIPHER *EVP_rc2_cfb();     /* RC2 in cfb mode,     iv=8, block=1, key=16 */
2256 EVP_CIPHER *EVP_rc2_ofb();     /* RC2 in ofb mode,     iv=8, block=1, key=16 */
2257 EVP_CIPHER *EVP_rc2_cbc();     /* RC2 in cbc mode,     iv=8, block=8, key=16 */
2258 EVP_CIPHER *EVP_bf_ecb();      /* Blowfish in ecb mode,iv=0, block=8, key=16 */
2259 EVP_CIPHER *EVP_bf_cfb();      /* Blowfish in cfb mode,iv=8, block=1, key=16 */
2260 EVP_CIPHER *EVP_bf_ofb();      /* Blowfish in ofb mode,iv=8, block=1, key=16 */
2261 EVP_CIPHER *EVP_bf_cbc();      /* Blowfish in cbc mode,iv=8, block=8, key=16 */
2262
2263 The meaning of the compound names is as follows.
2264 des     The base cipher is DES.
2265 idea    The base cipher is IDEA
2266 rc4     The base cipher is RC4-128
2267 rc2     The base cipher is RC2-128
2268 ecb     Electronic Code Book form of the cipher.
2269 cbc     Cipher Block Chaining form of the cipher.
2270 cfb     64 bit Cipher Feedback form of the cipher.
2271 ofb     64 bit Output Feedback form of the cipher.
2272 ede     The cipher is used in Encrypt, Decrypt, Encrypt mode.  The first
2273         and last keys are the same.
2274 ede3    The cipher is used in Encrypt, Decrypt, Encrypt mode.
2275
2276 All the Cipher routines take a EVP_CIPHER_CTX pointer as an argument.
2277 The state of the cipher is kept in this structure.
2278
2279 typedef struct EVP_CIPHER_Ctx_st
2280         {
2281         EVP_CIPHER *cipher;
2282         int encrypt;            /* encrypt or decrypt */
2283         int buf_len;            /* number we have left */
2284         unsigned char buf[8];
2285         union   {
2286                 .... /* cipher specific stuff */
2287                 } c;
2288         } EVP_CIPHER_CTX;
2289
2290 Cipher is a pointer the the EVP_CIPHER for the current context.  The encrypt
2291 flag indicates encryption or decryption.  buf_len is the number of bytes
2292 currently being held in buf.
2293 The 'c' union holds the cipher specify context.
2294
2295 The following functions are to be used.
2296
2297 int EVP_read_pw_string(
2298 char *buf,
2299 int len,
2300 char *prompt,
2301 int verify,
2302         This function is the same as des_read_pw_string() (des.doc).
2303
2304 void EVP_set_pw_prompt(char *prompt);
2305         This function sets the 'default' prompt to use to use in
2306         EVP_read_pw_string when the prompt parameter is NULL.  If the
2307         prompt parameter is NULL, this 'default prompt' feature is turned
2308         off.  Be warned, this is a global variable so weird things
2309         will happen if it is used under Win16 and care must be taken
2310         with a multi-threaded version of the library.
2311
2312 char *EVP_get_pw_prompt();
2313         This returns a pointer to the default prompt string.  NULL
2314         if it is not set.
2315
2316 int EVP_BytesToKey(
2317 EVP_CIPHER *type,
2318 EVP_MD *md,
2319 unsigned char *salt,
2320 unsigned char *data,
2321 int datal,
2322 int count,
2323 unsigned char *key,
2324 unsigned char *iv);
2325         This function is used to generate a key and an initialisation vector
2326         for a specified cipher from a key string and a salt.  Type
2327         specifies the cipher the 'key' is being generated for.  Md is the
2328         message digest algorithm to use to generate the key and iv.  The salt
2329         is an optional 8 byte object that is used to help seed the key
2330         generator.
2331         If the salt value is NULL, it is just not used.  Datal is the
2332         number of bytes to use from 'data' in the key generation.  
2333         This function returns the key size for the specified cipher, if
2334         data is NULL, this value is returns and no other
2335         computation is performed.  Count is
2336         the number of times to loop around the key generator.  I would
2337         suggest leaving it's value as 1.  Key and iv are the structures to
2338         place the returning iv and key in.  If they are NULL, no value is
2339         generated for that particular value.
2340         The algorithm used is as follows
2341         
2342         /* M[] is an array of message digests
2343          * MD() is the message digest function */
2344         M[0]=MD(data . salt);
2345         for (i=1; i<count; i++) M[0]=MD(M[0]);
2346
2347         i=1
2348         while (data still needed for key and iv)
2349                 {
2350                 M[i]=MD(M[i-1] . data . salt);
2351                 for (i=1; i<count; i++) M[i]=MD(M[i]);
2352                 i++;
2353                 }
2354
2355         If the salt is NULL, it is not used.
2356         The digests are concatenated together.
2357         M = M[0] . M[1] . M[2] .......
2358
2359         For key= 8, iv=8 => key=M[0.. 8], iv=M[ 9 .. 16].
2360         For key=16, iv=0 => key=M[0..16].
2361         For key=16, iv=8 => key=M[0..16], iv=M[17 .. 24].
2362         For key=24, iv=8 => key=M[0..24], iv=M[25 .. 32].
2363
2364         This routine will produce DES-CBC keys and iv that are compatible
2365         with the PKCS-5 standard when md2 or md5 are used.  If md5 is
2366         used, the salt is NULL and count is 1, this routine will produce
2367         the password to key mapping normally used with RC4.
2368         I have attempted to logically extend the PKCS-5 standard to
2369         generate keys and iv for ciphers that require more than 16 bytes,
2370         if anyone knows what the correct standard is, please inform me.
2371         When using sha or sha1, things are a bit different under this scheme,
2372         since sha produces a 20 byte digest.  So for ciphers requiring
2373         24 bits of data, 20 will come from the first MD and 4 will
2374         come from the second.
2375
2376         I have considered having a separate function so this 'routine'
2377         can be used without the requirement of passing a EVP_CIPHER *,
2378         but I have decided to not bother.  If you wish to use the
2379         function without official EVP_CIPHER structures, just declare
2380         a local one and set the key_len and iv_len fields to the
2381         length you desire.
2382
2383 The following routines perform encryption and decryption 'by parts'.  By
2384 this I mean that there are groups of 3 routines.  An Init function that is
2385 used to specify a cipher and initialise data structures.  An Update routine
2386 that does encryption/decryption, one 'chunk' at a time.  And finally a
2387 'Final' function that finishes the encryption/decryption process.
2388 All these functions take a EVP_CIPHER pointer to specify which cipher to
2389 encrypt/decrypt with.  They also take a EVP_CIPHER_CTX object as an
2390 argument.  This structure is used to hold the state information associated
2391 with the operation in progress.
2392
2393 void EVP_EncryptInit(
2394 EVP_CIPHER_CTX *ctx,
2395 EVP_CIPHER *type,
2396 unsigned char *key,
2397 unsigned char *iv);
2398         This function initialise a EVP_CIPHER_CTX for encryption using the
2399         cipher passed in the 'type' field.  The cipher is initialised to use
2400         'key' as the key and 'iv' for the initialisation vector (if one is
2401         required).  If the type, key or iv is NULL, the value currently in the
2402         EVP_CIPHER_CTX is reused.  So to perform several decrypt
2403         using the same cipher, key and iv, initialise with the cipher,
2404         key and iv the first time and then for subsequent calls,
2405         reuse 'ctx' but pass NULL for type, key and iv.  You must make sure
2406         to pass a key that is large enough for a particular cipher.  I
2407         would suggest using the EVP_BytesToKey() function.
2408
2409 void EVP_EncryptUpdate(
2410 EVP_CIPHER_CTX *ctx,
2411 unsigned char *out,
2412 int *outl,
2413 unsigned char *in,
2414 int inl);
2415         This function takes 'inl' bytes from 'in' and outputs bytes
2416         encrypted by the cipher 'ctx' was initialised with into 'out'.  The
2417         number of bytes written to 'out' is put into outl.  If a particular
2418         cipher encrypts in blocks, less or more bytes than input may be
2419         output.  Currently the largest block size used by supported ciphers
2420         is 8 bytes, so 'out' should have room for 'inl+7' bytes.  Normally
2421         EVP_EncryptInit() is called once, followed by lots and lots of
2422         calls to EVP_EncryptUpdate, followed by a single EVP_EncryptFinal
2423         call.
2424
2425 void EVP_EncryptFinal(
2426 EVP_CIPHER_CTX *ctx,
2427 unsigned char *out,
2428 int *outl);
2429         Because quite a large number of ciphers are block ciphers, there is
2430         often an incomplete block to write out at the end of the
2431         encryption.  EVP_EncryptFinal() performs processing on this last
2432         block.  The last block in encoded in such a way that it is possible
2433         to determine how many bytes in the last block are valid.  For 8 byte
2434         block size ciphers, if only 5 bytes in the last block are valid, the
2435         last three bytes will be filled with the value 3.  If only 2 were
2436         valid, the other 6 would be filled with sixes.  If all 8 bytes are
2437         valid, a extra 8 bytes are appended to the cipher stream containing
2438         nothing but 8 eights.  These last bytes are output into 'out' and
2439         the number of bytes written is put into 'outl'  These last bytes
2440         are output into 'out' and the number of bytes written is put into
2441         'outl'.  This form of block cipher finalisation is compatible with
2442         PKCS-5.  Please remember that even if you are using ciphers like
2443         RC4 that has no blocking and so the function will not write
2444         anything into 'out', it would still be a good idea to pass a
2445         variable for 'out' that can hold 8 bytes just in case the cipher is
2446         changed some time in the future.  It should also be remembered
2447         that the EVP_CIPHER_CTX contains the password and so when one has
2448         finished encryption with a particular EVP_CIPHER_CTX, it is good
2449         practice to zero the structure 
2450         (ie. memset(ctx,0,sizeof(EVP_CIPHER_CTX)).
2451         
2452 void EVP_DecryptInit(
2453 EVP_CIPHER_CTX *ctx,
2454 EVP_CIPHER *type,
2455 unsigned char *key,
2456 unsigned char *iv);
2457         This function is basically the same as EVP_EncryptInit() accept that
2458         is prepares the EVP_CIPHER_CTX for decryption.
2459
2460 void EVP_DecryptUpdate(
2461 EVP_CIPHER_CTX *ctx,
2462 unsigned char *out,
2463 int *outl,
2464 unsigned char *in,
2465 int inl);
2466         This function is basically the same as EVP_EncryptUpdate()
2467         except that it performs decryption.  There is one
2468         fundamental difference though.  'out' can not be the same as
2469         'in' for any ciphers with a block size greater than 1 if more
2470         than one call to EVP_DecryptUpdate() will be made.  This
2471         is because this routine can hold a 'partial' block between
2472         calls.  When a partial block is decrypted (due to more bytes
2473         being passed via this function, they will be written to 'out'
2474         overwriting the input bytes in 'in' that have not been read
2475         yet.  From this it should also be noted that 'out' should
2476         be at least one 'block size' larger than 'inl'.  This problem
2477         only occurs on the second and subsequent call to
2478         EVP_DecryptUpdate() when using a block cipher.
2479
2480 int EVP_DecryptFinal(
2481 EVP_CIPHER_CTX *ctx,
2482 unsigned char *out,
2483 int *outl);
2484         This function is different to EVP_EncryptFinal in that it 'removes'
2485         any padding bytes appended when the data was encrypted.  Due to the
2486         way in which 1 to 8 bytes may have been appended when encryption
2487         using a block cipher, 'out' can end up with 0 to 7 bytes being put
2488         into it.  When decoding the padding bytes, it is possible to detect
2489         an incorrect decryption.  If the decryption appears to be wrong, 0
2490         is returned.  If everything seems ok, 1 is returned.  For ciphers
2491         with a block size of 1 (RC4), this function would normally not
2492         return any bytes and would always return 1.  Just because this
2493         function returns 1 does not mean the decryption was correct. It
2494         would normally be wrong due to either the wrong key/iv or
2495         corruption of the cipher data fed to EVP_DecryptUpdate().
2496         As for EVP_EncryptFinal, it is a good idea to zero the
2497         EVP_CIPHER_CTX after use since the structure contains the key used
2498         to decrypt the data.
2499         
2500 The following Cipher routines are convenience routines that call either
2501 EVP_EncryptXxx or EVP_DecryptXxx depending on weather the EVP_CIPHER_CTX
2502 was setup to encrypt or decrypt.  
2503
2504 void EVP_CipherInit(
2505 EVP_CIPHER_CTX *ctx,
2506 EVP_CIPHER *type,
2507 unsigned char *key,
2508 unsigned char *iv,
2509 int enc);
2510         This function take arguments that are the same as EVP_EncryptInit()
2511         and EVP_DecryptInit() except for the extra 'enc' flag.  If 1, the
2512         EVP_CIPHER_CTX is setup for encryption, if 0, decryption.
2513
2514 void EVP_CipherUpdate(
2515 EVP_CIPHER_CTX *ctx,
2516 unsigned char *out,
2517 int *outl,
2518 unsigned char *in,
2519 int inl);
2520         Again this function calls either EVP_EncryptUpdate() or
2521         EVP_DecryptUpdate() depending on state in the 'ctx' structure.
2522         As noted for EVP_DecryptUpdate(), when this routine is used
2523         for decryption with block ciphers, 'out' should not be the
2524         same as 'in'.
2525
2526 int EVP_CipherFinal(
2527 EVP_CIPHER_CTX *ctx,
2528 unsigned char *outm,
2529 int *outl);
2530         This routine call EVP_EncryptFinal() or EVP_DecryptFinal()
2531         depending on the state information in 'ctx'.  1 is always returned
2532         if the mode is encryption, otherwise the return value is the return
2533         value of EVP_DecryptFinal().
2534
2535 ==== cipher.m ========================================================
2536
2537 Date: Tue, 15 Oct 1996 08:16:14 +1000 (EST)
2538 From: Eric Young <eay@mincom.com>
2539 X-Sender: eay@orb
2540 To: Roland Haring <rharing@tandem.cl>
2541 Cc: ssl-users@mincom.com
2542 Subject: Re: Symmetric encryption with ssleay
2543 In-Reply-To: <m0vBpyq-00001aC@tandemnet.tandem.cl>
2544 Message-Id: <Pine.SOL.3.91.961015075623.11394A-100000@orb>
2545 Mime-Version: 1.0
2546 Content-Type: TEXT/PLAIN; charset=US-ASCII
2547 Sender: ssl-lists-owner@mincom.com
2548 Precedence: bulk
2549 Status: RO
2550 X-Status: 
2551
2552 On Fri, 11 Oct 1996, Roland Haring wrote:
2553 > THE_POINT:
2554 >       Would somebody be so kind to give me the minimum basic 
2555 >       calls I need to do to libcrypto.a to get some text encrypted
2556 >       and decrypted again? ...hopefully with code included to do
2557 >       base64 encryption and decryption ... e.g. that sign-it.c code
2558 >       posted some while ago was a big help :-) (please, do not point
2559 >       me to apps/enc.c where I suspect my Heissenbug to be hidden :-)
2560
2561 Ok, the base64 encoding stuff in 'enc.c' does the wrong thing sometimes 
2562 when the data is less than a line long (this is for decoding).  I'll dig 
2563 up the exact fix today and post it.  I am taking longer on 0.6.5 than I 
2564 intended so I'll just post this patch.
2565
2566 The documentation to read is in
2567 doc/cipher.doc,
2568 doc/encode.doc (very sparse :-).
2569 and perhaps
2570 doc/digest.doc,
2571
2572 The basic calls to encrypt with say triple DES are
2573
2574 Given
2575 char key[EVP_MAX_KEY_LENGTH];
2576 char iv[EVP_MAX_IV_LENGTH];
2577 EVP_CIPHER_CTX ctx;
2578 unsigned char out[512+8];
2579 int outl;
2580
2581 /* optional generation of key/iv data from text password using md5
2582  * via an upward compatable verson of PKCS#5. */
2583 EVP_BytesToKey(EVP_des_ede3_cbc,EVP_md5,NULL,passwd,strlen(passwd),
2584         key,iv);
2585
2586 /* Initalise the EVP_CIPHER_CTX */
2587 EVP_EncryptInit(ctx,EVP_des_ede3_cbc,key,iv);
2588
2589 while (....)
2590         {
2591         /* This is processing 512 bytes at a time, the bytes are being
2592          * copied into 'out', outl bytes are output.  'out' should not be the
2593          * same as 'in' for reasons mentioned in the documentation. */
2594         EVP_EncryptUpdate(ctx,out,&outl,in,512);
2595         }
2596
2597 /* Output the last 'block'.  If the cipher is a block cipher, the last
2598  * block is encoded in such a way so that a wrong decryption will normally be
2599  * detected - again, one of the PKCS standards. */
2600
2601 EVP_EncryptFinal(ctx,out,&outl);
2602
2603 To decrypt, use the EVP_DecryptXXXXX functions except that EVP_DecryptFinal()
2604 will return 0 if the decryption fails (only detectable on block ciphers).
2605
2606 You can also use
2607 EVP_CipherInit()
2608 EVP_CipherUpdate()
2609 EVP_CipherFinal()
2610 which does either encryption or decryption depending on an extra 
2611 parameter to EVP_CipherInit().
2612
2613
2614 To do the base64 encoding,
2615 EVP_EncodeInit()
2616 EVP_EncodeUpdate()
2617 EVP_EncodeFinal()
2618
2619 EVP_DecodeInit()
2620 EVP_DecodeUpdate()
2621 EVP_DecodeFinal()
2622
2623 where the encoding is quite simple, but the decoding can be a bit more 
2624 fun (due to dud input).
2625
2626 EVP_DecodeUpdate() returns -1 for an error on an input line, 0 if the 
2627 'last line' was just processed, and 1 if more lines should be submitted.
2628
2629 EVP_DecodeFinal() returns -1 for an error or 1 if things are ok.
2630
2631 So the loop becomes
2632 EVP_DecodeInit(....)
2633 for (;;)
2634         {
2635         i=EVP_DecodeUpdate(....);
2636         if (i < 0) goto err;
2637
2638         /* process the data */
2639
2640         if (i == 0) break;
2641         }
2642 EVP_DecodeFinal(....);
2643 /* process the data */
2644
2645 The problem in 'enc.c' is that I was stuff the processing up after the 
2646 EVP_DecodeFinal(...) when the for(..) loop was not being run (one line of 
2647 base64 data) and this was because 'enc.c' tries to scan over a file until
2648 it hits the first valid base64 encoded line.
2649
2650 hope this helps a bit.
2651 eric
2652 --
2653 Eric Young                  | BOOL is tri-state according to Bill Gates.
2654 AARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
2655
2656 ==== conf.doc ========================================================
2657
2658 The CONF library.
2659
2660 The CONF library is a simple set of routines that can be used to configure
2661 programs.  It is a superset of the genenv() function with some extra
2662 structure.
2663
2664 The library consists of 5 functions.
2665
2666 LHASH *CONF_load(LHASH *config,char *file);
2667 This function is called to load in a configuration file.  Multiple
2668 configuration files can be loaded, with each subsequent 'load' overwriting
2669 any already defined 'variables'.  If there is an error, NULL is returned.
2670 If config is NULL, a new LHASH structure is created and returned, otherwise
2671 the new data in the 'file' is loaded into the 'config' structure.
2672
2673 void CONF_free(LHASH *config);
2674 This function free()s the data in config.
2675
2676 char *CONF_get_string(LHASH *config,char *section,char *name);
2677 This function returns the string found in 'config' that corresponds to the
2678 'section' and 'name' specified.  Classes and the naming system used will be
2679 discussed later in this document.  If the variable is not defined, an NULL
2680 is returned.
2681
2682 long CONF_get_long(LHASH *config,char *section, char *name);
2683 This function is the same as CONF_get_string() except that it converts the
2684 string to an long and returns it.  If variable is not a number or the
2685 variable does not exist, 0 is returned.  This is a little problematic but I
2686 don't know of a simple way around it.
2687
2688 STACK *CONF_get_section(LHASH *config, char *section);
2689 This function returns a 'stack' of CONF_VALUE items that are all the
2690 items defined in a particular section.  DO NOT free() any of the
2691 variable returned.  They will disappear when CONF_free() is called.
2692
2693 The 'lookup' model.
2694 The configuration file is divided into 'sections'.  Each section is started by
2695 a line of the form '[ section ]'.  All subsequent variable definitions are
2696 of this section.  A variable definition is a simple alpha-numeric name
2697 followed by an '=' and then the data.  A section or variable name can be
2698 described by a regular expression of the following form '[A-Za-z0-9_]+'.
2699 The value of the variable is the text after the '=' until the end of the
2700 line, stripped of leading and trailing white space.
2701 At this point I should mention that a '#' is a comment character, \ is the
2702 escape character, and all three types of quote can be used to stop any
2703 special interpretation of the data.
2704 Now when the data is being loaded, variable expansion can occur.  This is
2705 done by expanding any $NAME sequences into the value represented by the
2706 variable NAME.  If the variable is not in the current section, the different
2707 section can be specified by using the $SECTION::NAME form.  The ${NAME} form
2708 also works and is very useful for expanding variables inside strings.
2709
2710 When a variable is looked up, there are 2 special section. 'default', which
2711 is the initial section, and 'ENV' which is the processes environment
2712 variables (accessed via getenv()).  When a variable is looked up, it is
2713 first 'matched' with it's section (if one was specified), if this fails, the
2714 'default' section is matched.
2715 If the 'lhash' variable passed was NULL, the environment is searched.
2716
2717 Now why do we bother with sections?  So we can have multiple programs using
2718 the same configuration file, or multiple instances of the same program
2719 using different variables.  It also provides a nice mechanism to override
2720 the processes environment variables (eg ENV::HOME=/tmp).  If there is a
2721 program specific variable missing, we can have default values.
2722 Multiple configuration files can be loaded, with each new value clearing
2723 any predefined values.  A system config file can provide 'default' values,
2724 and application/usr specific files can provide overriding values.
2725
2726 Examples
2727
2728 # This is a simple example
2729 SSLEAY_HOME     = /usr/local/ssl
2730 ENV::PATH       = $SSLEAY_HOME/bin:$PATH        # override my path
2731
2732 [X509]
2733 cert_dir        = $SSLEAY_HOME/certs    # /usr/local/ssl/certs
2734
2735 [SSL]
2736 CIPHER          = DES-EDE-MD5:RC4-MD5
2737 USER_CERT       = $HOME/${USER}di'r 5'  # /home/eay/eaydir 5
2738 USER_CERT       = $HOME/\${USER}di\'r   # /home/eay/${USER}di'r
2739 USER_CERT       = "$HOME/${US"ER}di\'r  # $HOME/${USER}di'r
2740
2741 TEST            = 1234\
2742 5678\
2743 9ab                                     # TEST=123456789ab
2744 TTT             = 1234\n\n              # TTT=1234<nl><nl>
2745
2746
2747
2748 ==== des.doc ========================================================
2749
2750 The DES library.
2751
2752 Please note that this library was originally written to operate with
2753 eBones, a version of Kerberos that had had encryption removed when it left
2754 the USA and then put back in.  As such there are some routines that I will
2755 advise not using but they are still in the library for historical reasons.
2756 For all calls that have an 'input' and 'output' variables, they can be the
2757 same.
2758
2759 This library requires the inclusion of 'des.h'.
2760
2761 All of the encryption functions take what is called a des_key_schedule as an 
2762 argument.  A des_key_schedule is an expanded form of the des key.
2763 A des_key is 8 bytes of odd parity, the type used to hold the key is a
2764 des_cblock.  A des_cblock is an array of 8 bytes, often in this library
2765 description I will refer to input bytes when the function specifies
2766 des_cblock's as input or output, this just means that the variable should
2767 be a multiple of 8 bytes.
2768
2769 The define DES_ENCRYPT is passed to specify encryption, DES_DECRYPT to
2770 specify decryption.  The functions and global variable are as follows:
2771
2772 int des_check_key;
2773         DES keys are supposed to be odd parity.  If this variable is set to
2774         a non-zero value, des_set_key() will check that the key has odd
2775         parity and is not one of the known weak DES keys.  By default this
2776         variable is turned off;
2777         
2778 void des_set_odd_parity(
2779 des_cblock *key );
2780         This function takes a DES key (8 bytes) and sets the parity to odd.
2781         
2782 int des_is_weak_key(
2783 des_cblock *key );
2784         This function returns a non-zero value if the DES key passed is a
2785         weak, DES key.  If it is a weak key, don't use it, try a different
2786         one.  If you are using 'random' keys, the chances of hitting a weak
2787         key are 1/2^52 so it is probably not worth checking for them.
2788         
2789 int des_set_key(
2790 des_cblock *key,
2791 des_key_schedule schedule);
2792         Des_set_key converts an 8 byte DES key into a des_key_schedule.
2793         A des_key_schedule is an expanded form of the key which is used to
2794         perform actual encryption.  It can be regenerated from the DES key
2795         so it only needs to be kept when encryption or decryption is about
2796         to occur.  Don't save or pass around des_key_schedule's since they
2797         are CPU architecture dependent, DES keys are not.  If des_check_key
2798         is non zero, zero is returned if the key has the wrong parity or
2799         the key is a weak key, else 1 is returned.
2800         
2801 int des_key_sched(
2802 des_cblock *key,
2803 des_key_schedule schedule);
2804         An alternative name for des_set_key().
2805
2806 int des_rw_mode;                /* defaults to DES_PCBC_MODE */
2807         This flag holds either DES_CBC_MODE or DES_PCBC_MODE (default).
2808         This specifies the function to use in the enc_read() and enc_write()
2809         functions.
2810
2811 void des_encrypt(
2812 unsigned long *data,
2813 des_key_schedule ks,
2814 int enc);
2815         This is the DES encryption function that gets called by just about
2816         every other DES routine in the library.  You should not use this
2817         function except to implement 'modes' of DES.  I say this because the
2818         functions that call this routine do the conversion from 'char *' to
2819         long, and this needs to be done to make sure 'non-aligned' memory
2820         access do not occur.  The characters are loaded 'little endian',
2821         have a look at my source code for more details on how I use this
2822         function.
2823         Data is a pointer to 2 unsigned long's and ks is the
2824         des_key_schedule to use.  enc, is non zero specifies encryption,
2825         zero if decryption.
2826
2827 void des_encrypt2(
2828 unsigned long *data,
2829 des_key_schedule ks,
2830 int enc);
2831         This functions is the same as des_encrypt() except that the DES
2832         initial permutation (IP) and final permutation (FP) have been left
2833         out.  As for des_encrypt(), you should not use this function.
2834         It is used by the routines in my library that implement triple DES.
2835         IP() des_encrypt2() des_encrypt2() des_encrypt2() FP() is the same
2836         as des_encrypt() des_encrypt() des_encrypt() except faster :-).
2837
2838 void des_ecb_encrypt(
2839 des_cblock *input,
2840 des_cblock *output,
2841 des_key_schedule ks,
2842 int enc);
2843         This is the basic Electronic Code Book form of DES, the most basic
2844         form.  Input is encrypted into output using the key represented by
2845         ks.  If enc is non zero (DES_ENCRYPT), encryption occurs, otherwise
2846         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
2847         (the des_cblock structure is 8 chars).
2848         
2849 void des_ecb3_encrypt(
2850 des_cblock *input,
2851 des_cblock *output,
2852 des_key_schedule ks1,
2853 des_key_schedule ks2,
2854 des_key_schedule ks3,
2855 int enc);
2856         This is the 3 key EDE mode of ECB DES.  What this means is that 
2857         the 8 bytes of input is encrypted with ks1, decrypted with ks2 and
2858         then encrypted again with ks3, before being put into output;
2859         C=E(ks3,D(ks2,E(ks1,M))).  There is a macro, des_ecb2_encrypt()
2860         that only takes 2 des_key_schedules that implements,
2861         C=E(ks1,D(ks2,E(ks1,M))) in that the final encrypt is done with ks1.
2862         
2863 void des_cbc_encrypt(
2864 des_cblock *input,
2865 des_cblock *output,
2866 long length,
2867 des_key_schedule ks,
2868 des_cblock *ivec,
2869 int enc);
2870         This routine implements DES in Cipher Block Chaining mode.
2871         Input, which should be a multiple of 8 bytes is encrypted
2872         (or decrypted) to output which will also be a multiple of 8 bytes.
2873         The number of bytes is in length (and from what I've said above,
2874         should be a multiple of 8).  If length is not a multiple of 8, I'm
2875         not being held responsible :-).  ivec is the initialisation vector.
2876         This function does not modify this variable.  To correctly implement
2877         cbc mode, you need to do one of 2 things; copy the last 8 bytes of
2878         cipher text for use as the next ivec in your application,
2879         or use des_ncbc_encrypt(). 
2880         Only this routine has this problem with updating the ivec, all
2881         other routines that are implementing cbc mode update ivec.
2882         
2883 void des_ncbc_encrypt(
2884 des_cblock *input,
2885 des_cblock *output,
2886 long length,
2887 des_key_schedule sk,
2888 des_cblock *ivec,
2889 int enc);
2890         For historical reasons, des_cbc_encrypt() did not update the
2891         ivec with the value requires so that subsequent calls to
2892         des_cbc_encrypt() would 'chain'.  This was needed so that the same
2893         'length' values would not need to be used when decrypting.
2894         des_ncbc_encrypt() does the right thing.  It is the same as
2895         des_cbc_encrypt accept that ivec is updates with the correct value
2896         to pass in subsequent calls to des_ncbc_encrypt().  I advise using
2897         des_ncbc_encrypt() instead of des_cbc_encrypt();
2898
2899 void des_xcbc_encrypt(
2900 des_cblock *input,
2901 des_cblock *output,
2902 long length,
2903 des_key_schedule sk,
2904 des_cblock *ivec,
2905 des_cblock *inw,
2906 des_cblock *outw,
2907 int enc);
2908         This is RSA's DESX mode of DES.  It uses inw and outw to
2909         'whiten' the encryption.  inw and outw are secret (unlike the iv)
2910         and are as such, part of the key.  So the key is sort of 24 bytes.
2911         This is much better than cbc des.
2912         
2913 void des_3cbc_encrypt(
2914 des_cblock *input,
2915 des_cblock *output,
2916 long length,
2917 des_key_schedule sk1,
2918 des_key_schedule sk2,
2919 des_cblock *ivec1,
2920 des_cblock *ivec2,
2921 int enc);
2922         This function is flawed, do not use it.  I have left it in the
2923         library because it is used in my des(1) program and will function
2924         correctly when used by des(1).  If I removed the function, people
2925         could end up unable to decrypt files.
2926         This routine implements outer triple cbc encryption using 2 ks and
2927         2 ivec's.  Use des_ede2_cbc_encrypt() instead.
2928         
2929 void des_ede3_cbc_encrypt(
2930 des_cblock *input,
2931 des_cblock *output, 
2932 long length,
2933 des_key_schedule ks1,
2934 des_key_schedule ks2, 
2935 des_key_schedule ks3, 
2936 des_cblock *ivec,
2937 int enc);
2938         This function implements outer triple CBC DES encryption with 3
2939         keys.  What this means is that each 'DES' operation
2940         inside the cbc mode is really an C=E(ks3,D(ks2,E(ks1,M))).
2941         Again, this is cbc mode so an ivec is requires.
2942         This mode is used by SSL.
2943         There is also a des_ede2_cbc_encrypt() that only uses 2
2944         des_key_schedule's, the first being reused for the final
2945         encryption.  C=E(ks1,D(ks2,E(ks1,M))).  This form of triple DES
2946         is used by the RSAref library.
2947         
2948 void des_pcbc_encrypt(
2949 des_cblock *input,
2950 des_cblock *output,
2951 long length,
2952 des_key_schedule ks,
2953 des_cblock *ivec,
2954 int enc);
2955         This is Propagating Cipher Block Chaining mode of DES.  It is used
2956         by Kerberos v4.  It's parameters are the same as des_ncbc_encrypt().
2957         
2958 void des_cfb_encrypt(
2959 unsigned char *in,
2960 unsigned char *out,
2961 int numbits,
2962 long length,
2963 des_key_schedule ks,
2964 des_cblock *ivec,
2965 int enc);
2966         Cipher Feedback Back mode of DES.  This implementation 'feeds back'
2967         in numbit blocks.  The input (and output) is in multiples of numbits
2968         bits.  numbits should to be a multiple of 8 bits.  Length is the
2969         number of bytes input.  If numbits is not a multiple of 8 bits,
2970         the extra bits in the bytes will be considered padding.  So if
2971         numbits is 12, for each 2 input bytes, the 4 high bits of the
2972         second byte will be ignored.  So to encode 72 bits when using
2973         a numbits of 12 take 12 bytes.  To encode 72 bits when using
2974         numbits of 9 will take 16 bytes.  To encode 80 bits when using
2975         numbits of 16 will take 10 bytes. etc, etc.  This padding will
2976         apply to both input and output.
2977
2978         
2979 void des_cfb64_encrypt(
2980 unsigned char *in,
2981 unsigned char *out,
2982 long length,
2983 des_key_schedule ks,
2984 des_cblock *ivec,
2985 int *num,
2986 int enc);
2987         This is one of the more useful functions in this DES library, it
2988         implements CFB mode of DES with 64bit feedback.  Why is this
2989         useful you ask?  Because this routine will allow you to encrypt an
2990         arbitrary number of bytes, no 8 byte padding.  Each call to this
2991         routine will encrypt the input bytes to output and then update ivec
2992         and num.  num contains 'how far' we are though ivec.  If this does
2993         not make much sense, read more about cfb mode of DES :-).
2994         
2995 void des_ede3_cfb64_encrypt(
2996 unsigned char *in,
2997 unsigned char *out,
2998 long length,
2999 des_key_schedule ks1,
3000 des_key_schedule ks2,
3001 des_key_schedule ks3,
3002 des_cblock *ivec,
3003 int *num,
3004 int enc);
3005         Same as des_cfb64_encrypt() accept that the DES operation is
3006         triple DES.  As usual, there is a macro for
3007         des_ede2_cfb64_encrypt() which reuses ks1.
3008
3009 void des_ofb_encrypt(
3010 unsigned char *in,
3011 unsigned char *out,
3012 int numbits,
3013 long length,
3014 des_key_schedule ks,
3015 des_cblock *ivec);
3016         This is a implementation of Output Feed Back mode of DES.  It is
3017         the same as des_cfb_encrypt() in that numbits is the size of the
3018         units dealt with during input and output (in bits).
3019         
3020 void des_ofb64_encrypt(
3021 unsigned char *in,
3022 unsigned char *out,
3023 long length,
3024 des_key_schedule ks,
3025 des_cblock *ivec,
3026 int *num);
3027         The same as des_cfb64_encrypt() except that it is Output Feed Back
3028         mode.
3029
3030 void des_ede3_ofb64_encrypt(
3031 unsigned char *in,
3032 unsigned char *out,
3033 long length,
3034 des_key_schedule ks1,
3035 des_key_schedule ks2,
3036 des_key_schedule ks3,
3037 des_cblock *ivec,
3038 int *num);
3039         Same as des_ofb64_encrypt() accept that the DES operation is
3040         triple DES.  As usual, there is a macro for
3041         des_ede2_ofb64_encrypt() which reuses ks1.
3042
3043 int des_read_pw_string(
3044 char *buf,
3045 int length,
3046 char *prompt,
3047 int verify);
3048         This routine is used to get a password from the terminal with echo
3049         turned off.  Buf is where the string will end up and length is the
3050         size of buf.  Prompt is a string presented to the 'user' and if
3051         verify is set, the key is asked for twice and unless the 2 copies
3052         match, an error is returned.  A return code of -1 indicates a
3053         system error, 1 failure due to use interaction, and 0 is success.
3054
3055 unsigned long des_cbc_cksum(
3056 des_cblock *input,
3057 des_cblock *output,
3058 long length,
3059 des_key_schedule ks,
3060 des_cblock *ivec);
3061         This function produces an 8 byte checksum from input that it puts in
3062         output and returns the last 4 bytes as a long.  The checksum is
3063         generated via cbc mode of DES in which only the last 8 byes are
3064         kept.  I would recommend not using this function but instead using
3065         the EVP_Digest routines, or at least using MD5 or SHA.  This
3066         function is used by Kerberos v4 so that is why it stays in the
3067         library.
3068         
3069 char *des_fcrypt(
3070 const char *buf,
3071 const char *salt
3072 char *ret);
3073         This is my fast version of the unix crypt(3) function.  This version
3074         takes only a small amount of space relative to other fast
3075         crypt() implementations.  This is different to the normal crypt
3076         in that the third parameter is the buffer that the return value
3077         is written into.  It needs to be at least 14 bytes long.  This
3078         function is thread safe, unlike the normal crypt.
3079
3080 char *crypt(
3081 const char *buf,
3082 const char *salt);
3083         This function calls des_fcrypt() with a static array passed as the
3084         third parameter.  This emulates the normal non-thread safe semantics
3085         of crypt(3).
3086
3087 void des_string_to_key(
3088 char *str,
3089 des_cblock *key);
3090         This function takes str and converts it into a DES key.  I would
3091         recommend using MD5 instead and use the first 8 bytes of output.
3092         When I wrote the first version of these routines back in 1990, MD5
3093         did not exist but I feel these routines are still sound.  This
3094         routines is compatible with the one in MIT's libdes.
3095         
3096 void des_string_to_2keys(
3097 char *str,
3098 des_cblock *key1,
3099 des_cblock *key2);
3100         This function takes str and converts it into 2 DES keys.
3101         I would recommend using MD5 and using the 16 bytes as the 2 keys.
3102         I have nothing against these 2 'string_to_key' routines, it's just
3103         that if you say that your encryption key is generated by using the
3104         16 bytes of an MD5 hash, every-one knows how you generated your
3105         keys.
3106
3107 int des_read_password(
3108 des_cblock *key,
3109 char *prompt,
3110 int verify);
3111         This routine combines des_read_pw_string() with des_string_to_key().
3112
3113 int des_read_2passwords(
3114 des_cblock *key1,
3115 des_cblock *key2,
3116 char *prompt,
3117 int verify);
3118         This routine combines des_read_pw_string() with des_string_to_2key().
3119
3120 void des_random_seed(
3121 des_cblock key);
3122         This routine sets a starting point for des_random_key().
3123         
3124 void des_random_key(
3125 des_cblock ret);
3126         This function return a random key.  Make sure to 'seed' the random
3127         number generator (with des_random_seed()) before using this function.
3128         I personally now use a MD5 based random number system.
3129
3130 int des_enc_read(
3131 int fd,
3132 char *buf,
3133 int len,
3134 des_key_schedule ks,
3135 des_cblock *iv);
3136         This function will write to a file descriptor the encrypted data
3137         from buf.  This data will be preceded by a 4 byte 'byte count' and
3138         will be padded out to 8 bytes.  The encryption is either CBC of
3139         PCBC depending on the value of des_rw_mode.  If it is DES_PCBC_MODE,
3140         pcbc is used, if DES_CBC_MODE, cbc is used.  The default is to use
3141         DES_PCBC_MODE.
3142
3143 int des_enc_write(
3144 int fd,
3145 char *buf,
3146 int len,
3147 des_key_schedule ks,
3148 des_cblock *iv);
3149         This routines read stuff written by des_enc_read() and decrypts it.
3150         I have used these routines quite a lot but I don't believe they are
3151         suitable for non-blocking io.  If you are after a full
3152         authentication/encryption over networks, have a look at SSL instead.
3153
3154 unsigned long des_quad_cksum(
3155 des_cblock *input,
3156 des_cblock *output,
3157 long length,
3158 int out_count,
3159 des_cblock *seed);
3160         This is a function from Kerberos v4 that is not anything to do with
3161         DES but was needed.  It is a cksum that is quicker to generate than
3162         des_cbc_cksum();  I personally would use MD5 routines now.
3163 =====
3164 Modes of DES
3165 Quite a bit of the following information has been taken from
3166         AS 2805.5.2
3167         Australian Standard
3168         Electronic funds transfer - Requirements for interfaces,
3169         Part 5.2: Modes of operation for an n-bit block cipher algorithm
3170         Appendix A
3171
3172 There are several different modes in which DES can be used, they are
3173 as follows.
3174
3175 Electronic Codebook Mode (ECB) (des_ecb_encrypt())
3176 - 64 bits are enciphered at a time.
3177 - The order of the blocks can be rearranged without detection.
3178 - The same plaintext block always produces the same ciphertext block
3179   (for the same key) making it vulnerable to a 'dictionary attack'.
3180 - An error will only affect one ciphertext block.
3181
3182 Cipher Block Chaining Mode (CBC) (des_cbc_encrypt())
3183 - a multiple of 64 bits are enciphered at a time.
3184 - The CBC mode produces the same ciphertext whenever the same
3185   plaintext is encrypted using the same key and starting variable.
3186 - The chaining operation makes the ciphertext blocks dependent on the
3187   current and all preceding plaintext blocks and therefore blocks can not
3188   be rearranged.
3189 - The use of different starting variables prevents the same plaintext
3190   enciphering to the same ciphertext.
3191 - An error will affect the current and the following ciphertext blocks.
3192
3193 Cipher Feedback Mode (CFB) (des_cfb_encrypt())
3194 - a number of bits (j) <= 64 are enciphered at a time.
3195 - The CFB mode produces the same ciphertext whenever the same
3196   plaintext is encrypted using the same key and starting variable.
3197 - The chaining operation makes the ciphertext variables dependent on the
3198   current and all preceding variables and therefore j-bit variables are
3199   chained together and can not be rearranged.
3200 - The use of different starting variables prevents the same plaintext
3201   enciphering to the same ciphertext.
3202 - The strength of the CFB mode depends on the size of k (maximal if
3203   j == k).  In my implementation this is always the case.
3204 - Selection of a small value for j will require more cycles through
3205   the encipherment algorithm per unit of plaintext and thus cause
3206   greater processing overheads.
3207 - Only multiples of j bits can be enciphered.
3208 - An error will affect the current and the following ciphertext variables.
3209
3210 Output Feedback Mode (OFB) (des_ofb_encrypt())
3211 - a number of bits (j) <= 64 are enciphered at a time.
3212 - The OFB mode produces the same ciphertext whenever the same
3213   plaintext enciphered using the same key and starting variable.  More
3214   over, in the OFB mode the same key stream is produced when the same
3215   key and start variable are used.  Consequently, for security reasons
3216   a specific start variable should be used only once for a given key.
3217 - The absence of chaining makes the OFB more vulnerable to specific attacks.
3218 - The use of different start variables values prevents the same
3219   plaintext enciphering to the same ciphertext, by producing different
3220   key streams.
3221 - Selection of a small value for j will require more cycles through
3222   the encipherment algorithm per unit of plaintext and thus cause
3223   greater processing overheads.
3224 - Only multiples of j bits can be enciphered.
3225 - OFB mode of operation does not extend ciphertext errors in the
3226   resultant plaintext output.  Every bit error in the ciphertext causes
3227   only one bit to be in error in the deciphered plaintext.
3228 - OFB mode is not self-synchronising.  If the two operation of
3229   encipherment and decipherment get out of synchronism, the system needs
3230   to be re-initialised.
3231 - Each re-initialisation should use a value of the start variable
3232  different from the start variable values used before with the same
3233  key.  The reason for this is that an identical bit stream would be
3234  produced each time from the same parameters.  This would be
3235  susceptible to a ' known plaintext' attack.
3236
3237 Triple ECB Mode (des_ecb3_encrypt())
3238 - Encrypt with key1, decrypt with key2 and encrypt with key3 again.
3239 - As for ECB encryption but increases the key length to 168 bits.
3240   There are theoretic attacks that can be used that make the effective
3241   key length 112 bits, but this attack also requires 2^56 blocks of
3242   memory, not very likely, even for the NSA.
3243 - If both keys are the same it is equivalent to encrypting once with
3244   just one key.
3245 - If the first and last key are the same, the key length is 112 bits.
3246   There are attacks that could reduce the key space to 55 bit's but it
3247   requires 2^56 blocks of memory.
3248 - If all 3 keys are the same, this is effectively the same as normal
3249   ecb mode.
3250
3251 Triple CBC Mode (des_ede3_cbc_encrypt())
3252 - Encrypt with key1, decrypt with key2 and then encrypt with key3.
3253 - As for CBC encryption but increases the key length to 168 bits with
3254   the same restrictions as for triple ecb mode.
3255
3256 ==== digest.doc ========================================================
3257
3258
3259 The Message Digest subroutines.
3260
3261 These routines require "evp.h" to be included.
3262
3263 These functions are a higher level interface to the various message digest
3264 routines found in this library.  As such, they allow the same code to be
3265 used to digest via different algorithms with only a change in an initial
3266 parameter.  They are basically just a front-end to the MD2, MD5, SHA
3267 and SHA1
3268 routines.
3269
3270 These routines all take a pointer to the following structure to specify
3271 which message digest algorithm to use.
3272 typedef struct evp_md_st
3273         {
3274         int type;
3275         int pkey_type;
3276         int md_size;
3277         void (*init)();
3278         void (*update)();
3279         void (*final)();
3280
3281         int required_pkey_type; /*EVP_PKEY_xxx */
3282         int (*sign)();
3283         int (*verify)();
3284         } EVP_MD;
3285
3286 If additional message digest algorithms are to be supported, a structure of
3287 this type needs to be declared and populated and then the Digest routines
3288 can be used with that algorithm.  The type field is the object NID of the
3289 digest type (read the section on Objects for an explanation).  The pkey_type
3290 is the Object type to use when the a message digest is generated by there
3291 routines and then is to be signed with the pkey algorithm.  Md_size is
3292 the size of the message digest returned.  Init, update
3293 and final are the relevant functions to perform the message digest function
3294 by parts.  One reason for specifying the message digest to use via this
3295 mechanism is that if you only use md5, only the md5 routines will
3296 be included in you linked program.  If you passed an integer
3297 that specified which message digest to use, the routine that mapped that
3298 integer to a set of message digest functions would cause all the message
3299 digests functions to be link into the code.  This setup also allows new
3300 message digest functions to be added by the application.
3301
3302 The six message digests defined in this library are
3303
3304 EVP_MD *EVP_md2(void);  /* RSA sign/verify */
3305 EVP_MD *EVP_md5(void);  /* RSA sign/verify */
3306 EVP_MD *EVP_sha(void);  /* RSA sign/verify */
3307 EVP_MD *EVP_sha1(void); /* RSA sign/verify */
3308 EVP_MD *EVP_dss(void);  /* DSA sign/verify */
3309 EVP_MD *EVP_dss1(void); /* DSA sign/verify */
3310
3311 All the message digest routines take a EVP_MD_CTX pointer as an argument.
3312 The state of the message digest is kept in this structure.
3313
3314 typedef struct pem_md_ctx_st
3315         {
3316         EVP_MD *digest;
3317         union   {
3318                 unsigned char base[4]; /* this is used in my library as a
3319                                         * 'pointer' to all union elements
3320                                         * structures. */
3321                 MD2_CTX md2;
3322                 MD5_CTX md5;
3323                 SHA_CTX sha;
3324                 } md;
3325         } EVP_MD_CTX;
3326
3327 The Digest functions are as follows.
3328
3329 void EVP_DigestInit(
3330 EVP_MD_CTX *ctx,
3331 EVP_MD *type);
3332         This function is used to initialise the EVP_MD_CTX.  The message
3333         digest that will associated with 'ctx' is specified by 'type'.
3334
3335 void EVP_DigestUpdate(
3336 EVP_MD_CTX *ctx,
3337 unsigned char *data,
3338 unsigned int cnt);
3339         This function is used to pass more data to the message digest
3340         function.  'cnt' bytes are digested from 'data'.
3341
3342 void EVP_DigestFinal(
3343 EVP_MD_CTX *ctx,
3344 unsigned char *md,
3345 unsigned int *len);
3346         This function finishes the digestion and puts the message digest
3347         into 'md'.  The length of the message digest is put into len;
3348         EVP_MAX_MD_SIZE is the size of the largest message digest that
3349         can be returned from this function.  Len can be NULL if the
3350         size of the digest is not required.
3351         
3352
3353 ==== encode.doc ========================================================
3354
3355
3356 void    EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
3357 void    EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,
3358                 int *outl,unsigned char *in,int inl);
3359 void    EVP_EncodeFinal(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl);
3360 int     EVP_EncodeBlock(unsigned char *t, unsigned char *f, int n);
3361
3362 void    EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
3363 int     EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
3364                 unsigned char *in, int inl);
3365 int     EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
3366                 char *out, int *outl);
3367 int     EVP_DecodeBlock(unsigned char *t, unsigned
3368                 char *f, int n);
3369
3370
3371 ==== envelope.doc ========================================================
3372
3373 The following routines are use to create 'digital' envelopes.
3374 By this I mean that they perform various 'higher' level cryptographic
3375 functions.  Have a read of 'cipher.doc' and 'digest.doc' since those
3376 routines are used by these functions.
3377 cipher.doc contains documentation about the cipher part of the
3378 envelope library and digest.doc contatins the description of the
3379 message digests supported.
3380
3381 To 'sign' a document involves generating a message digest and then encrypting
3382 the digest with an private key.
3383
3384 #define EVP_SignInit(a,b)               EVP_DigestInit(a,b)
3385 #define EVP_SignUpdate(a,b,c)           EVP_DigestUpdate(a,b,c)
3386 Due to the fact this operation is basically just an extended message
3387 digest, the first 2 functions are macro calls to Digest generating
3388 functions.
3389
3390 int     EVP_SignFinal(
3391 EVP_MD_CTX *ctx,
3392 unsigned char *md,
3393 unsigned int *s,
3394 EVP_PKEY *pkey);
3395         This finalisation function finishes the generation of the message
3396 digest and then encrypts the digest (with the correct message digest 
3397 object identifier) with the EVP_PKEY private key.  'ctx' is the message digest
3398 context.  'md' will end up containing the encrypted message digest.  This
3399 array needs to be EVP_PKEY_size(pkey) bytes long.  's' will actually
3400 contain the exact length.  'pkey' of course is the private key.  It is
3401 one of EVP_PKEY_RSA or EVP_PKEY_DSA type.
3402 If there is an error, 0 is returned, otherwise 1.
3403                 
3404 Verify is used to check an signed message digest.
3405
3406 #define EVP_VerifyInit(a,b)             EVP_DigestInit(a,b)
3407 #define EVP_VerifyUpdate(a,b,c)         EVP_DigestUpdate(a,b,c)
3408 Since the first step is to generate a message digest, the first 2 functions
3409 are macros.
3410
3411 int EVP_VerifyFinal(
3412 EVP_MD_CTX *ctx,
3413 unsigned char *md,
3414 unsigned int s,
3415 EVP_PKEY *pkey);
3416         This function finishes the generation of the message digest and then
3417 compares it with the supplied encrypted message digest.  'md' contains the
3418 's' bytes of encrypted message digest.  'pkey' is used to public key decrypt
3419 the digest.  It is then compared with the message digest just generated.
3420 If they match, 1 is returned else 0.
3421
3422 int     EVP_SealInit(EVP_CIPHER_CTX *ctx, EVP_CIPHER *type, unsigned char **ek,
3423                 int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk);
3424 Must have at least one public key, error is 0.  I should also mention that
3425 the buffers pointed to by 'ek' need to be EVP_PKEY_size(pubk[n]) is size.
3426
3427 #define EVP_SealUpdate(a,b,c,d,e)       EVP_EncryptUpdate(a,b,c,d,e)    
3428 void    EVP_SealFinal(EVP_CIPHER_CTX *ctx,unsigned char *out,int *outl);
3429
3430
3431 int     EVP_OpenInit(EVP_CIPHER_CTX *ctx,EVP_CIPHER *type,unsigned char *ek,
3432                 int ekl,unsigned char *iv,EVP_PKEY *priv);
3433 0 on failure
3434
3435 #define EVP_OpenUpdate(a,b,c,d,e)       EVP_DecryptUpdate(a,b,c,d,e)
3436
3437 int     EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
3438 Decrypt final return code
3439
3440
3441 ==== error.doc ========================================================
3442
3443 The error routines.
3444
3445 The 'error' system I've implemented is intended to server 2 purpose, to
3446 record the reason why a command failed and to record where in the libraries
3447 the failure occurred.  It is more or less setup to record a 'trace' of which
3448 library components were being traversed when the error occurred.
3449
3450 When an error is recorded, it is done so a as single unsigned long which is
3451 composed of three parts.  The top byte is the 'library' number, the middle
3452 12 bytes is the function code, and the bottom 12 bits is the 'reason' code.
3453
3454 Each 'library', or should a say, 'section' of the SSLeay library has a
3455 different unique 'library' error number.  Each function in the library has
3456 a number that is unique for that library.  Each 'library' also has a number
3457 for each 'error reason' that is only unique for that 'library'.
3458
3459 Due to the way these error routines record a 'error trace', there is an
3460 array per thread that is used to store the error codes.
3461 The various functions in this library are used to access
3462 and manipulate this array.
3463
3464 void ERR_put_error(int lib, int func,int reason);
3465         This routine records an error in library 'lib', function 'func'
3466 and reason 'reason'.  As errors get 'put' into the buffer, they wrap
3467 around and overwrite old errors if too many are written.  It is assumed
3468 that the last errors are the most important.
3469
3470 unsigned long ERR_get_error(void );
3471         This function returns the last error added to the error buffer.
3472 In effect it is popping the value off the buffer so repeated calls will
3473 continue to return values until there are no more errors to return in which
3474 case 0 is returned.
3475
3476 unsigned long ERR_peek_error(void );
3477         This function returns the value of the last error added to the
3478 error buffer but does not 'pop' it from the buffer.
3479
3480 void ERR_clear_error(void );
3481         This function clears the error buffer, discarding all unread
3482 errors.
3483
3484 While the above described error system obviously produces lots of different
3485 error number, a method for 'reporting' these errors in a human readable
3486 form is required.  To achieve this, each library has the option of
3487 'registering' error strings.
3488
3489 typedef struct ERR_string_data_st
3490         {
3491         unsigned long error;
3492         char *string;
3493         } ERR_STRING_DATA;
3494
3495 The 'ERR_STRING_DATA' contains an error code and the corresponding text
3496 string.  To add new function error strings for a library, the
3497 ERR_STRING_DATA needs to be 'registered' with the library.
3498
3499 void ERR_load_strings(unsigned long lib,ERR_STRING_DATA *err);
3500         This function 'registers' the array of ERR_STRING_DATA pointed to by
3501 'err' as error text strings for the error library 'lib'.
3502
3503 void ERR_free_strings(void);
3504         This function free()s all the loaded error strings.
3505
3506 char *ERR_error_string(unsigned long error,char *buf);
3507         This function returns a text string that is a human readable
3508 version of the error represented by 'error'.  Buff should be at least 120
3509 bytes long and if it is NULL, the return value is a pointer to a static
3510 variable that will contain the error string, otherwise 'buf' is returned.
3511 If there is not a text string registered for a particular error, a text
3512 string containing the error number is returned instead.
3513
3514 void ERR_print_errors(BIO *bp);
3515 void ERR_print_errors_fp(FILE *fp);
3516         This function is a convenience routine that prints the error string
3517 for each error until all errors have been accounted for.
3518
3519 char *ERR_lib_error_string(unsigned long e);
3520 char *ERR_func_error_string(unsigned long e);
3521 char *ERR_reason_error_string(unsigned long e);
3522 The above three functions return the 3 different components strings for the
3523 error 'e'.  ERR_error_string() uses these functions.
3524
3525 void ERR_load_ERR_strings(void );
3526         This function 'registers' the error strings for the 'ERR' module.
3527
3528 void ERR_load_crypto_strings(void );
3529         This function 'register' the error strings for just about every
3530 library in the SSLeay package except for the SSL routines.  There is no
3531 need to ever reg