Update dependencies.
[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 ==== a_verify.doc ========================================================
39
40 From eay@mincom.com Fri Oct  4 18:29:06 1996
41 Received: by orb.mincom.oz.au id AA29080
42   (5.65c/IDA-1.4.4 for eay); Fri, 4 Oct 1996 08:29:07 +1000
43 Date: Fri, 4 Oct 1996 08:29:06 +1000 (EST)
44 From: Eric Young <eay@mincom.oz.au>
45 X-Sender: eay@orb
46 To: wplatzer <wplatzer@iaik.tu-graz.ac.at>
47 Cc: Eric Young <eay@mincom.oz.au>, SSL Mailing List <ssl-users@mincom.com>
48 Subject: Re: Netscape's Public Key
49 In-Reply-To: <19961003134837.NTM0049@iaik.tu-graz.ac.at>
50 Message-Id: <Pine.SOL.3.91.961004081346.8018K-100000@orb>
51 Mime-Version: 1.0
52 Content-Type: TEXT/PLAIN; charset=US-ASCII
53 Status: RO
54 X-Status: 
55
56 On Thu, 3 Oct 1996, wplatzer wrote:
57 > I get Public Key from Netscape (Gold 3.0b4), but cannot do anything
58 > with it... It looks like (asn1parse):
59
60 > 0:d=0 hl=3 l=180 cons: SEQUENCE
61 > 3:d=1 hl=2 l= 96 cons: SEQUENCE
62 > 5:d=2 hl=2 l= 92 cons: SEQUENCE
63 > 7:d=3 hl=2 l= 13 cons: SEQUENCE
64 > 9:d=4 hl=2 l= 9 prim: OBJECT :rsaEncryption
65 > 20:d=4 hl=2 l= 0 prim: NULL
66 > 22:d=3 hl=2 l= 75 prim: BIT STRING
67 > 99:d=2 hl=2 l= 0 prim: IA5STRING :
68 > 101:d=1 hl=2 l= 13 cons: SEQUENCE
69 > 103:d=2 hl=2 l= 9 prim: OBJECT :md5withRSAEncryption
70 > 114:d=2 hl=2 l= 0 prim: NULL
71 > 116:d=1 hl=2 l= 65 prim: BIT STRING
72
73 > The first BIT STRING is the public key and the second BIT STRING is 
74 > the signature.
75 > But a public key consists of the public exponent and the modulus. Are 
76 > both numbers in the first BIT STRING?
77 > Is there a document simply describing this coding stuff (checking 
78 > signature, get the public key, etc.)?
79
80 Minimal in SSLeay.  If you want to see what the modulus and exponent are,
81 try asn1parse -offset 25 -length 75 <key.pem
82 asn1parse will currently stuff up on the 'length 75' part (fixed in next 
83 release) but it will print the stuff.  If you are after more 
84 documentation on ASN.1, have a look at www.rsa.com and get their PKCS 
85 documents, most of my initial work on SSLeay was done using them.
86
87 As for SSLeay,
88 util/crypto.num and util/ssl.num are lists of all exported functions in 
89 the library (but not macros :-(.
90
91 The ones for extracting public keys from certificates and certificate 
92 requests are EVP_PKEY *      X509_REQ_extract_key(X509_REQ *req);
93 EVP_PKEY *      X509_extract_key(X509 *x509);
94
95 To verify a signature on a signed ASN.1 object
96 int X509_verify(X509 *a,EVP_PKEY *key);
97 int X509_REQ_verify(X509_REQ *a,EVP_PKEY *key);
98 int X509_CRL_verify(X509_CRL *a,EVP_PKEY *key);
99 int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a,EVP_PKEY *key);
100
101 I should mention that EVP_PKEY can be used to hold a public or a private key,
102 since for  things like RSA and DSS, a public key is just a subset of what 
103 is stored for the private key.
104
105 To sign any of the above structures
106
107 int X509_sign(X509 *a,EVP_PKEY *key,EVP_MD *md);
108 int X509_REQ_sign(X509_REQ *a,EVP_PKEY *key,EVP_MD *md);
109 int X509_CRL_sign(X509_CRL *a,EVP_PKEY *key,EVP_MD *md);
110 int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *a,EVP_PKEY *key,EVP_MD *md);
111
112 where md is the message digest to sign with.
113
114 There are all defined in x509.h and all the _sign and _verify functions are
115 actually macros to the ASN1_sign() and ASN1_verify() functions.
116 These functions will put the correct algorithm identifiers in the correct 
117 places in the structures.
118
119 eric
120 --
121 Eric Young                  | BOOL is tri-state according to Bill Gates.
122 AARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
123
124 ==== verify ========================================================
125
126 X509_verify_cert_chain(
127         CERT_STORE *cert_store,
128         STACK /* X509 */ *certs,
129         int *verify_result,
130         int (*verify_error_callback)()
131         char *argument_to_callback, /* SSL */
132
133 app_verify_callback(
134         char *app_verify_arg, /* from SSL_CTX */
135         STACK /* X509 */ *certs,
136         int *verify_result,
137         int (*verify_error_callback)()
138         SSL *s,
139
140 int X509_verify_cert(
141         CERT_STORE *cert_store,
142         X509 *x509,
143         int *verify_result,
144         int (*verify_error_callback)(),
145         char *arg,
146
147 ==== apps.doc ========================================================
148
149 The applications
150
151 Ok, where to begin....
152 In the begining, when SSLeay was small (April 1995), there
153 were but few applications, they did happily cohabit in
154 the one bin directory.  Then over time, they did multiply and grow,
155 and they started to look like microsoft software; 500k to print 'hello world'.
156 A new approach was needed.  They were coalessed into one 'Monolithic'
157 application, ssleay.  This one program is composed of many programs that
158 can all be compiled independantly.
159
160 ssleay has 3 modes of operation.
161 1) If the ssleay binaray has the name of one of its component programs, it
162 executes that program and then exits.  This can be achieve by using hard or
163 symbolic links, or failing that, just renaming the binary.
164 2) If the first argument to ssleay is the name of one of the component
165 programs, that program runs that program and then exits.
166 3) If there are no arguments, ssleay enters a 'command' mode.  Each line is
167 interpreted as a program name plus arguments.  After each 'program' is run,
168 ssleay returns to the comand line.
169
170 dgst    - message digests
171 enc     - encryption and base64 encoding
172
173 ans1parse - 'pulls' appart ASN.1 encoded objects like certificates.
174
175 dh      - Diffle-Hellman parameter manipulation.
176 rsa     - RSA manipulations.
177 crl     - Certificate revokion list manipulations
178 x509    - X509 cert fiddles, including signing.
179 pkcs7   - pkcs7 manipulation, only DER versions right now.
180
181 genrsa  - generate an RSA private key.
182 gendh   - Generate a set of Diffle-Hellman parameters.
183 req     - Generate a PKCS#10 object, a certificate request.
184
185 s_client - SSL client program
186 s_server - SSL server program
187 s_time   - A SSL protocol timing program
188 s_mult   - Another SSL server, but it multiplexes
189            connections.
190 s_filter - under development
191
192 errstr  - Convert SSLeay error numbers to strings.
193 ca      - Sign certificate requests, and generate
194           certificate revokion lists
195 crl2pkcs7 - put a crl and certifcates into a pkcs7 object.
196 speed   - Benchmark the ciphers.
197 verify  - Check certificates
198 hashdir - under development
199
200 [ there a now a few more options, play with the program to see what they
201   are ]
202
203 ==== asn1.doc ========================================================
204
205 The ASN.1 Routines.
206
207 ASN.1 is a specification for how to encode structured 'data' in binary form.
208 The approach I have take to the manipulation of structures and their encoding
209 into ASN.1 is as follows.
210
211 For each distinct structure there are 4 function of the following form
212 TYPE *TYPE_new(void);
213 void TYPE_free(TYPE *);
214 TYPE *d2i_TYPE(TYPE **a,unsigned char **pp,long length);
215 long i2d_TYPE(TYPE *a,unsigned char **pp);      /* CHECK RETURN VALUE */
216
217 where TYPE is the type of the 'object'.  The TYPE that have these functions
218 can be in one of 2 forms, either the internal C malloc()ed data structure
219 or in the DER (a variant of ASN.1 encoding) binary encoding which is just
220 an array of unsigned bytes.  The 'i2d' functions converts from the internal
221 form to the DER form and the 'd2i' functions convert from the DER form to
222 the internal form.
223
224 The 'new' function returns a malloc()ed version of the structure with all
225 substructures either created or left as NULL pointers.  For 'optional'
226 fields, they are normally left as NULL to indicate no value.  For variable
227 size sub structures (often 'SET OF' or 'SEQUENCE OF' in ASN.1 syntax) the
228 STACK data type is used to hold the values.  Have a read of stack.doc
229 and have a look at the relevant header files to see what I mean.  If there
230 is an error while malloc()ing the structure, NULL is returned.
231
232 The 'free' function will free() all the sub components of a particular
233 structure.  If any of those sub components have been 'removed', replace
234 them with NULL pointers, the 'free' functions are tolerant of NULL fields.
235
236 The 'd2i' function copies a binary representation into a C structure.  It
237 operates as follows.  'a' is a pointer to a pointer to
238 the structure to populate, 'pp' is a pointer to a pointer to where the DER
239 byte string is located and 'length' is the length of the '*pp' data.
240 If there are no errors, a pointer to the populated structure is returned.
241 If there is an error, NULL is returned.  Errors can occur because of
242 malloc() failures but normally they will be due to syntax errors in the DER
243 encoded data being parsed. It is also an error if there was an
244 attempt to read more that 'length' bytes from '*p'.  If
245 everything works correctly, the value in '*p' is updated
246 to point at the location just beyond where the DER
247 structure was read from.  In this way, chained calls to 'd2i' type
248 functions can be made, with the pointer into the 'data' array being
249 'walked' along the input byte array.
250 Depending on the value passed for 'a', different things will be done.  If
251 'a' is NULL, a new structure will be malloc()ed and returned.  If '*a' is
252 NULL, a new structure will be malloc()ed and put into '*a' and returned.
253 If '*a' is not NULL, the structure in '*a' will be populated, or in the
254 case of an error, free()ed and then returned.
255 Having these semantics means that a structure
256 can call a 'd2i' function to populate a field and if the field is currently
257 NULL, the structure will be created.
258
259 The 'i2d' function type is used to copy a C structure to a byte array.
260 The parameter 'a' is the structure to convert and '*p' is where to put it.
261 As for the 'd2i' type structure, 'p' is updated to point after the last
262 byte written.  If p is NULL, no data is written.  The function also returns
263 the number of bytes written.  Where this becomes useful is that if the
264 function is called with a NULL 'p' value, the length is returned.  This can
265 then be used to malloc() an array of bytes and then the same function can
266 be recalled passing the malloced array to be written to. e.g.
267
268 int len;
269 unsigned char *bytes,*p;
270 len=i2d_X509(x,NULL);   /* get the size of the ASN1 encoding of 'x' */
271 if ((bytes=(unsigned char *)malloc(len)) == NULL)
272         goto err;
273 p=bytes;
274 i2d_X509(x,&p);
275
276 Please note that a new variable, 'p' was passed to i2d_X509.  After the
277 call to i2d_X509 p has been incremented by len bytes.
278
279 Now the reason for this functional organisation is that it allows nested
280 structures to be built up by calling these functions as required.  There
281 are various macros used to help write the general 'i2d', 'd2i', 'new' and
282 'free' functions.  They are discussed in another file and would only be
283 used by some-one wanting to add new structures to the library.  As you
284 might be able to guess, the process of writing ASN.1 files can be a bit CPU
285 expensive for complex structures.  I'm willing to live with this since the
286 simpler library code make my life easier and hopefully most programs using
287 these routines will have their execution profiles dominated by cipher or
288 message digest routines.
289 What follows is a list of 'TYPE' values and the corresponding ASN.1
290 structure and where it is used.
291
292 TYPE                    ASN.1
293 ASN1_INTEGER            INTEGER
294 ASN1_BIT_STRING         BIT STRING
295 ASN1_OCTET_STRING       OCTET STRING
296 ASN1_OBJECT             OBJECT IDENTIFIER
297 ASN1_PRINTABLESTRING    PrintableString
298 ASN1_T61STRING          T61String
299 ASN1_IA5STRING          IA5String
300 ASN1_UTCTIME            UTCTime
301 ASN1_TYPE               Any of the above mentioned types plus SEQUENCE and SET
302
303 Most of the above mentioned types are actualled stored in the
304 ASN1_BIT_STRING type and macros are used to differentiate between them.
305 The 3 types used are
306
307 typedef struct asn1_object_st
308         {
309         /* both null if a dynamic ASN1_OBJECT, one is
310          * defined if a 'static' ASN1_OBJECT */
311         char *sn,*ln;
312         int nid;
313         int length;
314         unsigned char *data;
315         } ASN1_OBJECT;
316 This is used to store ASN1 OBJECTS.  Read 'objects.doc' for details ono
317 routines to manipulate this structure.  'sn' and 'ln' are used to hold text
318 strings that represent the object (short name and long or lower case name).
319 These are used by the 'OBJ' library.  'nid' is a number used by the OBJ
320 library to uniquely identify objects.  The ASN1 routines will populate the
321 'length' and 'data' fields which will contain the bit string representing
322 the object.
323
324 typedef struct asn1_bit_string_st
325         {
326         int length;
327         int type;
328         unsigned char *data;
329         } ASN1_BIT_STRING;
330 This structure is used to hold all the other base ASN1 types except for
331 ASN1_UTCTIME (which is really just a 'char *').  Length is the number of
332 bytes held in data and type is the ASN1 type of the object (there is a list
333 in asn1.h).
334
335 typedef struct asn1_type_st
336         {
337         int type;
338         union   {
339                 char *ptr;
340                 ASN1_INTEGER *          integer;
341                 ASN1_BIT_STRING *       bit_string;
342                 ASN1_OCTET_STRING *     octet_string;
343                 ASN1_OBJECT *           object;
344                 ASN1_PRINTABLESTRING *  printablestring;
345                 ASN1_T61STRING *        t61string;
346                 ASN1_IA5STRING *        ia5string;
347                 ASN1_UTCTIME *          utctime;
348                 ASN1_BIT_STRING *       set;
349                 ASN1_BIT_STRING *       sequence;
350                 } value;
351         } ASN1_TYPE;
352 This structure is used in a few places when 'any' type of object can be
353 expected.
354
355 X509                    Certificate
356 X509_CINF               CertificateInfo
357 X509_ALGOR              AlgorithmIdentifier
358 X509_NAME               Name                    
359 X509_NAME_ENTRY         A single sub component of the name.
360 X509_VAL                Validity
361 X509_PUBKEY             SubjectPublicKeyInfo
362 The above mentioned types are declared in x509.h. They are all quite
363 straight forward except for the X509_NAME/X509_NAME_ENTRY pair.
364 A X509_NAME is a STACK (see stack.doc) of X509_NAME_ENTRY's.
365 typedef struct X509_name_entry_st
366         {
367         ASN1_OBJECT *object;
368         ASN1_BIT_STRING *value;
369         int set;
370         int size;       /* temp variable */
371         } X509_NAME_ENTRY;
372 The size is a temporary variable used by i2d_NAME and set is the set number
373 for the particular NAME_ENTRY.  A X509_NAME is encoded as a sequence of
374 sequence of sets.  Normally each set contains only a single item.
375 Sometimes it contains more.  Normally throughout this library there will be
376 only one item per set.  The set field contains the 'set' that this entry is
377 a member of.  So if you have just created a X509_NAME structure and
378 populated it with X509_NAME_ENTRYs, you should then traverse the X509_NAME
379 (which is just a STACK) and set the 'set/' field to incrementing numbers.
380 For more details on why this is done, read the ASN.1 spec for Distinguished
381 Names.
382
383 X509_REQ                CertificateRequest
384 X509_REQ_INFO           CertificateRequestInfo
385 These are used to hold certificate requests.
386
387 X509_CRL                CertificateRevocationList
388 These are used to hold a certificate revocation list
389
390 RSAPrivateKey           PrivateKeyInfo
391 RSAPublicKey            PublicKeyInfo
392 Both these 'function groups' operate on 'RSA' structures (see rsa.doc).
393 The difference is that the RSAPublicKey operations only manipulate the m
394 and e fields in the RSA structure.
395
396 DSAPrivateKey           DSS private key
397 DSAPublicKey            DSS public key
398 Both these 'function groups' operate on 'DSS' structures (see dsa.doc).
399 The difference is that the RSAPublicKey operations only manipulate the 
400 XXX fields in the DSA structure.
401
402 DHparams                DHParameter
403 This is used to hold the p and g value for The Diffie-Hellman operation.
404 The function deal with the 'DH' strucure (see dh.doc).
405
406 Now all of these function types can be used with several other functions to give
407 quite useful set of general manipulation routines.  Normally one would
408 not uses these functions directly but use them via macros. 
409
410 char *ASN1_dup(int (*i2d)(),char *(*d2i)(),char *x);
411 'x' is the input structure case to a 'char *', 'i2d' is the 'i2d_TYPE'
412 function for the type that 'x' is and d2i is the 'd2i_TYPE' function for the
413 type that 'x' is.  As is obvious from the parameters, this function
414 duplicates the strucutre by transforming it into the DER form and then
415 re-loading it into a new strucutre and returning the new strucutre.  This
416 is obviously a bit cpu intensive but when faced with a complex dynamic
417 structure this is the simplest programming approach.  There are macros for
418 duplicating the major data types but is simple to add extras.
419
420 char *ASN1_d2i_fp(char *(*new)(),char *(*d2i)(),FILE *fp,unsigned char **x);
421 'x' is a pointer to a pointer of the 'desired type'.  new and d2i are the
422 corresponding 'TYPE_new' and 'd2i_TYPE' functions for the type and 'fp' is
423 an open file pointer to read from.  This function reads from 'fp' as much
424 data as it can and then uses 'd2i' to parse the bytes to load and return
425 the parsed strucutre in 'x' (if it was non-NULL) and to actually return the
426 strucutre.  The behavior of 'x' is as per all the other d2i functions.
427
428 char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
429 The 'BIO' is the new IO type being used in SSLeay (see bio.doc).  This
430 function is the same as ASN1_d2i_fp() except for the BIO argument.
431 ASN1_d2i_fp() actually calls this function.
432
433 int ASN1_i2d_fp(int (*i2d)(),FILE *out,unsigned char *x);
434 'x' is converted to bytes by 'i2d' and then written to 'out'.  ASN1_i2d_fp
435 and ASN1_d2i_fp are not really symetric since ASN1_i2d_fp will read all
436 available data from the file pointer before parsing a single item while
437 ASN1_i2d_fp can be used to write a sequence of data objects.  To read a
438 series of objects from a file I would sugest loading the file into a buffer
439 and calling the relevent 'd2i' functions.
440
441 char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
442 This function is the same as ASN1_i2d_fp() except for the BIO argument.
443 ASN1_i2d_fp() actually calls this function.
444
445 char *  PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
446 This function will read the next PEM encoded (base64) object of the same
447 type as 'x' (loaded by the d2i function).  'name' is the name that is in
448 the '-----BEGIN name-----' that designates the start of that object type.
449 If the data is encrypted, 'cb' will be called to prompt for a password.  If
450 it is NULL a default function will be used to prompt from the password.
451 'x' is delt with as per the standard 'd2i' function interface.  This
452 function can be used to read a series of objects from a file.  While any
453 data type can be encrypted (see PEM_ASN1_write) only RSA private keys tend
454 to be encrypted.
455
456 char *  PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *fp,
457         char **x,int (*cb)());
458 Same as PEM_ASN1_read() except using a BIO.  This is called by
459 PEM_ASN1_read().
460
461 int     PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,EVP_CIPHER *enc,
462                 unsigned char *kstr,int klen,int (*callback)());
463
464 int     PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *fp,
465                 char *x,EVP_CIPHER *enc,unsigned char *kstr,int klen,
466                 int (*callback)());
467
468 int ASN1_sign(int (*i2d)(), X509_ALGOR *algor1, X509_ALGOR *algor2,
469         ASN1_BIT_STRING *signature, char *data, RSA *rsa, EVP_MD *type);
470 int ASN1_verify(int (*i2d)(), X509_ALGOR *algor1,
471         ASN1_BIT_STRING *signature,char *data, RSA *rsa);
472
473 int ASN1_BIT_STRING_cmp(ASN1_BIT_STRING *a, ASN1_BIT_STRING *b);
474 ASN1_BIT_STRING *ASN1_BIT_STRING_type_new(int type );
475
476 int ASN1_UTCTIME_check(ASN1_UTCTIME *a);
477 void ASN1_UTCTIME_print(BIO *fp,ASN1_UTCTIME *a);
478 ASN1_UTCTIME *ASN1_UTCTIME_dup(ASN1_UTCTIME *a);
479
480 ASN1_BIT_STRING *d2i_asn1_print_type(ASN1_BIT_STRING **a,unsigned char **pp,
481                 long length,int type);
482
483 int             i2d_ASN1_SET(STACK *a, unsigned char **pp,
484                         int (*func)(), int ex_tag, int ex_class);
485 STACK *         d2i_ASN1_SET(STACK **a, unsigned char **pp, long length,
486                         char *(*func)(), int ex_tag, int ex_class);
487
488 int i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *object);
489 int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
490 int a2i_ASN1_INTEGER(BIO *bp,ASN1_INTEGER *bs,char *buf,int size);
491
492 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
493 long ASN1_INTEGER_get(ASN1_INTEGER *a);
494 ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
495 BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
496
497 /* given a string, return the correct type.  Max is the maximum number
498  * of bytes to parse.  It stops parsing when 'max' bytes have been
499  * processed or a '\0' is hit */
500 int ASN1_PRINTABLE_type(unsigned char *s,int max);
501
502 void ASN1_parse(BIO *fp,unsigned char *pp,long len);
503
504 int i2d_ASN1_bytes(ASN1_BIT_STRING *a, unsigned char **pp, int tag, int class);
505 ASN1_BIT_STRING *d2i_ASN1_bytes(ASN1_OCTET_STRING **a, unsigned char **pp,
506         long length, int Ptag, int Pclass);
507
508 /* PARSING */
509 int asn1_Finish(ASN1_CTX *c);
510
511 /* SPECIALS */
512 int ASN1_get_object(unsigned char **pp, long *plength, int *ptag,
513         int *pclass, long omax);
514 int ASN1_check_infinite_end(unsigned char **p,long len);
515 void ASN1_put_object(unsigned char **pp, int constructed, int length,
516         int tag, int class);
517 int ASN1_object_size(int constructed, int length, int tag);
518
519 X509 *  X509_get_cert(CERTIFICATE_CTX *ctx,X509_NAME * name,X509 *tmp_x509);
520 int     X509_add_cert(CERTIFICATE_CTX *ctx,X509 *);
521
522 char *  X509_cert_verify_error_string(int n);
523 int     X509_add_cert_file(CERTIFICATE_CTX *c,char *file, int type);
524 char *  X509_gmtime (char *s, long adj);
525 int     X509_add_cert_dir (CERTIFICATE_CTX *c,char *dir, int type);
526 int     X509_load_verify_locations (CERTIFICATE_CTX *ctx,
527                 char *file_env, char *dir_env);
528 int     X509_set_default_verify_paths(CERTIFICATE_CTX *cts);
529 X509 *  X509_new_D2i_X509(int len, unsigned char *p);
530 char *  X509_get_default_cert_area(void );
531 char *  X509_get_default_cert_dir(void );
532 char *  X509_get_default_cert_file(void );
533 char *  X509_get_default_cert_dir_env(void );
534 char *  X509_get_default_cert_file_env(void );
535 char *  X509_get_default_private_dir(void );
536 X509_REQ *X509_X509_TO_req(X509 *x, RSA *rsa);
537 int     X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)()); 
538
539 CERTIFICATE_CTX *CERTIFICATE_CTX_new();
540 void CERTIFICATE_CTX_free(CERTIFICATE_CTX *c);
541
542 void X509_NAME_print(BIO *fp, X509_NAME *name, int obase);
543 int             X509_print_fp(FILE *fp,X509 *x);
544 int             X509_print(BIO *fp,X509 *x);
545
546 X509_INFO *     X509_INFO_new(void);
547 void            X509_INFO_free(X509_INFO *a);
548
549 char *          X509_NAME_oneline(X509_NAME *a);
550
551 #define X509_verify(x,rsa)
552 #define X509_REQ_verify(x,rsa)
553 #define X509_CRL_verify(x,rsa)
554
555 #define X509_sign(x,rsa,md)
556 #define X509_REQ_sign(x,rsa,md)
557 #define X509_CRL_sign(x,rsa,md)
558
559 #define X509_dup(x509)
560 #define d2i_X509_fp(fp,x509)
561 #define i2d_X509_fp(fp,x509)
562 #define d2i_X509_bio(bp,x509)
563 #define i2d_X509_bio(bp,x509)
564
565 #define X509_CRL_dup(crl)
566 #define d2i_X509_CRL_fp(fp,crl)
567 #define i2d_X509_CRL_fp(fp,crl)
568 #define d2i_X509_CRL_bio(bp,crl)
569 #define i2d_X509_CRL_bio(bp,crl)
570
571 #define X509_REQ_dup(req)
572 #define d2i_X509_REQ_fp(fp,req)
573 #define i2d_X509_REQ_fp(fp,req)
574 #define d2i_X509_REQ_bio(bp,req)
575 #define i2d_X509_REQ_bio(bp,req)
576
577 #define RSAPrivateKey_dup(rsa)
578 #define d2i_RSAPrivateKey_fp(fp,rsa)
579 #define i2d_RSAPrivateKey_fp(fp,rsa)
580 #define d2i_RSAPrivateKey_bio(bp,rsa)
581 #define i2d_RSAPrivateKey_bio(bp,rsa)
582
583 #define X509_NAME_dup(xn)
584 #define X509_NAME_ENTRY_dup(ne)
585
586 void X509_REQ_print_fp(FILE *fp,X509_REQ *req);
587 void X509_REQ_print(BIO *fp,X509_REQ *req);
588
589 RSA *X509_REQ_extract_key(X509_REQ *req);
590 RSA *X509_extract_key(X509 *x509);
591
592 int             X509_issuer_and_serial_cmp(X509 *a, X509 *b);
593 unsigned long   X509_issuer_and_serial_hash(X509 *a);
594
595 X509_NAME *     X509_get_issuer_name(X509 *a);
596 int             X509_issuer_name_cmp(X509 *a, X509 *b);
597 unsigned long   X509_issuer_name_hash(X509 *a);
598
599 X509_NAME *     X509_get_subject_name(X509 *a);
600 int             X509_subject_name_cmp(X509 *a,X509 *b);
601 unsigned long   X509_subject_name_hash(X509 *x);
602
603 int             X509_NAME_cmp (X509_NAME *a, X509_NAME *b);
604 unsigned long   X509_NAME_hash(X509_NAME *x);
605
606
607 ==== bio.doc ========================================================
608
609 BIO Routines
610
611 This documentation is rather sparse, you are probably best 
612 off looking at the code for specific details.
613
614 The BIO library is a IO abstraction that was originally 
615 inspired by the need to have callbacks to perform IO to FILE 
616 pointers when using Windows 3.1 DLLs.  There are two types 
617 of BIO; a source/sink type and a filter type.
618 The source/sink methods are as follows:
619 -       BIO_s_mem()  memory buffer - a read/write byte array that
620         grows until memory runs out :-).
621 -       BIO_s_file()  FILE pointer - A wrapper around the normal 
622         'FILE *' commands, good for use with stdin/stdout.
623 -       BIO_s_fd()  File descriptor - A wrapper around file 
624         descriptors, often used with pipes.
625 -       BIO_s_socket()  Socket - Used around sockets.  It is 
626         mostly in the Microsoft world that sockets are different 
627         from file descriptors and there are all those ugly winsock 
628         commands.
629 -       BIO_s_null()  Null - read nothing and write nothing.; a 
630         useful endpoint for filter type BIO's specifically things 
631         like the message digest BIO.
632
633 The filter types are
634 -       BIO_f_buffer()  IO buffering - does output buffering into 
635         larger chunks and performs input buffering to allow gets() 
636         type functions.
637 -       BIO_f_md()  Message digest - a transparent filter that can 
638         be asked to return a message digest for the data that has 
639         passed through it.
640 -       BIO_f_cipher()  Encrypt or decrypt all data passing 
641         through the filter.
642 -       BIO_f_base64()  Base64 decode on read and encode on write.
643 -       BIO_f_ssl()  A filter that performs SSL encryption on the 
644         data sent through it.
645
646 Base BIO functions.
647 The BIO library has a set of base functions that are 
648 implemented for each particular type.  Filter BIOs will 
649 normally call the equivalent function on the source/sink BIO 
650 that they are layered on top of after they have performed 
651 some modification to the data stream.  Multiple filter BIOs 
652 can be 'push' into a stack of modifers, so to read from a 
653 file, unbase64 it, then decrypt it, a BIO_f_cipher, 
654 BIO_f_base64 and a BIO_s_file would probably be used.  If a 
655 sha-1 and md5 message digest needed to be generated, a stack 
656 two BIO_f_md() BIOs and a BIO_s_null() BIO could be used.
657 The base functions are
658 -       BIO *BIO_new(BIO_METHOD *type); Create  a new BIO of  type 'type'.
659 -       int BIO_free(BIO *a); Free a BIO structure.  Depending on 
660         the configuration, this will free the underlying data 
661         object for a source/sink BIO.
662 -       int BIO_read(BIO *b, char *data, int len); Read upto 'len' 
663         bytes into 'data'. 
664 -       int BIO_gets(BIO *bp,char *buf, int size); Depending on 
665         the BIO, this can either be a 'get special' or a get one 
666         line of data, as per fgets();
667 -       int BIO_write(BIO *b, char *data, int len); Write 'len' 
668         bytes from 'data' to the 'b' BIO.
669 -       int BIO_puts(BIO *bp,char *buf); Either a 'put special' or 
670         a write null terminated string as per fputs().
671 -       long BIO_ctrl(BIO *bp,int cmd,long larg,char *parg);  A 
672         control function which is used to manipulate the BIO 
673         structure and modify it's state and or report on it.  This 
674         function is just about never used directly, rather it 
675         should be used in conjunction with BIO_METHOD specific 
676         macros.
677 -       BIO *BIO_push(BIO *new_top, BIO *old); new_top is apped to the
678         top of the 'old' BIO list.  new_top should be a filter BIO.
679         All writes will go through 'new_top' first and last on read.
680         'old' is returned.
681 -       BIO *BIO_pop(BIO *bio); the new topmost BIO is returned, NULL if
682         there are no more.
683
684 If a particular low level BIO method is not supported 
685 (normally BIO_gets()), -2 will be returned if that method is 
686 called.  Otherwise the IO methods (read, write, gets, puts) 
687 will return the number of bytes read or written, and 0 or -1 
688 for error (or end of input).  For the -1 case, 
689 BIO_should_retry(bio) can be called to determine if it was a 
690 genuine error or a temporary problem.  -2 will also be 
691 returned if the BIO has not been initalised yet, in all 
692 cases, the correct error codes are set (accessible via the 
693 ERR library).
694
695
696 The following functions are convenience functions:
697 -       int BIO_printf(BIO *bio, char * format, ..);  printf but 
698         to a BIO handle.
699 -       long BIO_ctrl_int(BIO *bp,int cmd,long larg,int iarg); a 
700         convenience function to allow a different argument types 
701         to be passed to BIO_ctrl().
702 -       int BIO_dump(BIO *b,char *bytes,int len); output 'len' 
703         bytes from 'bytes' in a hex dump debug format.
704 -       long BIO_debug_callback(BIO *bio, int cmd, char *argp, int 
705         argi, long argl, long ret) - a default debug BIO callback, 
706         this is mentioned below.  To use this one normally has to 
707         use the BIO_set_callback_arg() function to assign an 
708         output BIO for the callback to use.
709 -       BIO *BIO_find_type(BIO *bio,int type); when there is a 'stack'
710         of BIOs, this function scan the list and returns the first
711         that is of type 'type', as listed in buffer.h under BIO_TYPE_XXX.
712 -       void BIO_free_all(BIO *bio); Free the bio and all other BIOs
713         in the list.  It walks the bio->next_bio list.
714
715
716
717 Extra commands are normally implemented as macros calling BIO_ctrl().
718 -       BIO_number_read(BIO *bio) - the number of bytes processed 
719         by BIO_read(bio,.).
720 -       BIO_number_written(BIO *bio) - the number of bytes written 
721         by BIO_write(bio,.).
722 -       BIO_reset(BIO *bio) - 'reset' the BIO.
723 -       BIO_eof(BIO *bio) - non zero if we are at the current end 
724         of input.
725 -       BIO_set_close(BIO *bio, int close_flag) - set the close flag.
726 -       BIO_get_close(BIO *bio) - return the close flag.
727         BIO_pending(BIO *bio) - return the number of bytes waiting 
728         to be read (normally buffered internally).
729 -       BIO_flush(BIO *bio) - output any data waiting to be output.
730 -       BIO_should_retry(BIO *io) - after a BIO_read/BIO_write 
731         operation returns 0 or -1, a call to this function will 
732         return non zero if you should retry the call later (this 
733         is for non-blocking IO).
734 -       BIO_should_read(BIO *io) - we should retry when data can 
735         be read.
736 -       BIO_should_write(BIO *io) - we should retry when data can 
737         be written.
738 -       BIO_method_name(BIO *io) - return a string for the method name.
739 -       BIO_method_type(BIO *io) - return the unique ID of the BIO method.
740 -       BIO_set_callback(BIO *io,  long (*callback)(BIO *io, int 
741         cmd, char *argp, int argi, long argl, long ret); - sets 
742         the debug callback.
743 -       BIO_get_callback(BIO *io) - return the assigned function 
744         as mentioned above.
745 -       BIO_set_callback_arg(BIO *io, char *arg)  - assign some 
746         data against the BIO.  This is normally used by the debug 
747         callback but could in reality be used for anything.  To 
748         get an idea of how all this works, have a look at the code 
749         in the default debug callback mentioned above.  The 
750         callback can modify the return values.
751
752 Details of the BIO_METHOD structure.
753 typedef struct bio_method_st
754         {
755         int type;
756         char *name;
757         int (*bwrite)();
758         int (*bread)();
759         int (*bputs)();
760         int (*bgets)();
761         long (*ctrl)();
762         int (*create)();
763         int (*destroy)();
764         } BIO_METHOD;
765
766 The 'type' is the numeric type of the BIO, these are listed in buffer.h;
767 'Name' is a textual representation of the BIO 'type'.
768 The 7 function pointers point to the respective function 
769 methods, some of which can be NULL if not implemented.
770 The BIO structure
771 typedef struct bio_st
772         {
773         BIO_METHOD *method;
774         long (*callback)(BIO * bio, int mode, char *argp, int 
775                 argi, long argl, long ret);
776         char *cb_arg; /* first argument for the callback */
777         int init;
778         int shutdown;
779         int flags;      /* extra storage */
780         int num;
781         char *ptr;
782         struct bio_st *next_bio; /* used by filter BIOs */
783         int references;
784         unsigned long num_read;
785         unsigned long num_write;
786         } BIO;
787
788 -       'Method' is the BIO method.
789 -       'callback', when configured, is called before and after 
790         each BIO method is called for that particular BIO.  This 
791         is intended primarily for debugging and of informational feedback.
792 -       'init' is 0 when the BIO can be used for operation.  
793         Often, after a BIO is created, a number of operations may 
794         need to be performed before it is available for use.  An 
795         example is for BIO_s_sock().  A socket needs to be 
796         assigned to the BIO before it can be used.
797 -       'shutdown', this flag indicates if the underlying 
798         comunication primative being used should be closed/freed 
799         when the BIO is closed.
800 -       'flags' is used to hold extra state.  It is primarily used 
801         to hold information about why a non-blocking operation 
802         failed and to record startup protocol information for the 
803         SSL BIO.
804 -       'num' and 'ptr' are used to hold instance specific state 
805         like file descriptors or local data structures.
806 -       'next_bio' is used by filter BIOs to hold the pointer of the
807         next BIO in the chain. written data is sent to this BIO and
808         data read is taken from it.
809 -       'references' is used to indicate the number of pointers to 
810         this structure.  This needs to be '1' before a call to 
811         BIO_free() is made if the BIO_free() function is to 
812         actually free() the structure, otherwise the reference 
813         count is just decreased.  The actual BIO subsystem does 
814         not really use this functionality but it is useful when 
815         used in more advanced applicaion.
816 -       num_read and num_write are the total number of bytes 
817         read/written via the 'read()' and 'write()' methods.
818
819 BIO_ctrl operations.
820 The following is the list of standard commands passed as the 
821 second parameter to BIO_ctrl() and should be supported by 
822 all BIO as best as possible.  Some are optional, some are 
823 manditory, in any case, where is makes sense, a filter BIO 
824 should pass such requests to underlying BIO's.
825 -       BIO_CTRL_RESET  - Reset the BIO back to an initial state.
826 -       BIO_CTRL_EOF    - return 0 if we are not at the end of input, 
827         non 0 if we are.
828 -       BIO_CTRL_INFO   - BIO specific special command, normal
829         information return.
830 -       BIO_CTRL_SET    - set IO specific parameter.
831 -       BIO_CTRL_GET    - get IO specific parameter.
832 -       BIO_CTRL_GET_CLOSE - Get the close on BIO_free() flag, one 
833         of BIO_CLOSE or BIO_NOCLOSE.
834 -       BIO_CTRL_SET_CLOSE - Set the close on BIO_free() flag.
835 -       BIO_CTRL_PENDING - Return the number of bytes available 
836         for instant reading
837 -       BIO_CTRL_FLUSH  - Output pending data, return number of bytes output.
838 -       BIO_CTRL_SHOULD_RETRY - After an IO error (-1 returned) 
839         should we 'retry' when IO is possible on the underlying IO object.
840 -       BIO_CTRL_RETRY_TYPE - What kind of IO are we waiting on.
841
842 The following command is a special BIO_s_file() specific option.
843 -       BIO_CTRL_SET_FILENAME - specify a file to open for IO.
844
845 The BIO_CTRL_RETRY_TYPE needs a little more explanation.  
846 When performing non-blocking IO, or say reading on a memory 
847 BIO, when no data is present (or cannot be written), 
848 BIO_read() and/or BIO_write() will return -1.  
849 BIO_should_retry(bio) will return true if this is due to an 
850 IO condition rather than an actual error.  In the case of 
851 BIO_s_mem(), a read when there is no data will return -1 and 
852 a should retry when there is more 'read' data.
853 The retry type is deduced from 2 macros
854 BIO_should_read(bio) and BIO_should_write(bio).
855 Now while it may appear obvious that a BIO_read() failure 
856 should indicate that a retry should be performed when more 
857 read data is available, this is often not true when using 
858 things like an SSL BIO.  During the SSL protocol startup 
859 multiple reads and writes are performed, triggered by any 
860 SSL_read or SSL_write.
861 So to write code that will transparently handle either a 
862 socket or SSL BIO,
863         i=BIO_read(bio,..)
864         if (I == -1)
865                 {
866                 if (BIO_should_retry(bio))
867                         {
868                         if (BIO_should_read(bio))
869                                 {
870                                 /* call us again when BIO can be read */
871                                 }
872                         if (BIO_should_write(bio))
873                                 {
874                                 /* call us again when BIO can be written */
875                                 }
876                         }
877                 }
878
879 At this point in time only read and write conditions can be 
880 used but in the future I can see the situation for other 
881 conditions, specifically with SSL there could be a condition 
882 of a X509 certificate lookup taking place and so the non-
883 blocking BIO_read would require a retry when the certificate 
884 lookup subsystem has finished it's lookup.  This is all 
885 makes more sense and is easy to use in a event loop type 
886 setup.
887 When using the SSL BIO, either SSL_read() or SSL_write()s 
888 can be called during the protocol startup and things will 
889 still work correctly.
890 The nice aspect of the use of the BIO_should_retry() macro 
891 is that all the errno codes that indicate a non-fatal error 
892 are encapsulated in one place.  The Windows specific error 
893 codes and WSAGetLastError() calls are also hidden from the 
894 application.
895
896 Notes on each BIO method.
897 Normally buffer.h is just required but depending on the 
898 BIO_METHOD, ssl.h or evp.h will also be required.
899
900 BIO_METHOD *BIO_s_mem(void);
901 -       BIO_set_mem_buf(BIO *bio, BUF_MEM *bm, int close_flag) - 
902         set the underlying BUF_MEM structure for the BIO to use.
903 -       BIO_get_mem_ptr(BIO *bio, char **pp) - if pp is not NULL, 
904         set it to point to the memory array and return the number 
905         of bytes available.
906 A read/write BIO.  Any data written is appended to the 
907 memory array and any read is read from the front.  This BIO 
908 can be used for read/write at the same time. BIO_gets() is 
909 supported in the fgets() sense.
910 BIO_CTRL_INFO can be used to retrieve pointers to the memory 
911 buffer and it's length.
912
913 BIO_METHOD *BIO_s_file(void);
914 -       BIO_set_fp(BIO *bio, FILE *fp, int close_flag) - set 'FILE *' to use.
915 -       BIO_get_fp(BIO *bio, FILE **fp) - get the 'FILE *' in use.
916 -       BIO_read_filename(BIO *bio, char *name) - read from file.
917 -       BIO_write_filename(BIO *bio, char *name) - write to file.
918 -       BIO_append_filename(BIO *bio, char *name) - append to file.
919 This BIO sits over the normal system fread()/fgets() type 
920 functions. Gets() is supported.  This BIO in theory could be 
921 used for read and write but it is best to think of each BIO 
922 of this type as either a read or a write BIO, not both.
923
924 BIO_METHOD *BIO_s_socket(void);
925 BIO_METHOD *BIO_s_fd(void);
926 -       BIO_sock_should_retry(int i) - the underlying function 
927         used to determine if a call should be retried; the 
928         argument is the '0' or '-1' returned by the previous BIO 
929         operation.
930 -       BIO_fd_should_retry(int i) - same as the 
931 -       BIO_sock_should_retry() except that it is different internally.
932 -       BIO_set_fd(BIO *bio, int fd, int close_flag) - set the 
933         file descriptor to use
934 -       BIO_get_fd(BIO *bio, int *fd) - get the file descriptor.
935 These two methods are very similar.  Gets() is not 
936 supported, if you want this functionality, put a 
937 BIO_f_buffer() onto it.  This BIO is bi-directional if the 
938 underlying file descriptor is.  This is normally the case 
939 for sockets but not the case for stdio descriptors.
940
941 BIO_METHOD *BIO_s_null(void);
942 Read and write as much data as you like, it all disappears 
943 into this BIO.
944
945 BIO_METHOD *BIO_f_buffer(void);
946 -       BIO_get_buffer_num_lines(BIO *bio) - return the number of 
947         complete lines in the buffer.
948 -       BIO_set_buffer_size(BIO *bio, long size) - set the size of 
949         the buffers.
950 This type performs input and output buffering.  It performs 
951 both at the same time.  The size of the buffer can be set 
952 via the set buffer size option.  Data buffered for output is 
953 only written when the buffer fills.
954
955 BIO_METHOD *BIO_f_ssl(void);
956 -       BIO_set_ssl(BIO *bio, SSL *ssl, int close_flag) - the SSL 
957         structure to use.
958 -       BIO_get_ssl(BIO *bio, SSL **ssl) - get the SSL structure 
959         in use.
960 The SSL bio is a little different from normal BIOs because 
961 the underlying SSL structure is a little different.  A SSL 
962 structure performs IO via a read and write BIO.  These can 
963 be different and are normally set via the
964 SSL_set_rbio()/SSL_set_wbio() calls.  The SSL_set_fd() calls 
965 are just wrappers that create socket BIOs and then call 
966 SSL_set_bio() where the read and write BIOs are the same.  
967 The BIO_push() operation makes the SSLs IO BIOs the same, so 
968 make sure the BIO pushed is capable of two directional 
969 traffic.  If it is not, you will have to install the BIOs 
970 via the more conventional SSL_set_bio() call.  BIO_pop() will retrieve
971 the 'SSL read' BIO.
972
973 BIO_METHOD *BIO_f_md(void);
974 -       BIO_set_md(BIO *bio, EVP_MD *md) - set the message digest 
975         to use.
976 -       BIO_get_md(BIO *bio, EVP_MD **mdp) - return the digest 
977         method in use in mdp, return 0 if not set yet.
978 -       BIO_reset() reinitializes the digest (EVP_DigestInit()) 
979         and passes the reset to the underlying BIOs.
980 All data read or written via BIO_read() or BIO_write() to 
981 this BIO will be added to the calculated digest.  This 
982 implies that this BIO is only one directional.  If read and 
983 write operations are performed, two separate BIO_f_md() BIOs 
984 are reuqired to generate digests on both the input and the 
985 output.  BIO_gets(BIO *bio, char *md, int size) will place the 
986 generated digest into 'md' and return the number of bytes.  
987 The EVP_MAX_MD_SIZE should probably be used to size the 'md' 
988 array.  Reading the digest will also reset it.
989
990 BIO_METHOD *BIO_f_cipher(void);
991 -       BIO_reset() reinitializes the cipher.
992 -       BIO_flush() should be called when the last bytes have been 
993         output to flush the final block of block ciphers.
994 -       BIO_get_cipher_status(BIO *b), when called after the last 
995         read from a cipher BIO, returns non-zero if the data 
996         decrypted correctly, otherwise, 0.
997 -       BIO_set_cipher(BIO *b, EVP_CIPHER *c, unsigned char *key, 
998         unsigned char *iv, int encrypt)   This function is used to 
999         setup a cipher BIO.  The length of key and iv are 
1000         specified by the choice of EVP_CIPHER.  Encrypt is 1 to 
1001         encrypt and 0 to decrypt.
1002
1003 BIO_METHOD *BIO_f_base64(void);
1004 -       BIO_flush() should be called when the last bytes have been output.
1005 This BIO base64 encodes when writing and base64 decodes when 
1006 reading.  It will scan the input until a suitable begin line 
1007 is found.  After reading data, BIO_reset() will reset the 
1008 BIO to start scanning again.  Do not mix reading and writing 
1009 on the same base64 BIO.  It is meant as a single stream BIO.
1010
1011 Directions      type
1012 both            BIO_s_mem()
1013 one/both        BIO_s_file()
1014 both            BIO_s_fd()
1015 both            BIO_s_socket() 
1016 both            BIO_s_null()
1017 both            BIO_f_buffer()
1018 one             BIO_f_md()  
1019 one             BIO_f_cipher()  
1020 one             BIO_f_base64()  
1021 both            BIO_f_ssl()
1022
1023 It is easy to mix one and two directional BIOs, all one has 
1024 to do is to keep two separate BIO pointers for reading and 
1025 writing and be careful about usage of underlying BIOs.  The 
1026 SSL bio by it's very nature has to be two directional but 
1027 the BIO_push() command will push the one BIO into the SSL 
1028 BIO for both reading and writing.
1029
1030 The best example program to look at is apps/enc.c and/or perhaps apps/dgst.c.
1031
1032
1033 ==== blowfish.doc ========================================================
1034
1035 The Blowfish library.
1036
1037 Blowfish is a block cipher that operates on 64bit (8 byte) quantities.  It
1038 uses variable size key, but 128bit (16 byte) key would normally be considered
1039 good.  It can be used in all the modes that DES can be used.  This
1040 library implements the ecb, cbc, cfb64, ofb64 modes.
1041
1042 Blowfish is quite a bit faster that DES, and much faster than IDEA or
1043 RC2.  It is one of the faster block ciphers.
1044
1045 For all calls that have an 'input' and 'output' variables, they can be the
1046 same.
1047
1048 This library requires the inclusion of 'blowfish.h'.
1049
1050 All of the encryption functions take what is called an BF_KEY as an 
1051 argument.  An BF_KEY is an expanded form of the Blowfish key.
1052 For all modes of the Blowfish algorithm, the BF_KEY used for
1053 decryption is the same one that was used for encryption.
1054
1055 The define BF_ENCRYPT is passed to specify encryption for the functions
1056 that require an encryption/decryption flag. BF_DECRYPT is passed to
1057 specify decryption.
1058
1059 Please note that any of the encryption modes specified in my DES library
1060 could be used with Blowfish.  I have only implemented ecb, cbc, cfb64 and
1061 ofb64 for the following reasons.
1062 - ecb is the basic Blowfish encryption.
1063 - cbc is the normal 'chaining' form for block ciphers.
1064 - cfb64 can be used to encrypt single characters, therefore input and output
1065   do not need to be a multiple of 8.
1066 - ofb64 is similar to cfb64 but is more like a stream cipher, not as
1067   secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
1068 - If you want triple Blowfish, thats 384 bits of key and you must be totally
1069   obsessed with security.  Still, if you want it, it is simple enough to
1070   copy the function from the DES library and change the des_encrypt to
1071   BF_encrypt; an exercise left for the paranoid reader :-).
1072
1073 The functions are as follows:
1074
1075 void BF_set_key(
1076 BF_KEY *ks;
1077 int len;
1078 unsigned char *key;
1079         BF_set_key converts an 'len' byte key into a BF_KEY.
1080         A 'ks' is an expanded form of the 'key' which is used to
1081         perform actual encryption.  It can be regenerated from the Blowfish key
1082         so it only needs to be kept when encryption or decryption is about
1083         to occur.  Don't save or pass around BF_KEY's since they
1084         are CPU architecture dependent, 'key's are not.  Blowfish is an
1085         interesting cipher in that it can be used with a variable length
1086         key.  'len' is the length of 'key' to be used as the key.
1087         A 'len' of 16 is recomended by me, but blowfish can use upto
1088         72 bytes.  As a warning, blowfish has a very very slow set_key
1089         function, it actually runs BF_encrypt 521 times.
1090         
1091 void BF_encrypt(unsigned long *data, BF_KEY *key);
1092 void BF_decrypt(unsigned long *data, BF_KEY *key);
1093         These are the Blowfish encryption function that gets called by just
1094         about every other Blowfish routine in the library.  You should not
1095         use this function except to implement 'modes' of Blowfish.
1096         I say this because the
1097         functions that call this routine do the conversion from 'char *' to
1098         long, and this needs to be done to make sure 'non-aligned' memory
1099         access do not occur.
1100         Data is a pointer to 2 unsigned long's and key is the
1101         BF_KEY to use. 
1102
1103 void BF_ecb_encrypt(
1104 unsigned char *in,
1105 unsigned char *out,
1106 BF_KEY *key,
1107 int encrypt);
1108         This is the basic Electronic Code Book form of Blowfish (in DES this
1109         mode is called Electronic Code Book so I'm going to use the term
1110         for blowfish as well.
1111         Input is encrypted into output using the key represented by
1112         key.  Depending on the encrypt, encryption or
1113         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
1114         
1115 void BF_cbc_encrypt(
1116 unsigned char *in,
1117 unsigned char *out,
1118 long length,
1119 BF_KEY *ks,
1120 unsigned char *ivec,
1121 int encrypt);
1122         This routine implements Blowfish in Cipher Block Chaining mode.
1123         Input, which should be a multiple of 8 bytes is encrypted
1124         (or decrypted) to output which will also be a multiple of 8 bytes.
1125         The number of bytes is in length (and from what I've said above,
1126         should be a multiple of 8).  If length is not a multiple of 8, bad 
1127         things will probably happen.  ivec is the initialisation vector.
1128         This function updates iv after each call so that it can be passed to
1129         the next call to BF_cbc_encrypt().
1130         
1131 void BF_cfb64_encrypt(
1132 unsigned char *in,
1133 unsigned char *out,
1134 long length,
1135 BF_KEY *schedule,
1136 unsigned char *ivec,
1137 int *num,
1138 int encrypt);
1139         This is one of the more useful functions in this Blowfish library, it
1140         implements CFB mode of Blowfish with 64bit feedback.
1141         This allows you to encrypt an arbitrary number of bytes,
1142         you do not require 8 byte padding.  Each call to this
1143         routine will encrypt the input bytes to output and then update ivec
1144         and num.  Num contains 'how far' we are though ivec.
1145         'Encrypt' is used to indicate encryption or decryption.
1146         CFB64 mode operates by using the cipher to generate a stream
1147         of bytes which is used to encrypt the plain text.
1148         The cipher text is then encrypted to generate the next 64 bits to
1149         be xored (incrementally) with the next 64 bits of plain
1150         text.  As can be seen from this, to encrypt or decrypt,
1151         the same 'cipher stream' needs to be generated but the way the next
1152         block of data is gathered for encryption is different for
1153         encryption and decryption.
1154         
1155 void BF_ofb64_encrypt(
1156 unsigned char *in,
1157 unsigned char *out,
1158 long length,
1159 BF_KEY *schedule,
1160 unsigned char *ivec,
1161 int *num);
1162         This functions implements OFB mode of Blowfish with 64bit feedback.
1163         This allows you to encrypt an arbitrary number of bytes,
1164         you do not require 8 byte padding.  Each call to this
1165         routine will encrypt the input bytes to output and then update ivec
1166         and num.  Num contains 'how far' we are though ivec.
1167         This is in effect a stream cipher, there is no encryption or
1168         decryption mode.
1169         
1170 For reading passwords, I suggest using des_read_pw_string() from my DES library.
1171 To generate a password from a text string, I suggest using MD5 (or MD2) to
1172 produce a 16 byte message digest that can then be passed directly to
1173 BF_set_key().
1174
1175 =====
1176 For more information about the specific Blowfish modes in this library
1177 (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
1178 documentation on my DES library.  What is said about DES is directly
1179 applicable for Blowfish.
1180
1181
1182 ==== bn.doc ========================================================
1183
1184 The Big Number library.
1185
1186 #include "bn.h" when using this library.
1187
1188 This big number library was written for use in implementing the RSA and DH
1189 public key encryption algorithms.  As such, features such as negative
1190 numbers have not been extensively tested but they should work as expected.
1191 This library uses dynamic memory allocation for storing its data structures
1192 and so there are no limit on the size of the numbers manipulated by these
1193 routines but there is always the requirement to check return codes from
1194 functions just in case a memory allocation error has occurred.
1195
1196 The basic object in this library is a BIGNUM.  It is used to hold a single
1197 large integer.  This type should be considered opaque and fields should not
1198 be modified or accessed directly.
1199 typedef struct bignum_st
1200         {
1201         int top;        /* Index of last used d. */
1202         BN_ULONG *d;    /* Pointer to an array of 'BITS2' bit chunks. */
1203         int max;        /* Size of the d array. */
1204         int neg;
1205         } BIGNUM;
1206 The big number is stored in a malloced array of BN_ULONG's.  A BN_ULONG can
1207 be either 16, 32 or 64 bits in size, depending on the 'number of  bits'
1208 specified in bn.h. 
1209 The 'd' field is this array.  'max' is the size of the 'd' array that has
1210 been allocated.  'top' is the 'last' entry being used, so for a value of 4,
1211 bn.d[0]=4 and bn.top=1.  'neg' is 1 if the number is negative.
1212 When a BIGNUM is '0', the 'd' field can be NULL and top == 0.
1213
1214 Various routines in this library require the use of 'temporary' BIGNUM
1215 variables during their execution.  Due to the use of dynamic memory
1216 allocation to create BIGNUMs being rather expensive when used in
1217 conjunction with repeated subroutine calls, the BN_CTX structure is
1218 used.  This structure contains BN_CTX BIGNUMs.  BN_CTX
1219 is the maximum number of temporary BIGNUMs any publicly exported 
1220 function will use.
1221
1222 #define BN_CTX  12
1223 typedef struct bignum_ctx
1224         {
1225         int tos;                        /* top of stack */
1226         BIGNUM *bn[BN_CTX];     /* The variables */
1227         } BN_CTX;
1228
1229 The functions that follow have been grouped according to function.  Most
1230 arithmetic functions return a result in the first argument, sometimes this
1231 first argument can also be an input parameter, sometimes it cannot.  These
1232 restrictions are documented.
1233
1234 extern BIGNUM *BN_value_one;
1235 There is one variable defined by this library, a BIGNUM which contains the
1236 number 1.  This variable is useful for use in comparisons and assignment.
1237
1238 Get Size functions.
1239
1240 int BN_num_bits(BIGNUM *a);
1241         This function returns the size of 'a' in bits.
1242         
1243 int BN_num_bytes(BIGNUM *a);
1244         This function (macro) returns the size of 'a' in bytes.
1245         For conversion of BIGNUMs to byte streams, this is the number of
1246         bytes the output string will occupy.  If the output byte
1247         format specifies that the 'top' bit indicates if the number is
1248         signed, so an extra '0' byte is required if the top bit on a
1249         positive number is being written, it is upto the application to
1250         make this adjustment.  Like I said at the start, I don't
1251         really support negative numbers :-).
1252
1253 Creation/Destruction routines.
1254
1255 BIGNUM *BN_new();
1256         Return a new BIGNUM object.  The number initially has a value of 0.  If
1257         there is an error, NULL is returned.
1258         
1259 void    BN_free(BIGNUM *a);
1260         Free()s a BIGNUM.
1261         
1262 void    BN_clear(BIGNUM *a);
1263         Sets 'a' to a value of 0 and also zeros all unused allocated
1264         memory.  This function is used to clear a variable of 'sensitive'
1265         data that was held in it.
1266         
1267 void    BN_clear_free(BIGNUM *a);
1268         This function zeros the memory used by 'a' and then free()'s it.
1269         This function should be used to BN_free() BIGNUMS that have held
1270         sensitive numeric values like RSA private key values.  Both this
1271         function and BN_clear tend to only be used by RSA and DH routines.
1272
1273 BN_CTX *BN_CTX_new(void);
1274         Returns a new BN_CTX.  NULL on error.
1275         
1276 void    BN_CTX_free(BN_CTX *c);
1277         Free a BN_CTX structure.  The BIGNUMs in 'c' are BN_clear_free()ed.
1278         
1279 BIGNUM *bn_expand(BIGNUM *b, int bits);
1280         This is an internal function that should not normally be used.  It
1281         ensures that 'b' has enough room for a 'bits' bit number.  It is
1282         mostly used by the various BIGNUM routines.  If there is an error,
1283         NULL is returned. if not, 'b' is returned.
1284         
1285 BIGNUM *BN_copy(BIGNUM *to, BIGNUM *from);
1286         The 'from' is copied into 'to'.  NULL is returned if there is an
1287         error, otherwise 'to' is returned.
1288
1289 BIGNUM *BN_dup(BIGNUM *a);
1290         A new BIGNUM is created and returned containing the value of 'a'.
1291         NULL is returned on error.
1292
1293 Comparison and Test Functions.
1294
1295 int BN_is_zero(BIGNUM *a)
1296         Return 1 if 'a' is zero, else 0.
1297
1298 int BN_is_one(a)
1299         Return 1 is 'a' is one, else 0.
1300
1301 int BN_is_word(a,w)
1302         Return 1 if 'a' == w, else 0.  'w' is a BN_ULONG.
1303
1304 int BN_cmp(BIGNUM *a, BIGNUM *b);
1305         Return -1 if 'a' is less than 'b', 0 if 'a' and 'b' are the same
1306         and 1 is 'a' is greater than 'b'.  This is a signed comparison.
1307         
1308 int BN_ucmp(BIGNUM *a, BIGNUM *b);
1309         This function is the same as BN_cmp except that the comparison
1310         ignores the sign of the numbers.
1311         
1312 Arithmetic Functions
1313 For all of these functions, 0 is returned if there is an error and 1 is
1314 returned for success.  The return value should always be checked.  eg.
1315 if (!BN_add(r,a,b)) goto err;
1316 Unless explicitly mentioned, the 'return' value can be one of the
1317 'parameters' to the function.
1318
1319 int BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1320         Add 'a' and 'b' and return the result in 'r'.  This is r=a+b.
1321         
1322 int BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1323         Subtract 'a' from 'b' and put the result in 'r'. This is r=a-b.
1324         
1325 int BN_lshift(BIGNUM *r, BIGNUM *a, int n);
1326         Shift 'a' left by 'n' bits.  This is r=a*(2^n).
1327         
1328 int BN_lshift1(BIGNUM *r, BIGNUM *a);
1329         Shift 'a' left by 1 bit.  This form is more efficient than
1330         BN_lshift(r,a,1).  This is r=a*2.
1331         
1332 int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
1333         Shift 'a' right by 'n' bits.  This is r=int(a/(2^n)).
1334         
1335 int BN_rshift1(BIGNUM *r, BIGNUM *a);
1336         Shift 'a' right by 1 bit.  This form is more efficient than
1337         BN_rshift(r,a,1).  This is r=int(a/2).
1338         
1339 int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b);
1340         Multiply a by b and return the result in 'r'. 'r' must not be
1341         either 'a' or 'b'.  It has to be a different BIGNUM.
1342         This is r=a*b.
1343
1344 int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
1345         Multiply a by a and return the result in 'r'. 'r' must not be
1346         'a'.  This function is alot faster than BN_mul(r,a,a).  This is r=a*a.
1347
1348 int BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
1349         Divide 'm' by 'd' and return the result in 'dv' and the remainder
1350         in 'rem'.  Either of 'dv' or 'rem' can be NULL in which case that
1351         value is not returned.  'ctx' needs to be passed as a source of
1352         temporary BIGNUM variables.
1353         This is dv=int(m/d), rem=m%d.
1354         
1355 int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
1356         Find the remainder of 'm' divided by 'd' and return it in 'rem'.
1357         'ctx' holds the temporary BIGNUMs required by this function.
1358         This function is more efficient than BN_div(NULL,rem,m,d,ctx);
1359         This is rem=m%d.
1360
1361 int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *m,BN_CTX *ctx);
1362         Multiply 'a' by 'b' and return the remainder when divided by 'm'.
1363         'ctx' holds the temporary BIGNUMs required by this function.
1364         This is r=(a*b)%m.
1365
1366 int BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx);
1367         Raise 'a' to the 'p' power and return the remainder when divided by
1368         'm'.  'ctx' holds the temporary BIGNUMs required by this function.
1369         This is r=(a^p)%m.
1370
1371 int BN_reciprocal(BIGNUM *r, BIGNUM *m, BN_CTX *ctx);
1372         Return the reciprocal of 'm'.  'ctx' holds the temporary variables
1373         required.  This function returns -1 on error, otherwise it returns
1374         the number of bits 'r' is shifted left to make 'r' into an integer.
1375         This number of bits shifted is required in BN_mod_mul_reciprocal().
1376         This is r=(1/m)<<(BN_num_bits(m)+1).
1377         
1378 int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *x, BIGNUM *y, BIGNUM *m, 
1379         BIGNUM *i, int nb, BN_CTX *ctx);
1380         This function is used to perform an efficient BN_mod_mul()
1381         operation.  If one is going to repeatedly perform BN_mod_mul() with
1382         the same modulus is worth calculating the reciprocal of the modulus
1383         and then using this function.  This operation uses the fact that
1384         a/b == a*r where r is the reciprocal of b.  On modern computers
1385         multiplication is very fast and big number division is very slow.
1386         'x' is multiplied by 'y' and then divided by 'm' and the remainder
1387         is returned.  'i' is the reciprocal of 'm' and 'nb' is the number
1388         of bits as returned from BN_reciprocal().  Normal usage is as follows.
1389         bn=BN_reciprocal(i,m);
1390         for (...)
1391                 { BN_mod_mul_reciprocal(r,x,y,m,i,bn,ctx); }
1392         This is r=(x*y)%m.  Internally it is approximately
1393         r=(x*y)-m*(x*y/m) or r=(x*y)-m*((x*y*i) >> bn)
1394         This function is used in BN_mod_exp() and BN_is_prime().
1395
1396 Assignment Operations
1397
1398 int BN_one(BIGNUM *a)
1399         Set 'a' to hold the value one.
1400         This is a=1.
1401         
1402 int BN_zero(BIGNUM *a)
1403         Set 'a' to hold the value zero.
1404         This is a=0.
1405         
1406 int BN_set_word(BIGNUM *a, unsigned long w);
1407         Set 'a' to hold the value of 'w'.  'w' is an unsigned long.
1408         This is a=w.
1409
1410 unsigned long BN_get_word(BIGNUM *a);
1411         Returns 'a' in an unsigned long.  Not remarkably, often 'a' will
1412         be biger than a word, in which case 0xffffffffL is returned.
1413
1414 Word Operations
1415 These functions are much more efficient that the normal bignum arithmetic
1416 operations.
1417
1418 BN_ULONG BN_mod_word(BIGNUM *a, unsigned long w);
1419         Return the remainder of 'a' divided by 'w'.
1420         This is return(a%w).
1421         
1422 int BN_add_word(BIGNUM *a, unsigned long w);
1423         Add 'w' to 'a'.  This function does not take the sign of 'a' into
1424         account.  This is a+=w;
1425         
1426 Bit operations.
1427
1428 int BN_is_bit_set(BIGNUM *a, int n);
1429         This function return 1 if bit 'n' is set in 'a' else 0.
1430
1431 int BN_set_bit(BIGNUM *a, int n);
1432         This function sets bit 'n' to 1 in 'a'. 
1433         This is a&= ~(1<<n);
1434
1435 int BN_clear_bit(BIGNUM *a, int n);
1436         This function sets bit 'n' to zero in 'a'.  Return 0 if less
1437         than 'n' bits in 'a' else 1.  This is a&= ~(1<<n);
1438
1439 int BN_mask_bits(BIGNUM *a, int n);
1440         Truncate 'a' to n bits long.  This is a&= ~((~0)<<n)
1441
1442 Format conversion routines.
1443
1444 BIGNUM *BN_bin2bn(unsigned char *s, int len,BIGNUM *ret);
1445         This function converts 'len' bytes in 's' into a BIGNUM which
1446         is put in 'ret'.  If ret is NULL, a new BIGNUM is created.
1447         Either this new BIGNUM or ret is returned.  The number is
1448         assumed to be in bigendian form in 's'.  By this I mean that
1449         to 'ret' is created as follows for 'len' == 5.
1450         ret = s[0]*2^32 + s[1]*2^24 + s[2]*2^16 + s[3]*2^8 + s[4];
1451         This function cannot be used to convert negative numbers.  It
1452         is always assumed the number is positive.  The application
1453         needs to diddle the 'neg' field of th BIGNUM its self.
1454         The better solution would be to save the numbers in ASN.1 format
1455         since this is a defined standard for storing big numbers.
1456         Look at the functions
1457
1458         ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
1459         BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
1460         int i2d_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp);
1461         ASN1_INTEGER *d2i_ASN1_INTEGER(ASN1_INTEGER **a,unsigned char **pp,
1462                 long length;
1463
1464 int BN_bn2bin(BIGNUM *a, unsigned char *to);
1465         This function converts 'a' to a byte string which is put into
1466         'to'.  The representation is big-endian in that the most
1467         significant byte of 'a' is put into to[0].  This function
1468         returns the number of bytes used to hold 'a'.  BN_num_bytes(a)
1469         would return the same value and can be used to determine how
1470         large 'to' needs to be.  If the number is negative, this
1471         information is lost.  Since this library was written to
1472         manipulate large positive integers, the inability to save and
1473         restore them is not considered to be a problem by me :-).
1474         As for BN_bin2bn(), look at the ASN.1 integer encoding funtions
1475         for SSLeay.  They use BN_bin2bn() and BN_bn2bin() internally.
1476         
1477 char *BN_bn2ascii(BIGNUM *a);
1478         This function returns a malloc()ed string that contains the
1479         ascii hexadecimal encoding of 'a'.  The number is in bigendian
1480         format with a '-' in front if the number is negative.
1481
1482 int BN_ascii2bn(BIGNUM **bn, char *a);
1483         The inverse of BN_bn2ascii.  The function returns the number of
1484         characters from 'a' were processed in generating a the bignum.
1485         error is inticated by 0 being returned.  The number is a
1486         hex digit string, optionally with a leading '-'.  If *bn
1487         is null, a BIGNUM is created and returned via that variable.
1488         
1489 int BN_print_fp(FILE *fp, BIGNUM *a);
1490         'a' is printed to file pointer 'fp'.  It is in the same format
1491         that is output from BN_bn2ascii().  0 is returned on error,
1492         1 if things are ok.
1493
1494 int BN_print(BIO *bp, BIGNUM *a);
1495         Same as BN_print except that the output is done to the SSLeay libraries
1496         BIO routines.  BN_print_fp() actually calls this function.
1497
1498 Miscellaneous Routines.
1499
1500 int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
1501         This function returns in 'rnd' a random BIGNUM that is bits
1502         long.  If bottom is 1, the number returned is odd.  If top is set,
1503         the top 2 bits of the number are set.  This is useful because if
1504         this is set, 2 'n; bit numbers multiplied together will return a 2n
1505         bit number.  If top was not set, they could produce a 2n-1 bit
1506         number.
1507
1508 BIGNUM *BN_mod_inverse(BIGNUM *a, BIGNUM *n,BN_CTX *ctx);
1509         This function create a new BIGNUM and returns it.  This number
1510         is the inverse mod 'n' of 'a'.  By this it is meant that the
1511         returned value 'r' satisfies (a*r)%n == 1.  This function is
1512         used in the generation of RSA keys.  'ctx', as per usual,
1513         is used to hold temporary variables that are required by the
1514         function.  NULL is returned on error.
1515
1516 int BN_gcd(BIGNUM *r,BIGNUM *a,BIGNUM *b,BN_CTX *ctx);
1517         'r' has the greatest common divisor of 'a' and 'b'.  'ctx' is
1518         used for temporary variables and 0 is returned on error.
1519
1520 int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(),BN_CTX *ctx,
1521         char *cb_arg);
1522         This function is used to check if a BIGNUM ('p') is prime.
1523         It performs this test by using the Miller-Rabin randomised
1524         primality test.  This is a probalistic test that requires a
1525         number of rounds to ensure the number is prime to a high
1526         degree of probability.  Since this can take quite some time, a
1527         callback function can be passed and it will be called each
1528         time 'p' passes a round of the prime testing.  'callback' will
1529         be called as follows, callback(1,n,cb_arg) where n is the number of
1530         the round, just passed.  As per usual 'ctx' contains temporary
1531         variables used.  If ctx is NULL, it does not matter, a local version
1532         will be malloced.  This parameter is present to save some mallocing
1533         inside the function but probably could be removed.
1534         0 is returned on error.
1535         'ncheck' is the number of Miller-Rabin tests to run.  It is
1536         suggested to use the value 'BN_prime_checks' by default.
1537
1538 BIGNUM *BN_generate_prime(
1539 int bits,
1540 int strong,
1541 BIGNUM *a,
1542 BIGNUM *rems,
1543 void (*callback)());
1544 char *cb_arg
1545         This function is used to generate prime numbers.  It returns a
1546         new BIGNUM that has a high probability of being a prime.
1547         'bits' is the number of bits that
1548         are to be in the prime.  If 'strong' is true, the returned prime
1549         will also be a strong prime ((p-1)/2 is also prime).
1550         While searching for the prime ('p'), we
1551         can add the requirement that the prime fill the following
1552         condition p%a == rem.  This can be used to help search for
1553         primes with specific features, which is required when looking
1554         for primes suitable for use with certain 'g' values in the
1555         Diffie-Hellman key exchange algorithm.  If 'a' is NULL,
1556         this condition is not checked.  If rem is NULL, rem is assumed
1557         to be 1.  Since this search for a prime
1558         can take quite some time, if callback is not NULL, it is called
1559         in the following situations.
1560         We have a suspected prime (from a quick sieve),
1561         callback(0,sus_prime++,cb_arg). Each item to be passed to BN_is_prime().
1562         callback(1,round++,cb_arg).  Each successful 'round' in BN_is_prime().
1563         callback(2,round,cb_arg). For each successful BN_is_prime() test.
1564
1565
1566 ==== callback.doc ========================================================
1567
1568 Callback functions used in SSLeay.
1569
1570 --------------------------
1571 The BIO library.  
1572
1573 Each BIO structure can have a callback defined against it.  This callback is
1574 called 2 times for each BIO 'function'.  It is passed 6 parameters.
1575 BIO_debug_callback() is an example callback which is defined in
1576 crypto/buffer/bio_cb.c and is used in apps/dgst.c  This is intended mostly
1577 for debuging or to notify the application of IO.
1578
1579 long BIO_debug_callback(BIO *bio,int cmd,char *argp,int argi,long argl,
1580         long ret);
1581 bio is the BIO being called, cmd is the type of BIO function being called.
1582 Look at the BIO_CB_* defines in buffer.h.  Argp and argi are the arguments
1583 passed to BIO_read(), BIO_write, BIO_gets(), BIO_puts().  In the case of
1584 BIO_ctrl(), argl is also defined.  The first time the callback is called,
1585 before the underlying function has been executed, 0 is passed as 'ret', and
1586 if the return code from the callback is not > 0, the call is aborted
1587 and the returned <= 0 value is returned.
1588 The second time the callback is called, the 'cmd' value also has
1589 BIO_CB_RETURN logically 'or'ed with it.  The 'ret' value is the value returned
1590 from the actuall function call and whatever the callback returns is returned
1591 from the BIO function.
1592
1593 BIO_set_callback(b,cb) can be used to set the callback function
1594 (b is a BIO), and BIO_set_callback_arg(b,arg) can be used to
1595 set the cb_arg argument in the BIO strucutre.  This field is only intended
1596 to be used by application, primarily in the callback function since it is
1597 accessable since the BIO is passed.
1598
1599 --------------------------
1600 The PEM library.
1601
1602 The pem library only really uses one type of callback,
1603 static int def_callback(char *buf, int num, int verify);
1604 which is used to return a password string if required.
1605 'buf' is the buffer to put the string in.  'num' is the size of 'buf'
1606 and 'verify' is used to indicate that the password should be checked.
1607 This last flag is mostly used when reading a password for encryption.
1608
1609 For all of these functions, a NULL callback will call the above mentioned
1610 default callback.  This default function does not work under Windows 3.1.
1611 For other machines, it will use an application defined prompt string
1612 (EVP_set_pw_prompt(), which defines a library wide prompt string)
1613 if defined, otherwise it will use it's own PEM password prompt.
1614 It will then call EVP_read_pw_string() to get a password from the console.
1615 If your application wishes to use nice fancy windows to retrieve passwords,
1616 replace this function.  The callback should return the number of bytes read
1617 into 'buf'.  If the number of bytes <= 0, it is considered an error.
1618
1619 Functions that take this callback are listed below.  For the 'read' type
1620 functions, the callback will only be required if the PEM data is encrypted.
1621
1622 For the Write functions, normally a password can be passed in 'kstr', of
1623 'klen' bytes which will be used if the 'enc' cipher is not NULL.  If
1624 'kstr' is NULL, the callback will be used to retrieve a password.
1625
1626 int PEM_do_header (EVP_CIPHER_INFO *cipher, unsigned char *data,long *len,
1627         int (*callback)());
1628 char *PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *bp,char **x,int (*cb)());
1629 char *PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
1630 int PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *bp,char *x,
1631         EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
1632 int PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,
1633         EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
1634 STACK *PEM_X509_INFO_read(FILE *fp, STACK *sk, int (*cb)());
1635 STACK *PEM_X509_INFO_read_bio(BIO *fp, STACK *sk, int (*cb)());
1636
1637 #define PEM_write_RSAPrivateKey(fp,x,enc,kstr,klen,cb)
1638 #define PEM_write_DSAPrivateKey(fp,x,enc,kstr,klen,cb)
1639 #define PEM_write_bio_RSAPrivateKey(bp,x,enc,kstr,klen,cb)
1640 #define PEM_write_bio_DSAPrivateKey(bp,x,enc,kstr,klen,cb)
1641 #define PEM_read_SSL_SESSION(fp,x,cb)
1642 #define PEM_read_X509(fp,x,cb)
1643 #define PEM_read_X509_REQ(fp,x,cb)
1644 #define PEM_read_X509_CRL(fp,x,cb)
1645 #define PEM_read_RSAPrivateKey(fp,x,cb)
1646 #define PEM_read_DSAPrivateKey(fp,x,cb)
1647 #define PEM_read_PrivateKey(fp,x,cb)
1648 #define PEM_read_PKCS7(fp,x,cb)
1649 #define PEM_read_DHparams(fp,x,cb)
1650 #define PEM_read_bio_SSL_SESSION(bp,x,cb)
1651 #define PEM_read_bio_X509(bp,x,cb)
1652 #define PEM_read_bio_X509_REQ(bp,x,cb)
1653 #define PEM_read_bio_X509_CRL(bp,x,cb)
1654 #define PEM_read_bio_RSAPrivateKey(bp,x,cb)
1655 #define PEM_read_bio_DSAPrivateKey(bp,x,cb)
1656 #define PEM_read_bio_PrivateKey(bp,x,cb)
1657 #define PEM_read_bio_PKCS7(bp,x,cb)
1658 #define PEM_read_bio_DHparams(bp,x,cb)
1659 int i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
1660 RSA *d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
1661
1662 Now you will notice that macros like
1663 #define PEM_write_X509(fp,x) \
1664                 PEM_ASN1_write((int (*)())i2d_X509,PEM_STRING_X509,fp, \
1665                                         (char *)x, NULL,NULL,0,NULL)
1666 Don't do encryption normally.  If you want to PEM encrypt your X509 structure,
1667 either just call PEM_ASN1_write directly or just define you own
1668 macro variant.  As you can see, this macro just sets all encryption related
1669 parameters to NULL.
1670
1671
1672 --------------------------
1673 The SSL library.
1674
1675 #define SSL_set_info_callback(ssl,cb)
1676 #define SSL_CTX_set_info_callback(ctx,cb)
1677 void callback(SSL *ssl,int location,int ret)
1678 This callback is called each time around the SSL_connect()/SSL_accept() 
1679 state machine.  So it will be called each time the SSL protocol progresses.
1680 It is mostly present for use when debugging.  When SSL_connect() or
1681 SSL_accept() return, the location flag is SSL_CB_ACCEPT_EXIT or
1682 SSL_CB_CONNECT_EXIT and 'ret' is the value about to be returned.
1683 Have a look at the SSL_CB_* defines in ssl.h.  If an info callback is defined
1684 against the SSL_CTX, it is called unless there is one set against the SSL.
1685 Have a look at
1686 void client_info_callback() in apps/s_client() for an example.
1687
1688 Certificate verification.
1689 void SSL_set_verify(SSL *s, int mode, int (*callback) ());
1690 void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*callback)());
1691 This callback is used to help verify client and server X509 certificates.
1692 It is actually passed to X509_cert_verify(), along with the SSL structure
1693 so you have to read about X509_cert_verify() :-).  The SSL_CTX version is used
1694 if the SSL version is not defined.  X509_cert_verify() is the function used
1695 by the SSL part of the library to verify certificates.  This function is
1696 nearly always defined by the application.
1697
1698 void SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx, int (*cb)(),char *arg);
1699 int callback(char *arg,SSL *s,X509 *xs,STACK *cert_chain);
1700 This call is used to replace the SSLeay certificate verification code.
1701 The 'arg' is kept in the SSL_CTX and is passed to the callback.
1702 If the callback returns 0, the certificate is rejected, otherwise it
1703 is accepted.  The callback is replacing the X509_cert_verify() call.
1704 This feature is not often used, but if you wished to implement
1705 some totally different certificate authentication system, this 'hook' is
1706 vital.
1707
1708 SSLeay keeps a cache of session-ids against each SSL_CTX.  These callbacks can
1709 be used to notify the application when a SSL_SESSION is added to the cache
1710 or to retrieve a SSL_SESSION that is not in the cache from the application.
1711 #define SSL_CTX_sess_set_get_cb(ctx,cb)
1712 SSL_SESSION *callback(SSL *s,char *session_id,int session_id_len,int *copy);
1713 If defined, this callback is called to return the SESSION_ID for the
1714 session-id in 'session_id', of 'session_id_len' bytes.  'copy' is set to 1
1715 if the server is to 'take a copy' of the SSL_SESSION structure.  It is 0
1716 if the SSL_SESSION is being 'passed in' so the SSLeay library is now
1717 responsible for 'free()ing' the structure.  Basically it is used to indicate
1718 if the reference count on the SSL_SESSION structure needs to be incremented.
1719
1720 #define SSL_CTX_sess_set_new_cb(ctx,cb)
1721 int callback(SSL *s, SSL_SESSION *sess);
1722 When a new connection is established, if the SSL_SESSION is going to be added
1723 to the cache, this callback is called.  Return 1 if a 'copy' is required,
1724 otherwise, return 0.  This return value just causes the reference count
1725 to be incremented (on return of a 1), this means the application does
1726 not need to worry about incrementing the refernece count (and the
1727 locking that implies in a multi-threaded application).
1728
1729 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)());
1730 This sets the SSL password reading function.
1731 It is mostly used for windowing applications
1732 and used by PEM_read_bio_X509() and PEM_read_bio_RSAPrivateKey()
1733 calls inside the SSL library.   The only reason this is present is because the
1734 calls to PEM_* functions is hidden in the SSLeay library so you have to
1735 pass in the callback some how.
1736
1737 #define SSL_CTX_set_client_cert_cb(ctx,cb)
1738 int callback(SSL *s,X509 **x509, EVP_PKEY **pkey);
1739 Called when a client certificate is requested but there is not one set
1740 against the SSL_CTX or the SSL.  If the callback returns 1, x509 and
1741 pkey need to point to valid data.  The library will free these when
1742 required so if the application wants to keep these around, increment
1743 their reference counts.  If 0 is returned, no client cert is
1744 available.  If -1 is returned, it is assumed that the callback needs
1745 to be called again at a later point in time.  SSL_connect will return
1746 -1 and SSL_want_x509_lookup(ssl) returns true.  Remember that
1747 application data can be attached to an SSL structure via the
1748 SSL_set_app_data(SSL *ssl,char *data) call.
1749
1750 --------------------------
1751 The X509 library.
1752
1753 int X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)(),
1754         int *error,char *arg,STACK *cert_chain);
1755 int verify_callback(int ok,X509 *xs,X509 *xi,int depth,int error,char *arg,
1756         STACK *cert_chain);
1757
1758 X509_cert_verify() is used to authenticate X509 certificates.  The 'ctx' holds
1759 the details of the various caches and files used to locate certificates.
1760 'xs' is the certificate to verify and 'cb' is the application callback (more
1761 detail later).  'error' will be set to the error code and 'arg' is passed
1762 to the 'cb' callback.  Look at the VERIFY_* defines in crypto/x509/x509.h
1763
1764 When ever X509_cert_verify() makes a 'negative' decision about a
1765 certitificate, the callback is called.  If everything checks out, the
1766 callback is called with 'VERIFY_OK' or 'VERIFY_ROOT_OK' (for a self
1767 signed cert that is not the passed certificate).
1768
1769 The callback is passed the X509_cert_verify opinion of the certificate 
1770 in 'ok', the certificate in 'xs', the issuer certificate in 'xi',
1771 the 'depth' of the certificate in the verification 'chain', the
1772 VERIFY_* code in 'error' and the argument passed to X509_cert_verify()
1773 in 'arg'. cert_chain is a list of extra certs to use if they are not
1774 in the cache.
1775
1776 The callback can be used to look at the error reason, and then return 0
1777 for an 'error' or '1' for ok.  This will override the X509_cert_verify()
1778 opinion of the certificates validity.  Processing will continue depending on
1779 the return value.  If one just wishes to use the callback for informational
1780 reason, just return the 'ok' parameter.
1781
1782 --------------------------
1783 The BN and DH library.
1784
1785 BIGNUM *BN_generate_prime(int bits,int strong,BIGNUM *add,
1786         BIGNUM *rem,void (*callback)(int,int));
1787 int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(int,int),
1788
1789 Read doc/bn.doc for the description of these 2.
1790
1791 DH *DH_generate_parameters(int prime_len,int generator,
1792         void (*callback)(int,int));
1793 Read doc/bn.doc for the description of the callback, since it is just passed
1794 to BN_generate_prime(), except that it is also called as
1795 callback(3,0) by this function.
1796
1797 --------------------------
1798 The CRYPTO library.
1799
1800 void CRYPTO_set_locking_callback(void (*func)(int mode,int type,char *file,
1801         int line));
1802 void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,
1803         int type,char *file, int line));
1804 void CRYPTO_set_id_callback(unsigned long (*func)(void));
1805
1806 Read threads.doc for info on these ones.
1807
1808
1809 ==== cipher.doc ========================================================
1810
1811 The Cipher subroutines.
1812
1813 These routines require "evp.h" to be included.
1814
1815 These functions are a higher level interface to the various cipher
1816 routines found in this library.  As such, they allow the same code to be
1817 used to encrypt and decrypt via different ciphers with only a change
1818 in an initial parameter.  These routines also provide buffering for block
1819 ciphers.
1820
1821 These routines all take a pointer to the following structure to specify
1822 which cipher to use.  If you wish to use a new cipher with these routines,
1823 you would probably be best off looking an how an existing cipher is
1824 implemented and copying it.  At this point in time, I'm not going to go
1825 into many details.  This structure should be considered opaque
1826
1827 typedef struct pem_cipher_st
1828         {
1829         int type;
1830         int block_size;
1831         int key_len;
1832         int iv_len;
1833         void (*enc_init)();     /* init for encryption */
1834         void (*dec_init)();     /* init for decryption */
1835         void (*do_cipher)();    /* encrypt data */
1836         } EVP_CIPHER;
1837         
1838 The type field is the object NID of the cipher type
1839 (read the section on Objects for an explanation of what a NID is).
1840 The cipher block_size is how many bytes need to be passed
1841 to the cipher at a time.  Key_len is the
1842 length of the key the cipher requires and iv_len is the length of the
1843 initialisation vector required.  enc_init is the function
1844 called to initialise the ciphers context for encryption and dec_init is the
1845 function to initialise for decryption (they need to be different, especially
1846 for the IDEA cipher).
1847
1848 One reason for specifying the Cipher via a pointer to a structure
1849 is that if you only use des-cbc, only the des-cbc routines will
1850 be included when you link the program.  If you passed an integer
1851 that specified which cipher to use, the routine that mapped that
1852 integer to a set of cipher functions would cause all the ciphers
1853 to be link into the code.  This setup also allows new ciphers
1854 to be added by the application (with some restrictions).
1855
1856 The thirteen ciphers currently defined in this library are
1857
1858 EVP_CIPHER *EVP_des_ecb();     /* DES in ecb mode,     iv=0, block=8, key= 8 */
1859 EVP_CIPHER *EVP_des_ede();     /* DES in ecb ede mode, iv=0, block=8, key=16 */
1860 EVP_CIPHER *EVP_des_ede3();    /* DES in ecb ede mode, iv=0, block=8, key=24 */
1861 EVP_CIPHER *EVP_des_cfb();     /* DES in cfb mode,     iv=8, block=1, key= 8 */
1862 EVP_CIPHER *EVP_des_ede_cfb(); /* DES in ede cfb mode, iv=8, block=1, key=16 */
1863 EVP_CIPHER *EVP_des_ede3_cfb();/* DES in ede cfb mode, iv=8, block=1, key=24 */
1864 EVP_CIPHER *EVP_des_ofb();     /* DES in ofb mode,     iv=8, block=1, key= 8 */
1865 EVP_CIPHER *EVP_des_ede_ofb(); /* DES in ede ofb mode, iv=8, block=1, key=16 */
1866 EVP_CIPHER *EVP_des_ede3_ofb();/* DES in ede ofb mode, iv=8, block=1, key=24 */
1867 EVP_CIPHER *EVP_des_cbc();     /* DES in cbc mode,     iv=8, block=8, key= 8 */
1868 EVP_CIPHER *EVP_des_ede_cbc(); /* DES in cbc ede mode, iv=8, block=8, key=16 */
1869 EVP_CIPHER *EVP_des_ede3_cbc();/* DES in cbc ede mode, iv=8, block=8, key=24 */
1870 EVP_CIPHER *EVP_desx_cbc();    /* DES in desx cbc mode,iv=8, block=8, key=24 */
1871 EVP_CIPHER *EVP_rc4();         /* RC4,                 iv=0, block=1, key=16 */
1872 EVP_CIPHER *EVP_idea_ecb();    /* IDEA in ecb mode,    iv=0, block=8, key=16 */
1873 EVP_CIPHER *EVP_idea_cfb();    /* IDEA in cfb mode,    iv=8, block=1, key=16 */
1874 EVP_CIPHER *EVP_idea_ofb();    /* IDEA in ofb mode,    iv=8, block=1, key=16 */
1875 EVP_CIPHER *EVP_idea_cbc();    /* IDEA in cbc mode,    iv=8, block=8, key=16 */
1876 EVP_CIPHER *EVP_rc2_ecb();     /* RC2 in ecb mode,     iv=0, block=8, key=16 */
1877 EVP_CIPHER *EVP_rc2_cfb();     /* RC2 in cfb mode,     iv=8, block=1, key=16 */
1878 EVP_CIPHER *EVP_rc2_ofb();     /* RC2 in ofb mode,     iv=8, block=1, key=16 */
1879 EVP_CIPHER *EVP_rc2_cbc();     /* RC2 in cbc mode,     iv=8, block=8, key=16 */
1880 EVP_CIPHER *EVP_bf_ecb();      /* Blowfish in ecb mode,iv=0, block=8, key=16 */
1881 EVP_CIPHER *EVP_bf_cfb();      /* Blowfish in cfb mode,iv=8, block=1, key=16 */
1882 EVP_CIPHER *EVP_bf_ofb();      /* Blowfish in ofb mode,iv=8, block=1, key=16 */
1883 EVP_CIPHER *EVP_bf_cbc();      /* Blowfish in cbc mode,iv=8, block=8, key=16 */
1884
1885 The meaning of the compound names is as follows.
1886 des     The base cipher is DES.
1887 idea    The base cipher is IDEA
1888 rc4     The base cipher is RC4-128
1889 rc2     The base cipher is RC2-128
1890 ecb     Electronic Code Book form of the cipher.
1891 cbc     Cipher Block Chaining form of the cipher.
1892 cfb     64 bit Cipher Feedback form of the cipher.
1893 ofb     64 bit Output Feedback form of the cipher.
1894 ede     The cipher is used in Encrypt, Decrypt, Encrypt mode.  The first
1895         and last keys are the same.
1896 ede3    The cipher is used in Encrypt, Decrypt, Encrypt mode.
1897
1898 All the Cipher routines take a EVP_CIPHER_CTX pointer as an argument.
1899 The state of the cipher is kept in this structure.
1900
1901 typedef struct EVP_CIPHER_Ctx_st
1902         {
1903         EVP_CIPHER *cipher;
1904         int encrypt;            /* encrypt or decrypt */
1905         int buf_len;            /* number we have left */
1906         unsigned char buf[8];
1907         union   {
1908                 .... /* cipher specific stuff */
1909                 } c;
1910         } EVP_CIPHER_CTX;
1911
1912 Cipher is a pointer the the EVP_CIPHER for the current context.  The encrypt
1913 flag indicates encryption or decryption.  buf_len is the number of bytes
1914 currently being held in buf.
1915 The 'c' union holds the cipher specify context.
1916
1917 The following functions are to be used.
1918
1919 int EVP_read_pw_string(
1920 char *buf,
1921 int len,
1922 char *prompt,
1923 int verify,
1924         This function is the same as des_read_pw_string() (des.doc).
1925
1926 void EVP_set_pw_prompt(char *prompt);
1927         This function sets the 'default' prompt to use to use in
1928         EVP_read_pw_string when the prompt parameter is NULL.  If the
1929         prompt parameter is NULL, this 'default prompt' feature is turned
1930         off.  Be warned, this is a global variable so weird things
1931         will happen if it is used under Win16 and care must be taken
1932         with a multi-threaded version of the library.
1933
1934 char *EVP_get_pw_prompt();
1935         This returns a pointer to the default prompt string.  NULL
1936         if it is not set.
1937
1938 int EVP_BytesToKey(
1939 EVP_CIPHER *type,
1940 EVP_MD *md,
1941 unsigned char *salt,
1942 unsigned char *data,
1943 int datal,
1944 int count,
1945 unsigned char *key,
1946 unsigned char *iv);
1947         This function is used to generate a key and an initialisation vector
1948         for a specified cipher from a key string and a salt.  Type
1949         specifies the cipher the 'key' is being generated for.  Md is the
1950         message digest algorithm to use to generate the key and iv.  The salt
1951         is an optional 8 byte object that is used to help seed the key
1952         generator.
1953         If the salt value is NULL, it is just not used.  Datal is the
1954         number of bytes to use from 'data' in the key generation.  
1955         This function returns the key size for the specified cipher, if
1956         data is NULL, this value is returns and no other
1957         computation is performed.  Count is
1958         the number of times to loop around the key generator.  I would
1959         suggest leaving it's value as 1.  Key and iv are the structures to
1960         place the returning iv and key in.  If they are NULL, no value is
1961         generated for that particular value.
1962         The algorithm used is as follows
1963         
1964         /* M[] is an array of message digests
1965          * MD() is the message digest function */
1966         M[0]=MD(data . salt);
1967         for (i=1; i<count; i++) M[0]=MD(M[0]);
1968
1969         i=1
1970         while (data still needed for key and iv)
1971                 {
1972                 M[i]=MD(M[i-1] . data . salt);
1973                 for (i=1; i<count; i++) M[i]=MD(M[i]);
1974                 i++;
1975                 }
1976
1977         If the salt is NULL, it is not used.
1978         The digests are concatenated together.
1979         M = M[0] . M[1] . M[2] .......
1980
1981         For key= 8, iv=8 => key=M[0.. 8], iv=M[ 9 .. 16].
1982         For key=16, iv=0 => key=M[0..16].
1983         For key=16, iv=8 => key=M[0..16], iv=M[17 .. 24].
1984         For key=24, iv=8 => key=M[0..24], iv=M[25 .. 32].
1985
1986         This routine will produce DES-CBC keys and iv that are compatible
1987         with the PKCS-5 standard when md2 or md5 are used.  If md5 is
1988         used, the salt is NULL and count is 1, this routine will produce
1989         the password to key mapping normally used with RC4.
1990         I have attempted to logically extend the PKCS-5 standard to
1991         generate keys and iv for ciphers that require more than 16 bytes,
1992         if anyone knows what the correct standard is, please inform me.
1993         When using sha or sha1, things are a bit different under this scheme,
1994         since sha produces a 20 byte digest.  So for ciphers requiring
1995         24 bits of data, 20 will come from the first MD and 4 will
1996         come from the second.
1997
1998         I have considered having a separate function so this 'routine'
1999         can be used without the requirement of passing a EVP_CIPHER *,
2000         but I have decided to not bother.  If you wish to use the
2001         function without official EVP_CIPHER structures, just declare
2002         a local one and set the key_len and iv_len fields to the
2003         length you desire.
2004
2005 The following routines perform encryption and decryption 'by parts'.  By
2006 this I mean that there are groups of 3 routines.  An Init function that is
2007 used to specify a cipher and initialise data structures.  An Update routine
2008 that does encryption/decryption, one 'chunk' at a time.  And finally a
2009 'Final' function that finishes the encryption/decryption process.
2010 All these functions take a EVP_CIPHER pointer to specify which cipher to
2011 encrypt/decrypt with.  They also take a EVP_CIPHER_CTX object as an
2012 argument.  This structure is used to hold the state information associated
2013 with the operation in progress.
2014
2015 void EVP_EncryptInit(
2016 EVP_CIPHER_CTX *ctx,
2017 EVP_CIPHER *type,
2018 unsigned char *key,
2019 unsigned char *iv);
2020         This function initialise a EVP_CIPHER_CTX for encryption using the
2021         cipher passed in the 'type' field.  The cipher is initialised to use
2022         'key' as the key and 'iv' for the initialisation vector (if one is
2023         required).  If the type, key or iv is NULL, the value currently in the
2024         EVP_CIPHER_CTX is reused.  So to perform several decrypt
2025         using the same cipher, key and iv, initialise with the cipher,
2026         key and iv the first time and then for subsequent calls,
2027         reuse 'ctx' but pass NULL for type, key and iv.  You must make sure
2028         to pass a key that is large enough for a particular cipher.  I
2029         would suggest using the EVP_BytesToKey() function.
2030
2031 void EVP_EncryptUpdate(
2032 EVP_CIPHER_CTX *ctx,
2033 unsigned char *out,
2034 int *outl,
2035 unsigned char *in,
2036 int inl);
2037         This function takes 'inl' bytes from 'in' and outputs bytes
2038         encrypted by the cipher 'ctx' was initialised with into 'out'.  The
2039         number of bytes written to 'out' is put into outl.  If a particular
2040         cipher encrypts in blocks, less or more bytes than input may be
2041         output.  Currently the largest block size used by supported ciphers
2042         is 8 bytes, so 'out' should have room for 'inl+7' bytes.  Normally
2043         EVP_EncryptInit() is called once, followed by lots and lots of
2044         calls to EVP_EncryptUpdate, followed by a single EVP_EncryptFinal
2045         call.
2046
2047 void EVP_EncryptFinal(
2048 EVP_CIPHER_CTX *ctx,
2049 unsigned char *out,
2050 int *outl);
2051         Because quite a large number of ciphers are block ciphers, there is
2052         often an incomplete block to write out at the end of the
2053         encryption.  EVP_EncryptFinal() performs processing on this last
2054         block.  The last block in encoded in such a way that it is possible
2055         to determine how many bytes in the last block are valid.  For 8 byte
2056         block size ciphers, if only 5 bytes in the last block are valid, the
2057         last three bytes will be filled with the value 3.  If only 2 were
2058         valid, the other 6 would be filled with sixes.  If all 8 bytes are
2059         valid, a extra 8 bytes are appended to the cipher stream containing
2060         nothing but 8 eights.  These last bytes are output into 'out' and
2061         the number of bytes written is put into 'outl'  These last bytes
2062         are output into 'out' and the number of bytes written is put into
2063         'outl'.  This form of block cipher finalisation is compatible with
2064         PKCS-5.  Please remember that even if you are using ciphers like
2065         RC4 that has no blocking and so the function will not write
2066         anything into 'out', it would still be a good idea to pass a
2067         variable for 'out' that can hold 8 bytes just in case the cipher is
2068         changed some time in the future.  It should also be remembered
2069         that the EVP_CIPHER_CTX contains the password and so when one has
2070         finished encryption with a particular EVP_CIPHER_CTX, it is good
2071         practice to zero the structure 
2072         (ie. memset(ctx,0,sizeof(EVP_CIPHER_CTX)).
2073         
2074 void EVP_DecryptInit(
2075 EVP_CIPHER_CTX *ctx,
2076 EVP_CIPHER *type,
2077 unsigned char *key,
2078 unsigned char *iv);
2079         This function is basically the same as EVP_EncryptInit() accept that
2080         is prepares the EVP_CIPHER_CTX for decryption.
2081
2082 void EVP_DecryptUpdate(
2083 EVP_CIPHER_CTX *ctx,
2084 unsigned char *out,
2085 int *outl,
2086 unsigned char *in,
2087 int inl);
2088         This function is basically the same as EVP_EncryptUpdate()
2089         except that it performs decryption.  There is one
2090         fundamental difference though.  'out' can not be the same as
2091         'in' for any ciphers with a block size greater than 1 if more
2092         than one call to EVP_DecryptUpdate() will be made.  This
2093         is because this routine can hold a 'partial' block between
2094         calls.  When a partial block is decrypted (due to more bytes
2095         being passed via this function, they will be written to 'out'
2096         overwriting the input bytes in 'in' that have not been read
2097         yet.  From this it should also be noted that 'out' should
2098         be at least one 'block size' larger than 'inl'.  This problem
2099         only occurs on the second and subsequent call to
2100         EVP_DecryptUpdate() when using a block cipher.
2101
2102 int EVP_DecryptFinal(
2103 EVP_CIPHER_CTX *ctx,
2104 unsigned char *out,
2105 int *outl);
2106         This function is different to EVP_EncryptFinal in that it 'removes'
2107         any padding bytes appended when the data was encrypted.  Due to the
2108         way in which 1 to 8 bytes may have been appended when encryption
2109         using a block cipher, 'out' can end up with 0 to 7 bytes being put
2110         into it.  When decoding the padding bytes, it is possible to detect
2111         an incorrect decryption.  If the decryption appears to be wrong, 0
2112         is returned.  If everything seems ok, 1 is returned.  For ciphers
2113         with a block size of 1 (RC4), this function would normally not
2114         return any bytes and would always return 1.  Just because this
2115         function returns 1 does not mean the decryption was correct. It
2116         would normally be wrong due to either the wrong key/iv or
2117         corruption of the cipher data fed to EVP_DecryptUpdate().
2118         As for EVP_EncryptFinal, it is a good idea to zero the
2119         EVP_CIPHER_CTX after use since the structure contains the key used
2120         to decrypt the data.
2121         
2122 The following Cipher routines are convenience routines that call either
2123 EVP_EncryptXxx or EVP_DecryptXxx depending on weather the EVP_CIPHER_CTX
2124 was setup to encrypt or decrypt.  
2125
2126 void EVP_CipherInit(
2127 EVP_CIPHER_CTX *ctx,
2128 EVP_CIPHER *type,
2129 unsigned char *key,
2130 unsigned char *iv,
2131 int enc);
2132         This function take arguments that are the same as EVP_EncryptInit()
2133         and EVP_DecryptInit() except for the extra 'enc' flag.  If 1, the
2134         EVP_CIPHER_CTX is setup for encryption, if 0, decryption.
2135
2136 void EVP_CipherUpdate(
2137 EVP_CIPHER_CTX *ctx,
2138 unsigned char *out,
2139 int *outl,
2140 unsigned char *in,
2141 int inl);
2142         Again this function calls either EVP_EncryptUpdate() or
2143         EVP_DecryptUpdate() depending on state in the 'ctx' structure.
2144         As noted for EVP_DecryptUpdate(), when this routine is used
2145         for decryption with block ciphers, 'out' should not be the
2146         same as 'in'.
2147
2148 int EVP_CipherFinal(
2149 EVP_CIPHER_CTX *ctx,
2150 unsigned char *outm,
2151 int *outl);
2152         This routine call EVP_EncryptFinal() or EVP_DecryptFinal()
2153         depending on the state information in 'ctx'.  1 is always returned
2154         if the mode is encryption, otherwise the return value is the return
2155         value of EVP_DecryptFinal().
2156
2157 ==== cipher.m ========================================================
2158
2159 Date: Tue, 15 Oct 1996 08:16:14 +1000 (EST)
2160 From: Eric Young <eay@mincom.com>
2161 X-Sender: eay@orb
2162 To: Roland Haring <rharing@tandem.cl>
2163 Cc: ssl-users@mincom.com
2164 Subject: Re: Symmetric encryption with ssleay
2165 In-Reply-To: <m0vBpyq-00001aC@tandemnet.tandem.cl>
2166 Message-Id: <Pine.SOL.3.91.961015075623.11394A-100000@orb>
2167 Mime-Version: 1.0
2168 Content-Type: TEXT/PLAIN; charset=US-ASCII
2169 Sender: ssl-lists-owner@mincom.com
2170 Precedence: bulk
2171 Status: RO
2172 X-Status: 
2173
2174 On Fri, 11 Oct 1996, Roland Haring wrote:
2175 > THE_POINT:
2176 >       Would somebody be so kind to give me the minimum basic 
2177 >       calls I need to do to libcrypto.a to get some text encrypted
2178 >       and decrypted again? ...hopefully with code included to do
2179 >       base64 encryption and decryption ... e.g. that sign-it.c code
2180 >       posted some while ago was a big help :-) (please, do not point
2181 >       me to apps/enc.c where I suspect my Heissenbug to be hidden :-)
2182
2183 Ok, the base64 encoding stuff in 'enc.c' does the wrong thing sometimes 
2184 when the data is less than a line long (this is for decoding).  I'll dig 
2185 up the exact fix today and post it.  I am taking longer on 0.6.5 than I 
2186 intended so I'll just post this patch.
2187
2188 The documentation to read is in
2189 doc/cipher.doc,
2190 doc/encode.doc (very sparse :-).
2191 and perhaps
2192 doc/digest.doc,
2193
2194 The basic calls to encrypt with say triple DES are
2195
2196 Given
2197 char key[EVP_MAX_KEY_LENGTH];
2198 char iv[EVP_MAX_IV_LENGTH];
2199 EVP_CIPHER_CTX ctx;
2200 unsigned char out[512+8];
2201 int outl;
2202
2203 /* optional generation of key/iv data from text password using md5
2204  * via an upward compatable verson of PKCS#5. */
2205 EVP_BytesToKey(EVP_des_ede3_cbc,EVP_md5,NULL,passwd,strlen(passwd),
2206         key,iv);
2207
2208 /* Initalise the EVP_CIPHER_CTX */
2209 EVP_EncryptInit(ctx,EVP_des_ede3_cbc,key,iv);
2210
2211 while (....)
2212         {
2213         /* This is processing 512 bytes at a time, the bytes are being
2214          * copied into 'out', outl bytes are output.  'out' should not be the
2215          * same as 'in' for reasons mentioned in the documentation. */
2216         EVP_EncryptUpdate(ctx,out,&outl,in,512);
2217         }
2218
2219 /* Output the last 'block'.  If the cipher is a block cipher, the last
2220  * block is encoded in such a way so that a wrong decryption will normally be
2221  * detected - again, one of the PKCS standards. */
2222
2223 EVP_EncryptFinal(ctx,out,&outl);
2224
2225 To decrypt, use the EVP_DecryptXXXXX functions except that EVP_DecryptFinal()
2226 will return 0 if the decryption fails (only detectable on block ciphers).
2227
2228 You can also use
2229 EVP_CipherInit()
2230 EVP_CipherUpdate()
2231 EVP_CipherFinal()
2232 which does either encryption or decryption depending on an extra 
2233 parameter to EVP_CipherInit().
2234
2235
2236 To do the base64 encoding,
2237 EVP_EncodeInit()
2238 EVP_EncodeUpdate()
2239 EVP_EncodeFinal()
2240
2241 EVP_DecodeInit()
2242 EVP_DecodeUpdate()
2243 EVP_DecodeFinal()
2244
2245 where the encoding is quite simple, but the decoding can be a bit more 
2246 fun (due to dud input).
2247
2248 EVP_DecodeUpdate() returns -1 for an error on an input line, 0 if the 
2249 'last line' was just processed, and 1 if more lines should be submitted.
2250
2251 EVP_DecodeFinal() returns -1 for an error or 1 if things are ok.
2252
2253 So the loop becomes
2254 EVP_DecodeInit(....)
2255 for (;;)
2256         {
2257         i=EVP_DecodeUpdate(....);
2258         if (i < 0) goto err;
2259
2260         /* process the data */
2261
2262         if (i == 0) break;
2263         }
2264 EVP_DecodeFinal(....);
2265 /* process the data */
2266
2267 The problem in 'enc.c' is that I was stuff the processing up after the 
2268 EVP_DecodeFinal(...) when the for(..) loop was not being run (one line of 
2269 base64 data) and this was because 'enc.c' tries to scan over a file until
2270 it hits the first valid base64 encoded line.
2271
2272 hope this helps a bit.
2273 eric
2274 --
2275 Eric Young                  | BOOL is tri-state according to Bill Gates.
2276 AARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
2277
2278 ==== conf.doc ========================================================
2279
2280 The CONF library.
2281
2282 The CONF library is a simple set of routines that can be used to configure
2283 programs.  It is a superset of the genenv() function with some extra
2284 structure.
2285
2286 The library consists of 5 functions.
2287
2288 LHASH *CONF_load(LHASH *config,char *file);
2289 This function is called to load in a configuration file.  Multiple
2290 configuration files can be loaded, with each subsequent 'load' overwriting
2291 any already defined 'variables'.  If there is an error, NULL is returned.
2292 If config is NULL, a new LHASH structure is created and returned, otherwise
2293 the new data in the 'file' is loaded into the 'config' structure.
2294
2295 void CONF_free(LHASH *config);
2296 This function free()s the data in config.
2297
2298 char *CONF_get_string(LHASH *config,char *section,char *name);
2299 This function returns the string found in 'config' that corresponds to the
2300 'section' and 'name' specified.  Classes and the naming system used will be
2301 discussed later in this document.  If the variable is not defined, an NULL
2302 is returned.
2303
2304 long CONF_get_long(LHASH *config,char *section, char *name);
2305 This function is the same as CONF_get_string() except that it converts the
2306 string to an long and returns it.  If variable is not a number or the
2307 variable does not exist, 0 is returned.  This is a little problematic but I
2308 don't know of a simple way around it.
2309
2310 STACK *CONF_get_section(LHASH *config, char *section);
2311 This function returns a 'stack' of CONF_VALUE items that are all the
2312 items defined in a particular section.  DO NOT free() any of the
2313 variable returned.  They will disappear when CONF_free() is called.
2314
2315 The 'lookup' model.
2316 The configuration file is divided into 'sections'.  Each section is started by
2317 a line of the form '[ section ]'.  All subsequent variable definitions are
2318 of this section.  A variable definition is a simple alpha-numeric name
2319 followed by an '=' and then the data.  A section or variable name can be
2320 described by a regular expression of the following form '[A-Za-z0-9_]+'.
2321 The value of the variable is the text after the '=' until the end of the
2322 line, stripped of leading and trailing white space.
2323 At this point I should mention that a '#' is a comment character, \ is the
2324 escape character, and all three types of quote can be used to stop any
2325 special interpretation of the data.
2326 Now when the data is being loaded, variable expansion can occur.  This is
2327 done by expanding any $NAME sequences into the value represented by the
2328 variable NAME.  If the variable is not in the current section, the different
2329 section can be specified by using the $SECTION::NAME form.  The ${NAME} form
2330 also works and is very useful for expanding variables inside strings.
2331
2332 When a variable is looked up, there are 2 special section. 'default', which
2333 is the initial section, and 'ENV' which is the processes environment
2334 variables (accessed via getenv()).  When a variable is looked up, it is
2335 first 'matched' with it's section (if one was specified), if this fails, the
2336 'default' section is matched.
2337 If the 'lhash' variable passed was NULL, the environment is searched.
2338
2339 Now why do we bother with sections?  So we can have multiple programs using
2340 the same configuration file, or multiple instances of the same program
2341 using different variables.  It also provides a nice mechanism to override
2342 the processes environment variables (eg ENV::HOME=/tmp).  If there is a
2343 program specific variable missing, we can have default values.
2344 Multiple configuration files can be loaded, with each new value clearing
2345 any predefined values.  A system config file can provide 'default' values,
2346 and application/usr specific files can provide overriding values.
2347
2348 Examples
2349
2350 # This is a simple example
2351 SSLEAY_HOME     = /usr/local/ssl
2352 ENV::PATH       = $SSLEAY_HOME/bin:$PATH        # override my path
2353
2354 [X509]
2355 cert_dir        = $SSLEAY_HOME/certs    # /usr/local/ssl/certs
2356
2357 [SSL]
2358 CIPHER          = DES-EDE-MD5:RC4-MD5
2359 USER_CERT       = $HOME/${USER}di'r 5'  # /home/eay/eaydir 5
2360 USER_CERT       = $HOME/\${USER}di\'r   # /home/eay/${USER}di'r
2361 USER_CERT       = "$HOME/${US"ER}di\'r  # $HOME/${USER}di'r
2362
2363 TEST            = 1234\
2364 5678\
2365 9ab                                     # TEST=123456789ab
2366 TTT             = 1234\n\n              # TTT=1234<nl><nl>
2367
2368
2369
2370 ==== des.doc ========================================================
2371
2372 The DES library.
2373
2374 Please note that this library was originally written to operate with
2375 eBones, a version of Kerberos that had had encryption removed when it left
2376 the USA and then put back in.  As such there are some routines that I will
2377 advise not using but they are still in the library for historical reasons.
2378 For all calls that have an 'input' and 'output' variables, they can be the
2379 same.
2380
2381 This library requires the inclusion of 'des.h'.
2382
2383 All of the encryption functions take what is called a des_key_schedule as an 
2384 argument.  A des_key_schedule is an expanded form of the des key.
2385 A des_key is 8 bytes of odd parity, the type used to hold the key is a
2386 des_cblock.  A des_cblock is an array of 8 bytes, often in this library
2387 description I will refer to input bytes when the function specifies
2388 des_cblock's as input or output, this just means that the variable should
2389 be a multiple of 8 bytes.
2390
2391 The define DES_ENCRYPT is passed to specify encryption, DES_DECRYPT to
2392 specify decryption.  The functions and global variable are as follows:
2393
2394 int des_check_key;
2395         DES keys are supposed to be odd parity.  If this variable is set to
2396         a non-zero value, des_set_key() will check that the key has odd
2397         parity and is not one of the known weak DES keys.  By default this
2398         variable is turned off;
2399         
2400 void des_set_odd_parity(
2401 des_cblock *key );
2402         This function takes a DES key (8 bytes) and sets the parity to odd.
2403         
2404 int des_is_weak_key(
2405 des_cblock *key );
2406         This function returns a non-zero value if the DES key passed is a
2407         weak, DES key.  If it is a weak key, don't use it, try a different
2408         one.  If you are using 'random' keys, the chances of hitting a weak
2409         key are 1/2^52 so it is probably not worth checking for them.
2410         
2411 int des_set_key(
2412 des_cblock *key,
2413 des_key_schedule schedule);
2414         Des_set_key converts an 8 byte DES key into a des_key_schedule.
2415         A des_key_schedule is an expanded form of the key which is used to
2416         perform actual encryption.  It can be regenerated from the DES key
2417         so it only needs to be kept when encryption or decryption is about
2418         to occur.  Don't save or pass around des_key_schedule's since they
2419         are CPU architecture dependent, DES keys are not.  If des_check_key
2420         is non zero, zero is returned if the key has the wrong parity or
2421         the key is a weak key, else 1 is returned.
2422         
2423 int des_key_sched(
2424 des_cblock *key,
2425 des_key_schedule schedule);
2426         An alternative name for des_set_key().
2427
2428 int des_rw_mode;                /* defaults to DES_PCBC_MODE */
2429         This flag holds either DES_CBC_MODE or DES_PCBC_MODE (default).
2430         This specifies the function to use in the enc_read() and enc_write()
2431         functions.
2432
2433 void des_encrypt(
2434 unsigned long *data,
2435 des_key_schedule ks,
2436 int enc);
2437         This is the DES encryption function that gets called by just about
2438         every other DES routine in the library.  You should not use this
2439         function except to implement 'modes' of DES.  I say this because the
2440         functions that call this routine do the conversion from 'char *' to
2441         long, and this needs to be done to make sure 'non-aligned' memory
2442         access do not occur.  The characters are loaded 'little endian',
2443         have a look at my source code for more details on how I use this
2444         function.
2445         Data is a pointer to 2 unsigned long's and ks is the
2446         des_key_schedule to use.  enc, is non zero specifies encryption,
2447         zero if decryption.
2448
2449 void des_encrypt2(
2450 unsigned long *data,
2451 des_key_schedule ks,
2452 int enc);
2453         This functions is the same as des_encrypt() except that the DES
2454         initial permutation (IP) and final permutation (FP) have been left
2455         out.  As for des_encrypt(), you should not use this function.
2456         It is used by the routines in my library that implement triple DES.
2457         IP() des_encrypt2() des_encrypt2() des_encrypt2() FP() is the same
2458         as des_encrypt() des_encrypt() des_encrypt() except faster :-).
2459
2460 void des_ecb_encrypt(
2461 des_cblock *input,
2462 des_cblock *output,
2463 des_key_schedule ks,
2464 int enc);
2465         This is the basic Electronic Code Book form of DES, the most basic
2466         form.  Input is encrypted into output using the key represented by
2467         ks.  If enc is non zero (DES_ENCRYPT), encryption occurs, otherwise
2468         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
2469         (the des_cblock structure is 8 chars).
2470         
2471 void des_ecb3_encrypt(
2472 des_cblock *input,
2473 des_cblock *output,
2474 des_key_schedule ks1,
2475 des_key_schedule ks2,
2476 des_key_schedule ks3,
2477 int enc);
2478         This is the 3 key EDE mode of ECB DES.  What this means is that 
2479         the 8 bytes of input is encrypted with ks1, decrypted with ks2 and
2480         then encrypted again with ks3, before being put into output;
2481         C=E(ks3,D(ks2,E(ks1,M))).  There is a macro, des_ecb2_encrypt()
2482         that only takes 2 des_key_schedules that implements,
2483         C=E(ks1,D(ks2,E(ks1,M))) in that the final encrypt is done with ks1.
2484         
2485 void des_cbc_encrypt(
2486 des_cblock *input,
2487 des_cblock *output,
2488 long length,
2489 des_key_schedule ks,
2490 des_cblock *ivec,
2491 int enc);
2492         This routine implements DES in Cipher Block Chaining mode.
2493         Input, which should be a multiple of 8 bytes is encrypted
2494         (or decrypted) to output which will also be a multiple of 8 bytes.
2495         The number of bytes is in length (and from what I've said above,
2496         should be a multiple of 8).  If length is not a multiple of 8, I'm
2497         not being held responsible :-).  ivec is the initialisation vector.
2498         This function does not modify this variable.  To correctly implement
2499         cbc mode, you need to do one of 2 things; copy the last 8 bytes of
2500         cipher text for use as the next ivec in your application,
2501         or use des_ncbc_encrypt(). 
2502         Only this routine has this problem with updating the ivec, all
2503         other routines that are implementing cbc mode update ivec.
2504         
2505 void des_ncbc_encrypt(
2506 des_cblock *input,
2507 des_cblock *output,
2508 long length,
2509 des_key_schedule sk,
2510 des_cblock *ivec,
2511 int enc);
2512         For historical reasons, des_cbc_encrypt() did not update the
2513         ivec with the value requires so that subsequent calls to
2514         des_cbc_encrypt() would 'chain'.  This was needed so that the same
2515         'length' values would not need to be used when decrypting.
2516         des_ncbc_encrypt() does the right thing.  It is the same as
2517         des_cbc_encrypt accept that ivec is updates with the correct value
2518         to pass in subsequent calls to des_ncbc_encrypt().  I advise using
2519         des_ncbc_encrypt() instead of des_cbc_encrypt();
2520
2521 void des_xcbc_encrypt(
2522 des_cblock *input,
2523 des_cblock *output,
2524 long length,
2525 des_key_schedule sk,
2526 des_cblock *ivec,
2527 des_cblock *inw,
2528 des_cblock *outw,
2529 int enc);
2530         This is RSA's DESX mode of DES.  It uses inw and outw to
2531         'whiten' the encryption.  inw and outw are secret (unlike the iv)
2532         and are as such, part of the key.  So the key is sort of 24 bytes.
2533         This is much better than cbc des.
2534         
2535 void des_3cbc_encrypt(
2536 des_cblock *input,
2537 des_cblock *output,
2538 long length,
2539 des_key_schedule sk1,
2540 des_key_schedule sk2,
2541 des_cblock *ivec1,
2542 des_cblock *ivec2,
2543 int enc);
2544         This function is flawed, do not use it.  I have left it in the
2545         library because it is used in my des(1) program and will function
2546         correctly when used by des(1).  If I removed the function, people
2547         could end up unable to decrypt files.
2548         This routine implements outer triple cbc encryption using 2 ks and
2549         2 ivec's.  Use des_ede2_cbc_encrypt() instead.
2550         
2551 void des_ede3_cbc_encrypt(
2552 des_cblock *input,
2553 des_cblock *output, 
2554 long length,
2555 des_key_schedule ks1,
2556 des_key_schedule ks2, 
2557 des_key_schedule ks3, 
2558 des_cblock *ivec,
2559 int enc);
2560         This function implements outer triple CBC DES encryption with 3
2561         keys.  What this means is that each 'DES' operation
2562         inside the cbc mode is really an C=E(ks3,D(ks2,E(ks1,M))).
2563         Again, this is cbc mode so an ivec is requires.
2564         This mode is used by SSL.
2565         There is also a des_ede2_cbc_encrypt() that only uses 2
2566         des_key_schedule's, the first being reused for the final
2567         encryption.  C=E(ks1,D(ks2,E(ks1,M))).  This form of triple DES
2568         is used by the RSAref library.
2569         
2570 void des_pcbc_encrypt(
2571 des_cblock *input,
2572 des_cblock *output,
2573 long length,
2574 des_key_schedule ks,
2575 des_cblock *ivec,
2576 int enc);
2577         This is Propagating Cipher Block Chaining mode of DES.  It is used
2578         by Kerberos v4.  It's parameters are the same as des_ncbc_encrypt().
2579         
2580 void des_cfb_encrypt(
2581 unsigned char *in,
2582 unsigned char *out,
2583 int numbits,
2584 long length,
2585 des_key_schedule ks,
2586 des_cblock *ivec,
2587 int enc);
2588         Cipher Feedback Back mode of DES.  This implementation 'feeds back'
2589         in numbit blocks.  The input (and output) is in multiples of numbits
2590         bits.  numbits should to be a multiple of 8 bits.  Length is the
2591         number of bytes input.  If numbits is not a multiple of 8 bits,
2592         the extra bits in the bytes will be considered padding.  So if
2593         numbits is 12, for each 2 input bytes, the 4 high bits of the
2594         second byte will be ignored.  So to encode 72 bits when using
2595         a numbits of 12 take 12 bytes.  To encode 72 bits when using
2596         numbits of 9 will take 16 bytes.  To encode 80 bits when using
2597         numbits of 16 will take 10 bytes. etc, etc.  This padding will
2598         apply to both input and output.
2599
2600         
2601 void des_cfb64_encrypt(
2602 unsigned char *in,
2603 unsigned char *out,
2604 long length,
2605 des_key_schedule ks,
2606 des_cblock *ivec,
2607 int *num,
2608 int enc);
2609         This is one of the more useful functions in this DES library, it
2610         implements CFB mode of DES with 64bit feedback.  Why is this
2611         useful you ask?  Because this routine will allow you to encrypt an
2612         arbitrary number of bytes, no 8 byte padding.  Each call to this
2613         routine will encrypt the input bytes to output and then update ivec
2614         and num.  num contains 'how far' we are though ivec.  If this does
2615         not make much sense, read more about cfb mode of DES :-).
2616         
2617 void des_ede3_cfb64_encrypt(
2618 unsigned char *in,
2619 unsigned char *out,
2620 long length,
2621 des_key_schedule ks1,
2622 des_key_schedule ks2,
2623 des_key_schedule ks3,
2624 des_cblock *ivec,
2625 int *num,
2626 int enc);
2627         Same as des_cfb64_encrypt() accept that the DES operation is
2628         triple DES.  As usual, there is a macro for
2629         des_ede2_cfb64_encrypt() which reuses ks1.
2630
2631 void des_ofb_encrypt(
2632 unsigned char *in,
2633 unsigned char *out,
2634 int numbits,
2635 long length,
2636 des_key_schedule ks,
2637 des_cblock *ivec);
2638         This is a implementation of Output Feed Back mode of DES.  It is
2639         the same as des_cfb_encrypt() in that numbits is the size of the
2640         units dealt with during input and output (in bits).
2641         
2642 void des_ofb64_encrypt(
2643 unsigned char *in,
2644 unsigned char *out,
2645 long length,
2646 des_key_schedule ks,
2647 des_cblock *ivec,
2648 int *num);
2649         The same as des_cfb64_encrypt() except that it is Output Feed Back
2650         mode.
2651
2652 void des_ede3_ofb64_encrypt(
2653 unsigned char *in,
2654 unsigned char *out,
2655 long length,
2656 des_key_schedule ks1,
2657 des_key_schedule ks2,
2658 des_key_schedule ks3,
2659 des_cblock *ivec,
2660 int *num);
2661         Same as des_ofb64_encrypt() accept that the DES operation is
2662         triple DES.  As usual, there is a macro for
2663         des_ede2_ofb64_encrypt() which reuses ks1.
2664
2665 int des_read_pw_string(
2666 char *buf,
2667 int length,
2668 char *prompt,
2669 int verify);
2670         This routine is used to get a password from the terminal with echo
2671         turned off.  Buf is where the string will end up and length is the
2672         size of buf.  Prompt is a string presented to the 'user' and if
2673         verify is set, the key is asked for twice and unless the 2 copies
2674         match, an error is returned.  A return code of -1 indicates a
2675         system error, 1 failure due to use interaction, and 0 is success.
2676
2677 unsigned long des_cbc_cksum(
2678 des_cblock *input,
2679 des_cblock *output,
2680 long length,
2681 des_key_schedule ks,
2682 des_cblock *ivec);
2683         This function produces an 8 byte checksum from input that it puts in
2684         output and returns the last 4 bytes as a long.  The checksum is
2685         generated via cbc mode of DES in which only the last 8 byes are
2686         kept.  I would recommend not using this function but instead using
2687         the EVP_Digest routines, or at least using MD5 or SHA.  This
2688         function is used by Kerberos v4 so that is why it stays in the
2689         library.
2690         
2691 char *des_fcrypt(
2692 const char *buf,
2693 const char *salt
2694 char *ret);
2695         This is my fast version of the unix crypt(3) function.  This version
2696         takes only a small amount of space relative to other fast
2697         crypt() implementations.  This is different to the normal crypt
2698         in that the third parameter is the buffer that the return value
2699         is written into.  It needs to be at least 14 bytes long.  This
2700         function is thread safe, unlike the normal crypt.
2701
2702 char *crypt(
2703 const char *buf,
2704 const char *salt);
2705         This function calls des_fcrypt() with a static array passed as the
2706         third parameter.  This emulates the normal non-thread safe semantics
2707         of crypt(3).
2708
2709 void des_string_to_key(
2710 char *str,
2711 des_cblock *key);
2712         This function takes str and converts it into a DES key.  I would
2713         recommend using MD5 instead and use the first 8 bytes of output.
2714         When I wrote the first version of these routines back in 1990, MD5
2715         did not exist but I feel these routines are still sound.  This
2716         routines is compatible with the one in MIT's libdes.
2717         
2718 void des_string_to_2keys(
2719 char *str,
2720 des_cblock *key1,
2721 des_cblock *key2);
2722         This function takes str and converts it into 2 DES keys.
2723         I would recommend using MD5 and using the 16 bytes as the 2 keys.
2724         I have nothing against these 2 'string_to_key' routines, it's just
2725         that if you say that your encryption key is generated by using the
2726         16 bytes of an MD5 hash, every-one knows how you generated your
2727         keys.
2728
2729 int des_read_password(
2730 des_cblock *key,
2731 char *prompt,
2732 int verify);
2733         This routine combines des_read_pw_string() with des_string_to_key().
2734
2735 int des_read_2passwords(
2736 des_cblock *key1,
2737 des_cblock *key2,
2738 char *prompt,
2739 int verify);
2740         This routine combines des_read_pw_string() with des_string_to_2key().
2741
2742 void des_random_seed(
2743 des_cblock key);
2744         This routine sets a starting point for des_random_key().
2745         
2746 void des_random_key(
2747 des_cblock ret);
2748         This function return a random key.  Make sure to 'seed' the random
2749         number generator (with des_random_seed()) before using this function.
2750         I personally now use a MD5 based random number system.
2751
2752 int des_enc_read(
2753 int fd,
2754 char *buf,
2755 int len,
2756 des_key_schedule ks,
2757 des_cblock *iv);
2758         This function will write to a file descriptor the encrypted data
2759         from buf.  This data will be preceded by a 4 byte 'byte count' and
2760         will be padded out to 8 bytes.  The encryption is either CBC of
2761         PCBC depending on the value of des_rw_mode.  If it is DES_PCBC_MODE,
2762         pcbc is used, if DES_CBC_MODE, cbc is used.  The default is to use
2763         DES_PCBC_MODE.
2764
2765 int des_enc_write(
2766 int fd,
2767 char *buf,
2768 int len,
2769 des_key_schedule ks,
2770 des_cblock *iv);
2771         This routines read stuff written by des_enc_read() and decrypts it.
2772         I have used these routines quite a lot but I don't believe they are
2773         suitable for non-blocking io.  If you are after a full
2774         authentication/encryption over networks, have a look at SSL instead.
2775
2776 unsigned long des_quad_cksum(
2777 des_cblock *input,
2778 des_cblock *output,
2779 long length,
2780 int out_count,
2781 des_cblock *seed);
2782         This is a function from Kerberos v4 that is not anything to do with
2783         DES but was needed.  It is a cksum that is quicker to generate than
2784         des_cbc_cksum();  I personally would use MD5 routines now.
2785 =====
2786 Modes of DES
2787 Quite a bit of the following information has been taken from
2788         AS 2805.5.2
2789         Australian Standard
2790         Electronic funds transfer - Requirements for interfaces,
2791         Part 5.2: Modes of operation for an n-bit block cipher algorithm
2792         Appendix A
2793
2794 There are several different modes in which DES can be used, they are
2795 as follows.
2796
2797 Electronic Codebook Mode (ECB) (des_ecb_encrypt())
2798 - 64 bits are enciphered at a time.
2799 - The order of the blocks can be rearranged without detection.
2800 - The same plaintext block always produces the same ciphertext block
2801   (for the same key) making it vulnerable to a 'dictionary attack'.
2802 - An error will only affect one ciphertext block.
2803
2804 Cipher Block Chaining Mode (CBC) (des_cbc_encrypt())
2805 - a multiple of 64 bits are enciphered at a time.
2806 - The CBC mode produces the same ciphertext whenever the same
2807   plaintext is encrypted using the same key and starting variable.
2808 - The chaining operation makes the ciphertext blocks dependent on the
2809   current and all preceding plaintext blocks and therefore blocks can not
2810   be rearranged.
2811 - The use of different starting variables prevents the same plaintext
2812   enciphering to the same ciphertext.
2813 - An error will affect the current and the following ciphertext blocks.
2814
2815 Cipher Feedback Mode (CFB) (des_cfb_encrypt())
2816 - a number of bits (j) <= 64 are enciphered at a time.
2817 - The CFB mode produces the same ciphertext whenever the same
2818   plaintext is encrypted using the same key and starting variable.
2819 - The chaining operation makes the ciphertext variables dependent on the
2820   current and all preceding variables and therefore j-bit variables are
2821   chained together and can not be rearranged.
2822 - The use of different starting variables prevents the same plaintext
2823   enciphering to the same ciphertext.
2824 - The strength of the CFB mode depends on the size of k (maximal if
2825   j == k).  In my implementation this is always the case.
2826 - Selection of a small value for j will require more cycles through
2827   the encipherment algorithm per unit of plaintext and thus cause
2828   greater processing overheads.
2829 - Only multiples of j bits can be enciphered.
2830 - An error will affect the current and the following ciphertext variables.
2831
2832 Output Feedback Mode (OFB) (des_ofb_encrypt())
2833 - a number of bits (j) <= 64 are enciphered at a time.
2834 - The OFB mode produces the same ciphertext whenever the same
2835   plaintext enciphered using the same key and starting variable.  More
2836   over, in the OFB mode the same key stream is produced when the same
2837   key and start variable are used.  Consequently, for security reasons
2838   a specific start variable should be used only once for a given key.
2839 - The absence of chaining makes the OFB more vulnerable to specific attacks.
2840 - The use of different start variables values prevents the same
2841   plaintext enciphering to the same ciphertext, by producing different
2842   key streams.
2843 - Selection of a small value for j will require more cycles through
2844   the encipherment algorithm per unit of plaintext and thus cause
2845   greater processing overheads.
2846 - Only multiples of j bits can be enciphered.
2847 - OFB mode of operation does not extend ciphertext errors in the
2848   resultant plaintext output.  Every bit error in the ciphertext causes
2849   only one bit to be in error in the deciphered plaintext.
2850 - OFB mode is not self-synchronising.  If the two operation of
2851   encipherment and decipherment get out of synchronism, the system needs
2852   to be re-initialised.
2853 - Each re-initialisation should use a value of the start variable
2854  different from the start variable values used before with the same
2855  key.  The reason for this is that an identical bit stream would be
2856  produced each time from the same parameters.  This would be
2857  susceptible to a ' known plaintext' attack.
2858
2859 Triple ECB Mode (des_ecb3_encrypt())
2860 - Encrypt with key1, decrypt with key2 and encrypt with key3 again.
2861 - As for ECB encryption but increases the key length to 168 bits.
2862   There are theoretic attacks that can be used that make the effective
2863   key length 112 bits, but this attack also requires 2^56 blocks of
2864   memory, not very likely, even for the NSA.
2865 - If both keys are the same it is equivalent to encrypting once with
2866   just one key.
2867 - If the first and last key are the same, the key length is 112 bits.
2868   There are attacks that could reduce the key space to 55 bit's but it
2869   requires 2^56 blocks of memory.
2870 - If all 3 keys are the same, this is effectively the same as normal
2871   ecb mode.
2872
2873 Triple CBC Mode (des_ede3_cbc_encrypt())
2874 - Encrypt with key1, decrypt with key2 and then encrypt with key3.
2875 - As for CBC encryption but increases the key length to 168 bits with
2876   the same restrictions as for triple ecb mode.
2877
2878 ==== digest.doc ========================================================
2879
2880
2881 The Message Digest subroutines.
2882
2883 These routines require "evp.h" to be included.
2884
2885 These functions are a higher level interface to the various message digest
2886 routines found in this library.  As such, they allow the same code to be
2887 used to digest via different algorithms with only a change in an initial
2888 parameter.  They are basically just a front-end to the MD2, MD5, SHA
2889 and SHA1
2890 routines.
2891
2892 These routines all take a pointer to the following structure to specify
2893 which message digest algorithm to use.
2894 typedef struct evp_md_st
2895         {
2896         int type;
2897         int pkey_type;
2898         int md_size;
2899         void (*init)();
2900         void (*update)();
2901         void (*final)();
2902
2903         int required_pkey_type; /*EVP_PKEY_xxx */
2904         int (*sign)();
2905         int (*verify)();
2906         } EVP_MD;
2907
2908 If additional message digest algorithms are to be supported, a structure of
2909 this type needs to be declared and populated and then the Digest routines
2910 can be used with that algorithm.  The type field is the object NID of the
2911 digest type (read the section on Objects for an explanation).  The pkey_type
2912 is the Object type to use when the a message digest is generated by there
2913 routines and then is to be signed with the pkey algorithm.  Md_size is
2914 the size of the message digest returned.  Init, update
2915 and final are the relevant functions to perform the message digest function
2916 by parts.  One reason for specifying the message digest to use via this
2917 mechanism is that if you only use md5, only the md5 routines will
2918 be included in you linked program.  If you passed an integer
2919 that specified which message digest to use, the routine that mapped that
2920 integer to a set of message digest functions would cause all the message
2921 digests functions to be link into the code.  This setup also allows new
2922 message digest functions to be added by the application.
2923
2924 The six message digests defined in this library are
2925
2926 EVP_MD *EVP_md2(void);  /* RSA sign/verify */
2927 EVP_MD *EVP_md5(void);  /* RSA sign/verify */
2928 EVP_MD *EVP_sha(void);  /* RSA sign/verify */
2929 EVP_MD *EVP_sha1(void); /* RSA sign/verify */
2930 EVP_MD *EVP_dss(void);  /* DSA sign/verify */
2931 EVP_MD *EVP_dss1(void); /* DSA sign/verify */
2932
2933 All the message digest routines take a EVP_MD_CTX pointer as an argument.
2934 The state of the message digest is kept in this structure.
2935
2936 typedef struct pem_md_ctx_st
2937         {
2938         EVP_MD *digest;
2939         union   {
2940                 unsigned char base[4]; /* this is used in my library as a
2941                                         * 'pointer' to all union elements
2942                                         * structures. */
2943                 MD2_CTX md2;
2944                 MD5_CTX md5;
2945                 SHA_CTX sha;
2946                 } md;
2947         } EVP_MD_CTX;
2948
2949 The Digest functions are as follows.
2950
2951 void EVP_DigestInit(
2952 EVP_MD_CTX *ctx,
2953 EVP_MD *type);
2954         This function is used to initialise the EVP_MD_CTX.  The message
2955         digest that will associated with 'ctx' is specified by 'type'.
2956
2957 void EVP_DigestUpdate(
2958 EVP_MD_CTX *ctx,
2959 unsigned char *data,
2960 unsigned int cnt);
2961         This function is used to pass more data to the message digest
2962         function.  'cnt' bytes are digested from 'data'.
2963
2964 void EVP_DigestFinal(
2965 EVP_MD_CTX *ctx,
2966 unsigned char *md,
2967 unsigned int *len);
2968         This function finishes the digestion and puts the message digest
2969         into 'md'.  The length of the message digest is put into len;
2970         EVP_MAX_MD_SIZE is the size of the largest message digest that
2971         can be returned from this function.  Len can be NULL if the
2972         size of the digest is not required.
2973         
2974
2975 ==== encode.doc ========================================================
2976
2977
2978 void    EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
2979 void    EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,
2980                 int *outl,unsigned char *in,int inl);
2981 void    EVP_EncodeFinal(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl);
2982 int     EVP_EncodeBlock(unsigned char *t, unsigned char *f, int n);
2983
2984 void    EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
2985 int     EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
2986                 unsigned char *in, int inl);
2987 int     EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
2988                 char *out, int *outl);
2989 int     EVP_DecodeBlock(unsigned char *t, unsigned
2990                 char *f, int n);
2991
2992
2993 ==== envelope.doc ========================================================
2994
2995 The following routines are use to create 'digital' envelopes.
2996 By this I mean that they perform various 'higher' level cryptographic
2997 functions.  Have a read of 'cipher.doc' and 'digest.doc' since those
2998 routines are used by these functions.
2999 cipher.doc contains documentation about the cipher part of the
3000 envelope library and digest.doc contatins the description of the
3001 message digests supported.
3002
3003 To 'sign' a document involves generating a message digest and then encrypting
3004 the digest with an private key.
3005
3006 #define EVP_SignInit(a,b)               EVP_DigestInit(a,b)
3007 #define EVP_SignUpdate(a,b,c)           EVP_DigestUpdate(a,b,c)
3008 Due to the fact this operation is basically just an extended message
3009 digest, the first 2 functions are macro calls to Digest generating
3010 functions.
3011
3012 int     EVP_SignFinal(
3013 EVP_MD_CTX *ctx,
3014 unsigned char *md,
3015 unsigned int *s,
3016 EVP_PKEY *pkey);
3017         This finalisation function finishes the generation of the message
3018 digest and then encrypts the digest (with the correct message digest 
3019 object identifier) with the EVP_PKEY private key.  'ctx' is the message digest
3020 context.  'md' will end up containing the encrypted message digest.  This
3021 array needs to be EVP_PKEY_size(pkey) bytes long.  's' will actually
3022 contain the exact length.  'pkey' of course is the private key.  It is
3023 one of EVP_PKEY_RSA or EVP_PKEY_DSA type.
3024 If there is an error, 0 is returned, otherwise 1.
3025                 
3026 Verify is used to check an signed message digest.
3027
3028 #define EVP_VerifyInit(a,b)             EVP_DigestInit(a,b)
3029 #define EVP_VerifyUpdate(a,b,c)         EVP_DigestUpdate(a,b,c)
3030 Since the first step is to generate a message digest, the first 2 functions
3031 are macros.
3032
3033 int EVP_VerifyFinal(
3034 EVP_MD_CTX *ctx,
3035 unsigned char *md,
3036 unsigned int s,
3037 EVP_PKEY *pkey);
3038         This function finishes the generation of the message digest and then
3039 compares it with the supplied encrypted message digest.  'md' contains the
3040 's' bytes of encrypted message digest.  'pkey' is used to public key decrypt
3041 the digest.  It is then compared with the message digest just generated.
3042 If they match, 1 is returned else 0.
3043
3044 int     EVP_SealInit(EVP_CIPHER_CTX *ctx, EVP_CIPHER *type, unsigned char **ek,
3045                 int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk);
3046 Must have at least one public key, error is 0.  I should also mention that
3047 the buffers pointed to by 'ek' need to be EVP_PKEY_size(pubk[n]) is size.
3048
3049 #define EVP_SealUpdate(a,b,c,d,e)       EVP_EncryptUpdate(a,b,c,d,e)    
3050 void    EVP_SealFinal(EVP_CIPHER_CTX *ctx,unsigned char *out,int *outl);
3051
3052
3053 int     EVP_OpenInit(EVP_CIPHER_CTX *ctx,EVP_CIPHER *type,unsigned char *ek,
3054                 int ekl,unsigned char *iv,EVP_PKEY *priv);
3055 0 on failure
3056
3057 #define EVP_OpenUpdate(a,b,c,d,e)       EVP_DecryptUpdate(a,b,c,d,e)
3058
3059 int     EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
3060 Decrypt final return code
3061
3062
3063 ==== error.doc ========================================================
3064
3065 The error routines.
3066
3067 The 'error' system I've implemented is intended to server 2 purpose, to
3068 record the reason why a command failed and to record where in the libraries
3069 the failure occurred.  It is more or less setup to record a 'trace' of which
3070 library components were being traversed when the error occurred.
3071
3072 When an error is recorded, it is done so a as single unsigned long which is
3073 composed of three parts.  The top byte is the 'library' number, the middle
3074 12 bytes is the function code, and the bottom 12 bits is the 'reason' code.
3075
3076 Each 'library', or should a say, 'section' of the SSLeay library has a
3077 different unique 'library' error number.  Each function in the library has
3078 a number that is unique for that library.  Each 'library' also has a number
3079 for each 'error reason' that is only unique for that 'library'.
3080
3081 Due to the way these error routines record a 'error trace', there is an
3082 array per thread that is used to store the error codes.
3083 The various functions in this library are used to access
3084 and manipulate this array.
3085
3086 void ERR_put_error(int lib, int func,int reason);
3087         This routine records an error in library 'lib', function 'func'
3088 and reason 'reason'.  As errors get 'put' into the buffer, they wrap
3089 around and overwrite old errors if too many are written.  It is assumed
3090 that the last errors are the most important.
3091
3092 unsigned long ERR_get_error(void );
3093         This function returns the last error added to the error buffer.
3094 In effect it is popping the value off the buffer so repeated calls will
3095 continue to return values until there are no more errors to return in which
3096 case 0 is returned.
3097
3098 unsigned long ERR_peek_error(void );
3099         This function returns the value of the last error added to the
3100 error buffer but does not 'pop' it from the buffer.
3101
3102 void ERR_clear_error(void );
3103         This function clears the error buffer, discarding all unread
3104 errors.
3105
3106 While the above described error system obviously produces lots of different
3107 error number, a method for 'reporting' these errors in a human readable
3108 form is required.  To achieve this, each library has the option of
3109 'registering' error strings.
3110
3111 typedef struct ERR_string_data_st
3112         {
3113         unsigned long error;
3114         char *string;
3115         } ERR_STRING_DATA;
3116
3117 The 'ERR_STRING_DATA' contains an error code and the corresponding text
3118 string.  To add new function error strings for a library, the
3119 ERR_STRING_DATA needs to be 'registered' with the library.
3120
3121 void ERR_load_strings(unsigned long lib,ERR_STRING_DATA *err);
3122         This function 'registers' the array of ERR_STRING_DATA pointed to by
3123 'err' as error text strings for the error library 'lib'.
3124
3125 void ERR_free_strings(void);
3126         This function free()s all the loaded error strings.
3127
3128 char *ERR_error_string(unsigned long error,char *buf);
3129         This function returns a text string that is a human readable
3130 version of the error represented by 'error'.  Buff should be at least 120
3131 bytes long and if it is NULL, the return value is a pointer to a static
3132 variable that will contain the error string, otherwise 'buf' is returned.
3133 If there is not a text string registered for a particular error, a text
3134 string containing the error number is returned instead.
3135
3136 void ERR_print_errors(BIO *bp);
3137 void ERR_print_errors_fp(FILE *fp);
3138         This function is a convenience routine that prints the error string
3139 for each error until all errors have been accounted for.
3140
3141 char *ERR_lib_error_string(unsigned long e);
3142 char *ERR_func_error_string(unsigned long e);
3143 char *ERR_reason_error_string(unsigned long e);
3144 The above three functions return the 3 different components strings for the
3145 error 'e'.  ERR_error_string() uses these functions.
3146
3147 void ERR_load_ERR_strings(void );
3148         This function 'registers' the error strings for the 'ERR' module.
3149
3150 void ERR_load_crypto_strings(void );
3151         This function 'register' the error strings for just about every
3152 library in the SSLeay package except for the SSL routines.  There is no
3153 need to ever register any error text strings and you will probably save in
3154 program size.  If on the other hand you do 'register' all errors, it is
3155 quite easy to determine why a particular routine failed.
3156
3157 As a final footnote as to why the error system is designed as it is.
3158 1) I did not want a single 'global' error code.
3159 2) I wanted to know which subroutine a failure occurred in.
3160 3) For Windows NT etc, it should be simple to replace the 'key' routines
3161    with code to pass error codes back to the application.
3162 4) I wanted the option of meaningful error text strings.
3163
3164 Late breaking news - the changes to support threads.
3165
3166 Each 'thread' has an 'ERR_STATE' state associated with it.
3167 ERR_STATE *ERR_get_state(void ) will return the 'state' for the calling
3168 thread/process.
3169
3170 ERR_remove_state(unsigned long pid); will 'free()' this state.  If pid == 0
3171 the current 'thread/process' will have it's error state removed.
3172 If you do not remove the error state of a thread, this could be considered a
3173 form of memory leak, so just after 'reaping' a thread that has died,
3174 call ERR_remove_state(pid).
3175
3176 Have a read of thread.doc for more details for what is required for
3177 multi-threading support.  All the other error routines will
3178 work correctly when using threads.
3179
3180
3181 ==== idea.doc ========================================================
3182
3183 The IDEA library.
3184 IDEA is a block cipher that operates on 64bit (8 byte) quantities.  It
3185 uses a 128bit (16 byte) key.  It can be used in all the modes that DES can
3186 be used.  This library implements the ecb, cbc, cfb64 and ofb64 modes.
3187
3188 For all calls that have an 'input' and 'output' variables, they can be the
3189 same.
3190
3191 This library requires the inclusion of 'idea.h'.
3192
3193 All of the encryption functions take what is called an IDEA_KEY_SCHEDULE as an 
3194 argument.  An IDEA_KEY_SCHEDULE is an expanded form of the idea key.
3195 For all modes of the IDEA algorithm, the IDEA_KEY_SCHEDULE used for
3196 decryption is different to the one used for encryption.
3197
3198 The define IDEA_ENCRYPT is passed to specify encryption for the functions
3199 that require an encryption/decryption flag. IDEA_DECRYPT is passed to
3200 specify decryption.  For some mode there is no encryption/decryption
3201 flag since this is determined by the IDEA_KEY_SCHEDULE.
3202
3203 So to encrypt you would do the following
3204 idea_set_encrypt_key(key,encrypt_ks);
3205 idea_ecb_encrypt(...,encrypt_ks);
3206 idea_cbc_encrypt(....,encrypt_ks,...,IDEA_ENCRYPT);
3207
3208 To Decrypt
3209 idea_set_encrypt_key(key,encrypt_ks);
3210 idea_set_decrypt_key(encrypt_ks,decrypt_ks);
3211 idea_ecb_encrypt(...,decrypt_ks);
3212 idea_cbc_encrypt(....,decrypt_ks,...,IDEA_DECRYPT);
3213
3214 Please note that any of the encryption modes specified in my DES library
3215 could be used with IDEA.  I have only implemented ecb, cbc, cfb64 and
3216 ofb64 for the following reasons.
3217 - ecb is the basic IDEA encryption.
3218 - cbc is the normal 'chaining' form for block ciphers.
3219 - cfb64 can be used to encrypt single characters, therefore input and output
3220   do not need to be a multiple of 8.
3221 - ofb64 is similar to cfb64 but is more like a stream cipher, not as
3222   secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
3223 - If you want triple IDEA, thats 384 bits of key and you must be totally
3224   obsessed with security.  Still, if you want it, it is simple enough to
3225   copy the function from the DES library and change the des_encrypt to
3226   idea_encrypt; an exercise left for the paranoid reader :-).
3227
3228 The functions are as follows:
3229
3230 void idea_set_encrypt_key(
3231 unsigned char *key;
3232 IDEA_KEY_SCHEDULE *ks);
3233         idea_set_encrypt_key converts a 16 byte IDEA key into an
3234         IDEA_KEY_SCHEDULE.  The IDEA_KEY_SCHEDULE is an expanded form of
3235         the key which can be used to perform IDEA encryption.
3236         An IDEA_KEY_SCHEDULE is an expanded form of the key which is used to
3237         perform actual encryption.  It can be regenerated from the IDEA key
3238         so it only needs to be kept when encryption is about
3239         to occur.  Don't save or pass around IDEA_KEY_SCHEDULE's since they
3240         are CPU architecture dependent, IDEA keys are not.
3241         
3242 void idea_set_decrypt_key(
3243 IDEA_KEY_SCHEDULE *encrypt_ks,
3244 IDEA_KEY_SCHEDULE *decrypt_ks);
3245         This functions converts an encryption IDEA_KEY_SCHEDULE into a
3246         decryption IDEA_KEY_SCHEDULE.  For all decryption, this conversion
3247         of the key must be done.  In some modes of IDEA, an
3248         encryption/decryption flag is also required, this is because these
3249         functions involve block chaining and the way this is done changes
3250         depending on which of encryption of decryption is being done.
3251         Please note that there is no quick way to generate the decryption
3252         key schedule other than generating the encryption key schedule and
3253         then converting it.
3254
3255 void idea_encrypt(
3256 unsigned long *data,
3257 IDEA_KEY_SCHEDULE *ks);
3258         This is the IDEA encryption function that gets called by just about
3259         every other IDEA routine in the library.  You should not use this
3260         function except to implement 'modes' of IDEA.  I say this because the
3261         functions that call this routine do the conversion from 'char *' to
3262         long, and this needs to be done to make sure 'non-aligned' memory
3263         access do not occur.
3264         Data is a pointer to 2 unsigned long's and ks is the
3265         IDEA_KEY_SCHEDULE to use.  Encryption or decryption depends on the
3266         IDEA_KEY_SCHEDULE.
3267
3268 void idea_ecb_encrypt(
3269 unsigned char *input,
3270 unsigned char *output,
3271 IDEA_KEY_SCHEDULE *ks);
3272         This is the basic Electronic Code Book form of IDEA (in DES this
3273         mode is called Electronic Code Book so I'm going to use the term
3274         for idea as well :-).
3275         Input is encrypted into output using the key represented by
3276         ks.  Depending on the IDEA_KEY_SCHEDULE, encryption or
3277         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
3278         
3279 void idea_cbc_encrypt(
3280 unsigned char *input,
3281 unsigned char *output,
3282 long length,
3283 IDEA_KEY_SCHEDULE *ks,
3284 unsigned char *ivec,
3285 int enc);
3286         This routine implements IDEA in Cipher Block Chaining mode.
3287         Input, which should be a multiple of 8 bytes is encrypted
3288         (or decrypted) to output which will also be a multiple of 8 bytes.
3289         The number of bytes is in length (and from what I've said above,
3290         should be a multiple of 8).  If length is not a multiple of 8, bad 
3291         things will probably happen.  ivec is the initialisation vector.
3292         This function updates iv after each call so that it can be passed to
3293         the next call to idea_cbc_encrypt().
3294         
3295 void idea_cfb64_encrypt(
3296 unsigned char *in,
3297 unsigned char *out,
3298 long length,
3299 des_key_schedule ks,
3300 des_cblock *ivec,
3301 int *num,
3302 int enc);
3303         This is one of the more useful functions in this IDEA library, it
3304         implements CFB mode of IDEA with 64bit feedback.
3305         This allows you to encrypt an arbitrary number of bytes,
3306         you do not require 8 byte padding.  Each call to this
3307         routine will encrypt the input bytes to output and then update ivec
3308         and num.  Num contains 'how far' we are though ivec.
3309         Enc is used to indicate encryption or decryption.
3310         One very important thing to remember is that when decrypting, use
3311         the encryption form of the key.
3312         CFB64 mode operates by using the cipher to
3313         generate a stream of bytes which is used to encrypt the plain text.
3314         The cipher text is then encrypted to generate the next 64 bits to
3315         be xored (incrementally) with the next 64 bits of plain
3316         text.  As can be seen from this, to encrypt or decrypt,
3317         the same 'cipher stream' needs to be generated but the way the next
3318         block of data is gathered for encryption is different for
3319         encryption and decryption.  What this means is that to encrypt
3320         idea_set_encrypt_key(key,ks);
3321         idea_cfb64_encrypt(...,ks,..,IDEA_ENCRYPT)
3322         do decrypt
3323         idea_set_encrypt_key(key,ks)
3324         idea_cfb64_encrypt(...,ks,...,IDEA_DECRYPT)
3325         Note: The same IDEA_KEY_SCHEDULE but different encryption flags.
3326         For idea_cbc or idea_ecb, idea_set_decrypt_key() would need to be
3327         used to generate the IDEA_KEY_SCHEDULE for decryption.
3328         The reason I'm stressing this point is that I just wasted 3 hours
3329         today trying to decrypt using this mode and the decryption form of
3330         the key :-(.
3331         
3332 void idea_ofb64_encrypt(
3333 unsigned char *in,
3334 unsigned char *out,
3335 long length,
3336 des_key_schedule ks,
3337 des_cblock *ivec,
3338 int *num);
3339         This functions implements OFB mode of IDEA with 64bit feedback.
3340         This allows you to encrypt an arbitrary number of bytes,
3341         you do not require 8 byte padding.  Each call to this
3342         routine will encrypt the input bytes to output and then update ivec
3343         and num.  Num contains 'how far' we are though ivec.
3344         This is in effect a stream cipher, there is no encryption or
3345         decryption mode.  The same key and iv should be used to
3346         encrypt and decrypt.
3347         
3348 For reading passwords, I suggest using des_read_pw_string() from my DES library.
3349 To generate a password from a text string, I suggest using MD5 (or MD2) to
3350 produce a 16 byte message digest that can then be passed directly to
3351 idea_set_encrypt_key().
3352
3353 =====
3354 For more information about the specific IDEA modes in this library
3355 (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
3356 documentation on my DES library.  What is said about DES is directly
3357 applicable for IDEA.
3358
3359
3360 ==== legal.doc ========================================================
3361
3362 From eay@mincom.com Thu Jun 27 00:25:45 1996
3363 Received: by orb.mincom.oz.au id AA15821
3364   (5.65c/IDA-1.4.4 for eay); Wed, 26 Jun 1996 14:25:45 +1000
3365 Date: Wed, 26 Jun 1996 14:25:45 +1000 (EST)
3366 From: Eric Young <eay@mincom.oz.au>
3367 X-Sender: eay@orb
3368 To: Ken Toll <ktoll@ren.digitalage.com>
3369 Cc: Eric Young <eay@mincom.oz.au>, ssl-talk@netscape.com
3370 Subject: Re: Unidentified subject!
3371 In-Reply-To: <9606261950.ZM28943@ren.digitalage.com>
3372 Message-Id: <Pine.SOL.3.91.960626131156.28573K-100000@orb>
3373 Mime-Version: 1.0
3374 Content-Type: TEXT/PLAIN; charset=US-ASCII
3375 Status: O
3376 X-Status: 
3377
3378
3379 This is a little off topic but since SSLeay is a free implementation of
3380 the SSLv2 protocol, I feel it is worth responding on the topic of if it 
3381 is actually legal for Americans to use free cryptographic software.
3382
3383 On Wed, 26 Jun 1996, Ken Toll wrote:
3384 > Is the U.S the only country that SSLeay cannot be used commercially 
3385 > (because of RSAref) or is that going to be an issue with every country 
3386 > that a client/server application (non-web browser/server) is deployed 
3387 > and sold?
3388
3389 >From what I understand, the software patents that apply to algorithms 
3390 like RSA and DH only apply in the USA.  The IDEA algorithm I believe is 
3391 patened in europe (USA?), but considing how little it is used by other SSL 
3392 implementations, it quite easily be left out of the SSLeay build
3393 (this can be done with a compile flag).
3394
3395 Actually if the RSA patent did apply outside the USA, it could be rather
3396 interesting since RSA is not alowed to let RSA toolkits outside of the USA
3397 [1], and since these are the only forms that they will alow the algorithm
3398 to be used in, it would mean that non-one outside of the USA could produce
3399 public key software which would be a very strong statment for
3400 international patent law to make :-).  This logic is a little flawed but
3401 it still points out some of the more interesting permutations of USA
3402 patent law and ITAR restrictions. 
3403
3404 Inside the USA there is also the unresolved issue of RC4/RC2 which were
3405 made public on sci.crypt in Sep 1994 (RC4) and Feb 1996 (RC2).  I have
3406 copies of the origional postings if people are interested.  RSA I believe 
3407 claim that they were 'trade-secrets' and that some-one broke an NDA in 
3408 revealing them.  Other claim they reverse engineered the algorithms from 
3409 compiled binaries.  If the algorithms were reverse engineered, I belive 
3410 RSA had no legal leg to stand on.  If an NDA was broken, I don't know.
3411 Regardless, RSA, I belive, is willing to go to court over the issue so 
3412 licencing is probably the best idea, or at least talk to them.
3413 If there are people who actually know more about this, pease let me know, I 
3414 don't want to vilify or spread miss-information if I can help it.
3415
3416 If you are not producing a web browser, it is easy to build SSLeay with
3417 RC2/RC4 removed. Since RC4 is the defacto standard cipher in 
3418 all web software (and it is damn fast) it is more or less required for 
3419 www use. For non www use of SSL, especially for an application where 
3420 interoperability with other vendors is not critical just leave it out.
3421
3422 Removing IDEA, RC2 and RC4 would only leave DES and Triple DES but 
3423 they should be ok.  Considing that Triple DES can encrypt at rates of
3424 410k/sec on a pentium 100, and 940k/sec on a P6/200, this is quite 
3425 reasonable performance.  Single DES clocks in at 1160k/s and 2467k/s
3426 respectivly is actually quite fast for those not so paranoid (56 bit key).[1]
3427
3428 > Is it possible to get a certificate for commercial use outside of the U.S.?
3429 yes.
3430
3431 Thawte Consulting issues certificates (they are the people who sell the
3432         Sioux httpd server and are based in South Africa)
3433 Verisign will issue certificates for Sioux (sold from South Africa), so this
3434         proves that they will issue certificate for OS use if they are
3435         happy with the quality of the software.
3436
3437 (The above mentioned companies just the ones that I know for sure are issuing
3438  certificates outside the USA).
3439
3440 There is always the point that if you are using SSL for an intra net, 
3441 SSLeay provides programs that can be used so you can issue your own 
3442 certificates.  They need polishing but at least it is a good starting point.
3443
3444 I am not doing anything outside Australian law by implementing these
3445 algorithms (to the best of my knowedge).  It is another example of how 
3446 the world legal system does not cope with the internet very well.
3447
3448 I may start making shared libraries available (I have now got DLL's for 
3449 Windows).  This will mean that distributions into the usa could be 
3450 shipped with a version with a reduced cipher set and the versions outside 
3451 could use the DLL/shared library with all the ciphers (and without RSAref).
3452
3453 This could be completly hidden from the application, so this would not 
3454 even require a re-linking.
3455
3456 This is the reverse of what people were talking about doing to get around 
3457 USA export regulations :-)
3458
3459 eric
3460
3461 [1]:    The RSAref2.0 tookit is available on at least 3 ftp sites in Europe
3462         and one in South Africa.
3463
3464 [2]:    Since I always get questions when I post benchmark numbers :-),
3465         DES performace figures are in 1000's of bytes per second in cbc 
3466         mode using an 8192 byte buffer.  The pentium 100 was running Windows NT 
3467         3.51 DLLs and the 686/200 was running NextStep.
3468         I quote pentium 100 benchmarks because it is basically the
3469         'entry level' computer that most people buy for personal use.
3470         Windows 95 is the OS shipping on those boxes, so I'll give
3471         NT numbers (the same Win32 runtime environment).  The 686
3472         numbers are present as an indication of where we will be in a
3473         few years.
3474 --
3475 Eric Young                  | BOOL is tri-state according to Bill Gates.
3476 AARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
3477
3478
3479
3480 ==== lhash.doc ========================================================
3481
3482 The LHASH library.
3483
3484 I wrote this library in 1991 and have since forgotten why I called it lhash.
3485 It implements a hash table from an article I read at the
3486 time from 'Communications of the ACM'.  What makes this hash
3487 table different is that as the table fills, the hash table is
3488 increased (or decreased) in size via realloc().
3489 When a 'resize' is done, instead of all hashes being redistributed over
3490 twice as many 'buckets', one bucket is split.  So when an 'expand' is done,
3491 there is only a minimal cost to redistribute some values.  Subsequent
3492 inserts will cause more single 'bucket' redistributions but there will
3493 never be a sudden large cost due to redistributing all the 'buckets'.
3494
3495 The state for a particular hash table is kept in the LHASH structure.
3496 The LHASH structure also records statistics about most aspects of accessing
3497 the hash table.  This is mostly a legacy of my writing this library for
3498 the reasons of implementing what looked like a nice algorithm rather than
3499 for a particular software product.
3500
3501 Internal stuff you probably don't want to know about.
3502 The decision to increase or decrease the hash table size is made depending
3503 on the 'load' of the hash table.  The load is the number of items in the
3504 hash table divided by the size of the hash table.  The default values are
3505 as follows.  If (hash->up_load < load) => expand.
3506 if (hash->down_load > load) =>  contract.  The 'up_load' has a default value of
3507 1 and 'down_load' has a default value of 2.  These numbers can be modified
3508 by the application by just playing with the 'up_load' and 'down_load'
3509 variables.  The 'load' is kept in a form which is multiplied by 256.  So
3510 hash->up_load=8*256; will cause a load of 8 to be set.
3511
3512 If you are interested in performance the field to watch is
3513 num_comp_calls.  The hash library keeps track of the 'hash' value for
3514 each item so when a lookup is done, the 'hashes' are compared, if
3515 there is a match, then a full compare is done, and
3516 hash->num_comp_calls is incremented.  If num_comp_calls is not equal
3517 to num_delete plus num_retrieve it means that your hash function is
3518 generating hashes that are the same for different values.  It is
3519 probably worth changing your hash function if this is the case because
3520 even if your hash table has 10 items in a 'bucked', it can be searched
3521 with 10 'unsigned long' compares and 10 linked list traverses.  This
3522 will be much less expensive that 10 calls to you compare function.
3523
3524 LHASH *lh_new(
3525 unsigned long (*hash)(),
3526 int (*cmp)());
3527         This function is used to create a new LHASH structure.  It is passed
3528         function pointers that are used to store and retrieve values passed
3529         into the hash table.  The 'hash'
3530         function is a hashing function that will return a hashed value of
3531         it's passed structure.  'cmp' is passed 2 parameters, it returns 0
3532         is they are equal, otherwise, non zero.
3533         If there are any problems (usually malloc failures), NULL is
3534         returned, otherwise a new LHASH structure is returned.  The
3535         hash value is normally truncated to a power of 2, so make sure
3536         that your hash function returns well mixed low order bits.
3537         
3538 void lh_free(
3539 LHASH *lh);
3540         This function free()s a LHASH structure.  If there is malloced
3541         data in the hash table, it will not be freed.  Consider using the
3542         lh_doall function to deallocate any remaining entries in the hash
3543         table.
3544         
3545 char *lh_insert(
3546 LHASH *lh,
3547 char *data);
3548         This function inserts the data pointed to by data into the lh hash
3549         table.  If there is already and entry in the hash table entry, the
3550         value being replaced is returned.  A NULL is returned if the new
3551         entry does not clash with an entry already in the table (the normal
3552         case) or on a malloc() failure (perhaps I should change this....).
3553         The 'char *data' is exactly what is passed to the hash and
3554         comparison functions specified in lh_new().
3555         
3556 char *lh_delete(
3557 LHASH *lh,
3558 char *data);
3559         This routine deletes an entry from the hash table.  The value being
3560         deleted is returned.  NULL is returned if there is no such value in
3561         the hash table.
3562
3563 char *lh_retrieve(
3564 LHASH *lh,
3565 char *data);
3566         If 'data' is in the hash table it is returned, else NULL is
3567         returned.  The way these routines would normally be uses is that a
3568         dummy structure would have key fields populated and then
3569         ret=lh_retrieve(hash,&dummy);.  Ret would now be a pointer to a fully
3570         populated structure.
3571
3572 void lh_doall(
3573 LHASH *lh,
3574 void (*func)(char *a));
3575         This function will, for every entry in the hash table, call function
3576         'func' with the data item as parameters.
3577         This function can be quite useful when used as follows.
3578         void cleanup(STUFF *a)
3579                 { STUFF_free(a); }
3580         lh_doall(hash,cleanup);
3581         lh_free(hash);
3582         This can be used to free all the entries, lh_free() then
3583         cleans up the 'buckets' that point to nothing.  Be careful
3584         when doing this.  If you delete entries from the hash table,
3585         in the call back function, the table may decrease in size,
3586         moving item that you are
3587         currently on down lower in the hash table.  This could cause
3588         some entries to be skipped.  The best solution to this problem
3589         is to set lh->down_load=0 before you start.  This will stop
3590         the hash table ever being decreased in size.
3591
3592 void lh_doall_arg(
3593 LHASH *lh;
3594 void(*func)(char *a,char *arg));
3595 char *arg;
3596         This function is the same as lh_doall except that the function
3597         called will be passed 'arg' as the second argument.
3598         
3599 unsigned long lh_strhash(
3600 char *c);
3601         This function is a demo string hashing function.  Since the LHASH
3602         routines would normally be passed structures, this routine would
3603         not normally be passed to lh_new(), rather it would be used in the
3604         function passed to lh_new().
3605
3606 The next three routines print out various statistics about the state of the
3607 passed hash table.  These numbers are all kept in the lhash structure.
3608
3609 void lh_stats(
3610 LHASH *lh,
3611 FILE *out);
3612         This function prints out statistics on the size of the hash table,
3613         how many entries are in it, and the number and result of calls to
3614         the routines in this library.
3615
3616 void lh_node_stats(
3617 LHASH *lh,
3618 FILE *out);
3619         For each 'bucket' in the hash table, the number of entries is
3620         printed.
3621         
3622 void lh_node_usage_stats(
3623 LHASH *lh,
3624 FILE *out);
3625         This function prints out a short summary of the state of the hash
3626         table.  It prints what I call the 'load' and the 'actual load'.
3627         The load is the average number of data items per 'bucket' in the
3628         hash table.  The 'actual load' is the average number of items per
3629         'bucket', but only for buckets which contain entries.  So the
3630         'actual load' is the average number of searches that will need to
3631         find an item in the hash table, while the 'load' is the average number
3632         that will be done to record a miss.
3633
3634 ==== md2.doc ========================================================
3635
3636 The MD2 library.
3637 MD2 is a message digest algorithm that can be used to condense an arbitrary
3638 length message down to a 16 byte hash.  The functions all need to be passed
3639 a MD2_CTX which is used to hold the MD2 context during multiple MD2_Update()
3640 function calls.  The normal method of use for this library is as follows
3641
3642 MD2_Init(...);
3643 MD2_Update(...);
3644 ...
3645 MD2_Update(...);
3646 MD2_Final(...);
3647
3648 This library requires the inclusion of 'md2.h'.
3649
3650 The main negative about MD2 is that it is slow, especially when compared
3651 to MD5.
3652
3653 The functions are as follows:
3654
3655 void MD2_Init(
3656 MD2_CTX *c);
3657         This function needs to be called to initiate a MD2_CTX structure for
3658         use.
3659         
3660 void MD2_Update(
3661 MD2_CTX *c;
3662 unsigned char *data;
3663 unsigned long len);
3664         This updates the message digest context being generated with 'len'
3665         bytes from the 'data' pointer.  The number of bytes can be any
3666         length.
3667
3668 void MD2_Final(
3669 unsigned char *md;
3670 MD2_CTX *c;
3671         This function is called when a message digest of the data digested
3672         with MD2_Update() is wanted.  The message digest is put in the 'md'
3673         array and is MD2_DIGEST_LENGTH (16) bytes long.
3674
3675 unsigned char *MD2(
3676 unsigned long n;
3677 unsigned char *d;
3678 unsigned char *md;
3679         This function performs a MD2_Init(), followed by a MD2_Update()
3680         followed by a MD2_Final() (using a local MD2_CTX).
3681         The resulting digest is put into 'md' if it is not NULL.
3682         Regardless of the value of 'md', the message
3683         digest is returned from the function.  If 'md' was NULL, the message
3684         digest returned is being stored in a static structure.
3685
3686 ==== md5.doc ========================================================
3687
3688 The MD5 library.
3689 MD5 is a message digest algorithm that can be used to condense an arbitrary
3690 length message down to a 16 byte hash.  The functions all need to be passed
3691 a MD5_CTX which is used to hold the MD5 context during multiple MD5_Update()
3692 function calls.  This library also contains random number routines that are
3693 based on MD5
3694
3695 The normal method of use for this library is as follows
3696
3697 MD5_Init(...);
3698 MD5_Update(...);
3699 ...
3700 MD5_Update(...);
3701 MD5_Final(...);
3702
3703 This library requires the inclusion of 'md5.h'.
3704
3705 The functions are as follows:
3706
3707 void MD5_Init(
3708 MD5_CTX *c);
3709         This function needs to be called to initiate a MD5_CTX structure for
3710         use.
3711         
3712 void MD5_Update(
3713 MD5_CTX *c;
3714 unsigned char *data;
3715 unsigned long len);
3716         This updates the message digest context being generated with 'len'
3717         bytes from the 'data' pointer.  The number of bytes can be any
3718         length.
3719
3720 void MD5_Final(
3721 unsigned char *md;
3722 MD5_CTX *c;
3723         This function is called when a message digest of the data digested
3724         with MD5_Update() is wanted.  The message digest is put in the 'md'
3725         array and is MD5_DIGEST_LENGTH (16) bytes long.
3726
3727 unsigned char *MD5(
3728 unsigned char *d;
3729 unsigned long n;
3730 unsigned char *md;
3731         This function performs a MD5_Init(), followed by a MD5_Update()
3732         followed by a MD5_Final() (using a local MD5_CTX).
3733         The resulting digest is put into 'md' if it is not NULL.
3734         Regardless of the value of 'md', the message
3735         digest is returned from the function.  If 'md' was NULL, the message
3736         digest returned is being stored in a static structure.
3737
3738
3739 ==== memory.doc ========================================================
3740
3741 In the interests of debugging SSLeay, there is an option to compile
3742 using some simple memory leak checking.
3743
3744 All malloc(), free() and realloc() calls in SSLeay now go via
3745 Malloc(), Free() and Realloc() (except those in crypto/lhash).
3746
3747 If CRYPTO_MDEBUG is defined, these calls are #defined to
3748 CRYPTO_malloc(), CRYPTO_free() and CRYPTO_realloc().
3749 If it is not defined, they are #defined to malloc(), free() and realloc().
3750
3751 the CRYPTO_malloc() routines by default just call the underlying library
3752 functons.
3753
3754 If CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON) is called, memory leak detection is
3755 turned on.  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF) turns it off.
3756
3757 When turned on, each Malloc() or Realloc() call is recored along with the file
3758 and line number from where the call was made.   (This is done using the
3759 lhash library which always uses normal system malloc(3) routines).
3760
3761 void CRYPTO_mem_leaks(BIO *b);
3762 void CRYPTO_mem_leaks_fp(FILE *fp);
3763 These both print out the list of memory that has not been free()ed.
3764 This will probably be rather hard to read, but if you look for the 'top level'
3765 structure allocation, this will often give an idea as to what is not being
3766 free()ed.  I don't expect people to use this stuff normally.
3767
3768 ==== ca.1 ========================================================
3769
3770 From eay@orb.mincom.oz.au Thu Dec 28 23:56:45 1995
3771 Received: by orb.mincom.oz.au id AA07374
3772   (5.65c/IDA-1.4.4 for eay); Thu, 28 Dec 1995 13:56:45 +1000
3773 Date: Thu, 28 Dec 1995 13:56:45 +1000 (EST)
3774 From: Eric Young <eay@mincom.oz.au>
3775 X-Sender: eay@orb
3776 To: sameer <sameer@c2.org>
3777 Cc: ssleay@mincom.oz.au
3778 Subject: Re: 'ca'
3779 In-Reply-To: <199512230440.UAA23410@infinity.c2.org>
3780 Message-Id: <Pine.SOL.3.91.951228133525.7269A-100000@orb>
3781 Mime-Version: 1.0
3782 Content-Type: TEXT/PLAIN; charset=US-ASCII
3783 Status: RO
3784 X-Status: 
3785
3786 On Fri, 22 Dec 1995, sameer wrote:
3787 >       I could use documentation on 'ca'. Thanks.
3788
3789 Very quickly.
3790 The ca program uses the ssleay.conf file for most of its configuration
3791
3792 ./ca -help
3793
3794  -verbose        - Talk alot while doing things
3795  -config file    - A config file. If you don't want to use the
3796                    default config file
3797  -name arg       - The particular CA definition to use
3798         In the config file, the section to use for parameters.  This lets 
3799         multiple setups to be contained in the one file.  By default, the 
3800         default_ca variable is looked up in the [ ca ] section.  So in the 
3801         shipped ssleay.conf, the CA definition used is CA_default.  It could be 
3802         any other name.
3803  -gencrl days    - Generate a new CRL, days is when the next CRL is due
3804         This will generate a new certificate revocion list.
3805  -days arg       - number of days to certify the certificate for
3806         When certifiying certificates, this is the number of days to use.
3807  -md arg         - md to use, one of md2, md5, sha or sha1
3808  -policy arg     - The CA 'policy' to support
3809         I'll describe this later, but there are 2 policies definied in the 
3810         shipped ssleay.conf
3811  -keyfile arg    - PEM RSA private key file
3812  -key arg        - key to decode the RSA private key if it is encrypted
3813         since we need to keep the CA's RSA key encrypted
3814  -cert           - The CA certificate
3815  -in file        - The input PEM encoded certificate request(s)
3816  -out file       - Where to put the output file(s)
3817  -outdir dir     - Where to put output certificates
3818         The -out options concatinates all the output certificied
3819         certificates to one file, -outdir puts them in a directory,
3820         named by serial number.
3821  -infiles ....   - The last argument, requests to process
3822         The certificate requests to process, -in is the same.
3823
3824 Just about all the above have default values defined in ssleay.conf.
3825
3826 The key variables in ssleay.conf are (for the pariticular '-name' being 
3827 used, in the default, it is CA_default).
3828
3829 dir is where all the CA database stuff is kept.
3830 certs is where all the previously issued certificates are kept.
3831 The database is a simple text database containing the following tab separated 
3832 fields.
3833 status: a value of 'R' - revoked, 'E' -expired or 'V' valid.
3834 issued date:  When the certificate was certified.
3835 revoked date:  When it was revoked, blank if not revoked.
3836 serial number:  The certificate serial number.
3837 certificate:    Where the certificate is located.
3838 CN:     The name of the certificate.
3839
3840 The demo file has quite a few made up values it it.  The last 2 were 
3841 added by the ca program and are acurate.
3842 The CA program does not update the 'certificate' file correctly right now.
3843 The serial field should be unique as should the CN/status combination.
3844 The ca program checks these at startup.  What still needs to be 
3845 wrtten is a program to 'regenerate' the data base file from the issued 
3846 certificate list (and a CRL list).
3847
3848 Back to the CA_default variables.
3849
3850 Most of the variables are commented.
3851
3852 policy is the default policy.
3853
3854 Ok for policies, they define the order and which fields must be present 
3855 in the certificate request and what gets filled in.
3856
3857 So a value of
3858 countryName             = match
3859 means that the country name must match the CA certificate.
3860 organizationalUnitName  = optional
3861 The org.Unit,Name does not have to be present and
3862 commonName              = supplied
3863 commonName must be supplied in the certificate request.
3864
3865 For the 'policy_match' polocy, the order of the attributes in the 
3866 generated certiticate would be
3867 countryName
3868 stateOrProvinceName
3869 organizationName
3870 organizationalUnitName
3871 commonName
3872 emailAddress
3873
3874 Have a play, it sort of makes sense.  If you think about how the persona 
3875 requests operate, it is similar to the 'policy_match' policy and the
3876 'policy_anything' is similar to what versign is doing.
3877
3878 I hope this helps a bit.  Some backend scripts are definitly needed to 
3879 update the database and to make certificate revocion easy.  All 
3880 certificates issued should also be kept forever (or until they expire?)
3881
3882 hope this helps
3883 eric (who has to run off an buy some cheap knee pads for the caving in 4 
3884 days time :-)
3885
3886 --
3887 Eric Young                  | Signature removed since it was generating
3888 AARNet: eay@mincom.oz.au    | more followups than the message contents :-)
3889
3890
3891 ==== ms3-ca.doc ========================================================
3892
3893 Date: Mon, 9 Jun 97 08:00:33 +0200
3894 From: Holger.Reif@PrakInf.TU-Ilmenau.DE (Holger Reif)
3895 Subject: ms3-ca.doc
3896 Organization: TU Ilmenau, Fak. IA, FG Telematik
3897 Content-Length: 14575
3898 Status: RO
3899 X-Status: 
3900
3901 Loading client certs into MSIE 3.01
3902 ===================================
3903
3904 This document conatains all the information necessary to succesfully set up 
3905 some scripts to issue client certs to Microsoft Internet Explorer. It 
3906 includes the required knowledge about the model MSIE uses for client 
3907 certification and includes complete sample scripts ready to play with. The 
3908 scripts were tested against a modified ca program of SSLeay 0.6.6 and should 
3909 work with the regular ca program that comes with version 0.8.0. I haven't 
3910 tested against MSIE 4.0
3911
3912 You can use the information contained in this document in either way you 
3913 want. However if you feel it saved you a lot of time I ask you to be as fair 
3914 as to mention my name: Holger Reif <reif@prakinf.tu-ilmenau.de>.
3915
3916 1.) The model used by MSIE
3917 --------------------------
3918
3919 The Internet Explorer doesn't come with a embedded engine for installing 
3920 client certs like Netscape's Navigator. It rather uses the CryptoAPI (CAPI) 
3921 defined by Microsoft. CAPI comes with WindowsNT 4.0 or is installed together 
3922 with Internet Explorer since 3.01. The advantage of this approach is a higher 
3923 flexibility because the certificates in the (per user) system open 
3924 certificate store may be used by other applications as well. The drawback 
3925 however is that you need to do a bit more work to get a client cert issued.
3926
3927 CAPI defines functions which will handle basic cryptographic work, eg. 
3928 generating keys, encrypting some data, signing text or building a certificate 
3929 request. The procedure is as follows: A CAPI function generates you a key 
3930 pair and saves it into the certificate store. After that one builds a 
3931 Distinguished Name. Together with that key pair another CAPI function forms a 
3932 PKCS#10 request which you somehow need to submit to a CA. Finally the issued 
3933 cert is given to a yet another CAPI function which saves it into the 
3934 certificate store.
3935
3936 The certificate store with the user's keys and certs is in the registry. You 
3937 will find it under HKEY_CURRENT_USER/Software/Microsoft/Cryptography/ (I 
3938 leave it to you as a little exercise to figure out what all the entries mean 
3939 ;-). Note that the keys are protected only with the user's usual Windows 
3940 login password.
3941
3942 2.) The practical usage
3943 -----------------------
3944
3945 Unfortunatly since CAPI is a system API you can't access its functions from 
3946 HTML code directly. For this purpose Microsoft provides a wrapper called 
3947 certenr3.dll. This DLL accesses the CAPI functions and provides an interface 
3948 usable from Visual Basic Script. One needs to install that library on the 
3949 computer which wants to have client cert. The easiest way is to load it as an 
3950 ActiveX control (certenr3.dll is properly authenticode signed by MS ;-). If 
3951 you have ever enrolled e cert request at a CA you will have installed it.
3952
3953 At time of writing certenr3.dll is contained in 
3954 http://www.microsoft.com/workshop/prog/security/csa/certenr3.exe. It comes 
3955 with an README file which explains the available functions. It is labeled 
3956 beta but every CA seems to use it anyway. The license.txt allows you the 
3957 usage for your own purposes (as far as I understood) and a somehow limited 
3958 distribution. 
3959
3960 The two functions of main interest are GenerateKeyPair and AcceptCredentials. 
3961 For complete explanation of all possible parameters see the README file. Here 
3962 are only minimal required parameters and their values.
3963
3964 GenerateKeyPair(sessionID, FASLE, szName, 0, "ClientAuth", TRUE, FALSE, 1)
3965 - sessionID is a (locally to that computer) unique string to correlate the 
3966 generated key pair with a cert installed later.
3967 - szName is the DN of the form "C=DE; S=Thueringen; L=Ilmenau; CN=Holger 
3968 Reif; 1.2.840.113549.1.9.1=reif@prakinf.tu-ilmenau.de". Note that S is the 
3969 abreviation for StateOrProvince. The recognized abreviation include CN, O, C, 
3970 OU, G, I, L, S, T. If the abreviation is unknown (eg. for PKCS#9 email addr) 
3971 you need to use the full object identifier. The starting point for searching 
3972 them could be crypto/objects.h since all OIDs know to SSLeay are listed 
3973 there.
3974 - note: the possible ninth parameter which should give a default name to the 
3975 certificate storage location doesn't seem to work. Changes to the constant 
3976 values in the call above doesn't seem to make sense. You can't generate 
3977 PKCS#10 extensions with that function.
3978
3979 The result of GenerateKeyPair is the base64 encoded PKCS#10 request. However 
3980 it has a little strange format that SSLeay doesn't accept. (BTW I feel the 
3981 decision of rejecting that format as standard conforming.) It looks like 
3982 follows:
3983         1st line with 76 chars
3984         2nd line with 76 chars
3985         ...
3986         (n-2)th line with 76 chars
3987         (n-1)th line contains a multiple of 4 chars less then 76 (possible 
3988 empty)
3989         (n)th line has zero or 4 chars (then with 1 or 2 equal signs - the 
3990                 original text's lenght wasn'T a multiple of 3) 
3991         The line separator has two chars: 0x0d 0x0a
3992
3993 AcceptCredentials(sessionID, credentials, 0, FALSE)
3994 - sessionID needs to be the same as while generating the key pair
3995 - credentials is the base64 encoded PKCS#7 object containing the cert. 
3996
3997 CRL's and CA certs are not required simply just the client cert. (It seems to 
3998 me that both are not even checked somehow.) The only format of the base64 
3999 encoded object I succesfully used was all characters in a very long string 
4000 without line feeds or carriage returns. (Hey, it doesn't matter, only a 
4001 computer reads it!)
4002
4003 The result should be S_OK. For error handling see the example that comes with 
4004 certenr3.dll.
4005
4006 A note about ASN.1 character encodings. certenr3.dll seems to know only about 
4007 2 of them: UniversalString and PrintableString. First it is definitely wrong 
4008 for an email address which is IA5STRING (checked by ssleay's ca). Second 
4009 unfortunately MSIE (at least until version 3.02) can't handle UniversalString 
4010 correctly - they just blow up you cert store! Therefore ssleay's ca (starting 
4011 from version 0.8.0) tries to convert the encodings automatically to IA5STRING 
4012 or TeletexString. The beef is it will work only for the latin-1 (western) 
4013 charset. Microsoft still has to do abit of homework...
4014
4015 3.) An example
4016 --------------
4017
4018 At least you need two steps: generating the key & request and then installing 
4019 the certificate. A real world CA would have some more steps involved, eg. 
4020 accepting some license. Note that both scripts shown below are just 
4021 experimental state without any warrenty!
4022
4023 First how to generate a request. Note that we can't use a static page because 
4024 of the sessionID. I generate it from system time plus pid and hope it is 
4025 unique enough. Your are free to feed it through md5 to get more impressive 
4026 ID's ;-) Then the intended text is read in with sed which inserts the 
4027 sessionID. 
4028
4029 -----BEGIN ms-enroll.cgi-----
4030 #!/bin/sh
4031 SESSION_ID=`date '+%y%m%d%H%M%S'`$$
4032 echo Content-type: text/html
4033 echo
4034 sed s/template_for_sessId/$SESSION_ID/ <<EOF
4035 <HTML><HEAD>
4036 <TITLE>Certificate Enrollment Test Page</TITLE>
4037 </HEAD><BODY>
4038
4039 <OBJECT
4040     classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
4041     codebase=certenr3.dll
4042     id=certHelper
4043     >
4044 </OBJECT>
4045
4046 <CENTER>
4047 <H2>enrollment for a personal cert</H2>
4048 <BR><HR WIDTH=50%><BR><P>
4049 <FORM NAME="MSIE_Enrollment" ACTION="ms-gencert.cgi" ENCTYPE=x-www-form-
4050 encoded METHOD=POST>
4051 <TABLE>
4052     <TR><TD>Country</TD><TD><INPUT NAME="Country" VALUE=""></TD></TR>
4053     <TR><TD>State</TD><TD><INPUT NAME="StateOrProvince" VALUE=""></TD></TR>
4054     <TR><TD>Location</TD><TD><INPUT NAME="Location" VALUE=""></TD></TR>
4055     <TR><TD>Organization</TD><TD><INPUT NAME="Organization" 
4056 VALUE=""></TD></TR>
4057     <TR><TD>Organizational Unit</TD>
4058         <TD><INPUT NAME="OrganizationalUnit" VALUE=""></TD></TR>
4059     <TR><TD>Name</TD><TD><INPUT NAME="CommonName" VALUE=""></TD></TR>
4060     <TR><TD>eMail Address</TD>
4061         <TD><INPUT NAME="EmailAddress" VALUE=""></TD></TR>
4062     <TR><TD></TD>
4063         <TD><INPUT TYPE="BUTTON" NAME="submit" VALUE="Beantragen"></TD></TR>
4064 </TABLE>
4065         <INPUT TYPE="hidden" NAME="SessionId" VALUE="template_for_sessId">
4066         <INPUT TYPE="hidden" NAME="Request" VALUE="">
4067 </FORM>
4068 <BR><HR WIDTH=50%><BR><P>
4069 </CENTER>
4070
4071 <SCRIPT LANGUAGE=VBS>
4072     Dim DN
4073
4074     Sub Submit_OnClick
4075         Dim TheForm
4076         Set TheForm = Document.MSIE_Enrollment
4077         sessionId       = TheForm.SessionId.value
4078         reqHardware     = FALSE
4079         C               = TheForm.Country.value
4080         SP              = TheForm.StateOrProvince.value
4081         L               = TheForm.Location.value
4082         O               = TheForm.Organization.value
4083         OU              = TheForm.OrganizationalUnit.value
4084         CN              = TheForm.CommonName.value
4085         Email           = TheForm.EmailAddress.value
4086         szPurpose       = "ClientAuth"
4087         doAcceptanceUINow   = FALSE
4088         doOnline        = TRUE
4089
4090         DN = ""
4091
4092         Call Add_RDN("C", C)
4093         Call Add_RDN("S", SP)
4094         Call Add_RDN("L", L)
4095         Call Add_RDN("O", O)
4096         Call Add_RDN("OU", OU)
4097         Call Add_RDN("CN", CN)
4098         Call Add_RDN("1.2.840.113549.1.9.1", Email)
4099                       ' rsadsi
4100                                      ' pkcs
4101                                        ' pkcs9
4102                                          ' eMailAddress
4103         On Error Resume Next
4104         sz10 = certHelper.GenerateKeyPair(sessionId, _
4105                 FALSE, DN, 0, ClientAuth, FASLE, TRUE, 1)_
4106         theError = Err.Number
4107         On Error Goto 0
4108         if (sz10 = Empty OR theError <> 0) Then
4109             sz = "The error '" & Hex(theError) & "' occurred." & chr(13) & _
4110                 chr(10) & "Your credentials could not be generated."
4111             result = MsgBox(sz, 0, "Credentials Enrollment")
4112             Exit Sub
4113         else 
4114             TheForm.Request.value = sz10
4115             TheForm.Submit
4116         end if
4117     End Sub
4118
4119     Sub Add_RDN(sn, value)
4120         if (value <> "") then
4121             if (DN <> "") then
4122                 DN = DN & "; "
4123             end if
4124             DN = DN & sn & "=" & value
4125         end if
4126     End Sub
4127 </SCRIPT>
4128 </BODY>
4129 </HTML>
4130 EOF
4131 -----END ms-enroll.cgi-----
4132
4133 Second, how to extract the request and feed the certificate back? We need to 
4134 "normalize" the base64 encoding of the PKCS#10 format which means 
4135 regenerating the lines and wrapping with BEGIN and END line. This is done by 
4136 gawk. The request is taken by ca the normal way. Then the cert needs to be 
4137 packed into a PKCS#7 structure (note: the use of a CRL is necessary for 
4138 crl2pkcs7 as of version 0.6.6. Starting with 0.8.0 it it might probably be 
4139 ommited). Finally we need to format the PKCS#7 object and generate the HTML 
4140 text. I use two templates to have a clearer script.
4141
4142 1st note: postit2 is slightly modified from a program I found at ncsa's ftp 
4143 site. Grab it from http://www.easterngraphics.com/certs/IX9704/postit2.c. You 
4144 need utils.c from there too.
4145
4146 2nd note: I'm note quite sure wether the gawk script really handles all 
4147 possible inputs for the request right! Today I don't use this construction 
4148 anymore myself.
4149
4150 3d note: the cert must be of version 3! This could be done with the nsComment 
4151 line in ssleay.cnf...
4152
4153 ------BEGIN ms-gencert.cgi-----
4154 #!/bin/sh
4155 FILE="/tmp/"`date '+%y%m%d%H%M%S'-`$$
4156 rm -f "$FILE".*
4157
4158 HOME=`pwd`; export HOME  # as ssleay.cnf insists on having such an env var
4159 cd /usr/local/ssl #where demoCA (as named in ssleay.conf) is located
4160
4161 postit2 -s " " -i 0x0d > "$FILE".inp  # process the FORM vars
4162
4163 SESSION_ID=`gawk '$1 == "SessionId" { print $2; exit }' "$FILE".inp`
4164
4165 gawk \
4166         'BEGIN { \
4167                 OFS = ""; \
4168                 print "-----BEGIN CERTIFICATE REQUEST-----"; \
4169                 req_seen=0 \
4170         } \
4171         $1 == "Request" { \
4172                 req_seen=1; \
4173                 if (length($2) == 72) print($2); \
4174                 lastline=$2; \
4175                 next; \
4176         } \
4177         { \
4178                 if (req_seen == 1) { \
4179                         if (length($1) >= 72) print($1); \
4180                         else if (length(lastline) < 72) { \
4181                                 req_seen=0; \
4182                                 print (lastline,$1); \
4183                         } \
4184                 lastline=$1; \
4185                 } \
4186         } \
4187         END { \
4188                 print "-----END CERTIFICATE REQUEST-----"; \
4189         }' > "$FILE".pem < "$FILE".inp 
4190
4191 ssleay ca -batch -in "$FILE".pem -key passwd -out "$FILE".out
4192 ssleay crl2pkcs7 -certfile "$FILE".out -out "$FILE".pkcs7 -in demoCA/crl.pem
4193
4194 sed s/template_for_sessId/$SESSION_ID/ <ms-enroll2a.html >"$FILE".cert
4195 /usr/local/bin/gawk \
4196         'BEGIN  { \
4197                 OFS = ""; \
4198                 dq = sprintf("%c",34); \
4199         } \
4200         $0 ~ "PKCS7" { next; } \
4201         { \
4202                 print dq$0dq" & _"; \
4203         }' <"$FILE".pkcs7 >> "$FILE".cert
4204 cat  ms-enroll2b.html >>"$FILE".cert
4205
4206 echo Content-type: text/html
4207 echo Content-length: `wc -c "$FILE".cert`
4208 echo
4209 cat "$FILE".cert
4210 rm -f "$FILE".*
4211 -----END ms-gencert.cgi-----
4212
4213 ----BEGIN ms-enroll2a.html----
4214 <HTML><HEAD><TITLE>Certificate Acceptance Test Page</TITLE></HEAD><BODY>
4215
4216 <OBJECT
4217     classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
4218     codebase=certenr3.dll
4219     id=certHelper
4220     >
4221 </OBJECT>
4222
4223 <CENTER>
4224 <H2>Your personal certificate</H2>
4225 <BR><HR WIDTH=50%><BR><P>
4226 Press the button!
4227 <P><INPUT TYPE=BUTTON VALUE="Nimm mich!" NAME="InstallCert">
4228 </CENTER>
4229 <BR><HR WIDTH=50%><BR>
4230
4231 <SCRIPT LANGUAGE=VBS>
4232     Sub InstallCert_OnClick
4233
4234         sessionId       = "template_for_sessId"
4235 credentials = "" & _
4236 ----END ms-enroll2a.html----
4237
4238 ----BEGIN ms-enroll2b.html----
4239 ""
4240         On Error Resume Next
4241         result = certHelper.AcceptCredentials(sessionId, credentials, 0, 
4242 FALSE)
4243         if (IsEmpty(result)) Then
4244            sz = "The error '" & Err.Number & "' occurred." & chr(13) & 
4245 chr(10) & "This Digital ID could not be registered."
4246            msgOut = MsgBox(sz, 0, "Credentials Registration Error")
4247            navigate "error.html"
4248         else
4249            sz = "Digital ID successfully registered."
4250            msgOut = MsgBox(sz, 0, "Credentials Registration")
4251            navigate "success.html"
4252         end if
4253         Exit Sub
4254     End Sub
4255 </SCRIPT>
4256 </BODY>
4257 </HTML>
4258 ----END ms-enroll2b.html----
4259
4260 4.) What do do with the cert?
4261 -----------------------------
4262
4263 The cert is visible (without restarting MSIE) under the following menu:
4264 View->Options->Security->Personal certs. You can examine it's contents at 
4265 least partially.
4266
4267 To use it for client authentication you need to use SSL3.0 (fortunately 
4268 SSLeay supports it with 0.8.0). Furthermore MSIE is told to only supports a 
4269 kind of automatic selection of certs (I personally wasn't able to test it 
4270 myself). But there is a requirement that the issuer of the server cert and 
4271 the issuer of the client cert needs to be the same (according to a developer 
4272 from MS). Which means: you need may more then one cert to talk to all 
4273 servers...
4274
4275 I'm sure we will get a bit more experience after ApacheSSL is available for 
4276 SSLeay 0.8.8.
4277
4278
4279 I hope you enjoyed reading and that in future questions on this topic will 
4280 rarely appear on ssl-users@moncom.com ;-)
4281
4282 Ilmenau, 9th of June 1997
4283 Holger Reif <reif@prakinf.tu-ilmenau.de>
4284 -- 
4285 read you later  -  Holger Reif
4286 ----------------------------------------  Signaturprojekt Deutsche Einheit
4287 TU Ilmenau - Informatik - Telematik                      (Verdamp lang her)
4288 Holger.Reif@PrakInf.TU-Ilmenau.DE         Alt wie ein Baum werden, um ueber
4289 http://Remus.PrakInf.TU-Ilmenau.DE/Reif/  alle 7 Bruecken gehen zu koennen
4290
4291
4292 ==== ns-ca.doc ========================================================
4293
4294 The following documentation was supplied by Jeff Barber, who provided the
4295 patch to the CA program to add this functionality.
4296
4297 eric
4298 --
4299 Jeff Barber                                Email: jeffb@issl.atl.hp.com
4300
4301 Hewlett Packard                            Phone: (404) 648-9503
4302 Internet and System Security Lab           Fax:   (404) 648-9516
4303
4304                          oo
4305 ---------------------cut /\ here for ns-ca.doc ------------------------------
4306
4307 This document briefly describes how to use SSLeay to implement a 
4308 certificate authority capable of dynamically serving up client
4309 certificates for version 3.0 beta 5 (and presumably later) versions of
4310 the Netscape Navigator.  Before describing how this is done, it's
4311 important to understand a little about how the browser implements its
4312 client certificate support.  This is documented in some detail in the
4313 URLs based at <URL:http://home.netscape.com/eng/security/certs.html>.
4314 Here's a brief overview:
4315
4316 -       The Navigator supports a new HTML tag "KEYGEN" which will cause
4317         the browser to generate an RSA key pair when you submit a form
4318         containing the tag.  The public key, along with an optional
4319         challenge (supposedly provided for use in certificate revocation
4320         but I don't use it) is signed, DER-encoded, base-64 encoded
4321         and sent to the web server as the value of the variable
4322         whose NAME is provided in the KEYGEN tag.  The private key is
4323         stored by the browser in a local key database.
4324
4325         This "Signed Public Key And Challenge" (SPKAC) arrives formatted
4326         into 64 character lines (which are of course URL-encoded when 
4327         sent via HTTP -- i.e. spaces, newlines and most punctuatation are
4328         encoded as "%HH" where HH is the hex equivalent of the ASCII code).
4329         Note that the SPKAC does not contain the other usual attributes
4330         of a certificate request, especially the subject name fields.
4331         These must be otherwise encoded in the form for submission along
4332         with the SPKAC.
4333
4334 -       Either immediately (in response to this form submission), or at
4335         some later date (a real CA will probably verify your identity in
4336         some way before issuing the certificate), a web server can send a
4337         certificate based on the public key and other attributes back to
4338         the browser by encoding it in DER (the binary form) and sending it
4339         to the browser as MIME type:
4340         "Content-type: application/x-x509-user-cert"
4341
4342         The browser uses the public key encoded in the certificate to
4343         associate the certificate with the appropriate private key in
4344         its local key database.  Now, the certificate is "installed".
4345
4346 -       When a server wants to require authentication based on client
4347         certificates, it uses the right signals via the SSL protocol to
4348         trigger the Navigator to ask you which certificate you want to
4349         send.  Whether the certificate is accepted is dependent on CA
4350         certificates and so forth installed in the server and is beyond
4351         the scope of this document.
4352
4353
4354 Now, here's how the SSLeay package can be used to provide client 
4355 certficates:
4356
4357 -       You prepare a file for input to the SSLeay ca application.
4358         The file contains a number of "name = value" pairs that identify
4359         the subject.  The names here are the same subject name component
4360         identifiers used in the CA section of the lib/ssleay.conf file,
4361         such as "emailAddress", "commonName" "organizationName" and so
4362         forth.  Both the long version and the short version (e.g. "Email",
4363         "CN", "O") can be used.
4364
4365         One more name is supported: this one is "SPKAC".  Its value
4366         is simply the value of the base-64 encoded SPKAC sent by the
4367         browser (with all the newlines and other space charaters
4368         removed -- and newline escapes are NOT supported).
4369
4370         [ As of SSLeay 0.6.4, multiple lines are supported.
4371           Put a \ at the end of each line and it will be joined with the
4372           previous line with the '\n' removed - eay ]
4373         
4374         Here's a sample input file:
4375
4376 C = US
4377 SP = Georgia
4378 O = Some Organization, Inc.
4379 OU = Netscape Compatibility Group
4380 CN = John X. Doe
4381 Email = jxdoe@someorg.com
4382 SPKAC = MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAwmk6FMJ4uAVIYbcvIOx5+bDGTfvL8X5gE+R67ccMk6rCSGbVQz2cetyQtnI+VIs0NwdD6wjuSuVtVFbLoHonowIDAQABFgAwDQYJKoZIhvcNAQEEBQADQQBFZDUWFl6BJdomtN1Bi53mwijy1rRgJ4YirF15yBEDM3DjAQkKXHYOIX+qpz4KXKnl6EYxTnGSFL5wWt8X2iyx
4383
4384 -       You execute the ca command (either from a CGI program run out of
4385         the web server, or as a later manual task) giving it the above
4386         file as input.  For example, if the file were named /tmp/cert.req,
4387         you'd run:
4388         $SSLDIR/bin/ca -spkac /tmp/cert.req -out /tmp/cert
4389
4390         The output is in DER format (binary) if a -out argument is 
4391         provided, as above; otherwise, it's in the PEM format (base-64
4392         encoded DER).  Also, the "-batch" switch is implied by the
4393         "-spkac" so you don't get asked whether to complete the signing
4394         (probably it shouldn't work this way but I was only interested
4395         in hacking together an online CA that could be used for issuing
4396         test certificates).
4397
4398         The "-spkac" capability doesn't support multiple files (I think).
4399
4400         Any CHALLENGE provided in the SPKAC is simply ignored.
4401
4402         The interactions between the identification fields you provide
4403         and those identified in your lib/ssleay.conf are the same as if
4404         you did an ordinary "ca -in infile -out outfile" -- that is, if
4405         something is marked as required in the ssleay.conf file and it
4406         isn't found in the -spkac file, the certificate won't be issued.
4407
4408 -       Now, you pick up the output from /tmp/cert and pass it back to
4409         the Navigator prepending the Content-type string described earlier.
4410
4411 -       In order to run the ca command out of a CGI program, you must
4412         provide a password to decrypt the CA's private key.  You can
4413         do this by using "echo MyKeyPassword | $SSLDIR/bin/ca ..."
4414         I think there's a way to not encrypt the key file in the first
4415         place, but I didn't see how to do that, so I made a small change
4416         to the library that allows the password to be accepted from a pipe.
4417         Either way is UTTERLY INSECURE and a real CA would never do that.
4418
4419         [ You can use the 'ssleay rsa' command to remove the password
4420           from the private key, or you can use the '-key' option to the
4421           ca command to specify the decryption key on the command line
4422           or use the -nodes option when generating the key.
4423           ca will try to clear the command line version of the password
4424           but for quite a few operating systems, this is not possible.
4425           - eric ]
4426
4427 So, what do you have to do to make use of this stuff to create an online 
4428 demo CA capability with SSLeay?
4429
4430 1       Create an HTML form for your users.  The form should contain
4431         fields for all of the required or optional fields in ssleay.conf.
4432         The form must contain a KEYGEN tag somewhere with at least a NAME
4433         attribute.
4434
4435 2       Create a CGI program to process the form input submitted by the
4436         browser.  The CGI program must URL-decode the variables and create
4437         the file described above, containing subject identification info
4438         as well as the SPKAC block.  It should then run the the ca program
4439         with the -spkac option.  If it works (check the exit status),
4440         return the new certificate with the appropriate MIME type.  If not,
4441         return the output of the ca command with MIME type "text/plain".
4442
4443 3       Set up your web server to accept connections signed by your demo
4444         CA.  This probably involves obtaining the PEM-encoded CA certificate
4445         (ordinarily in $SSLDIR/CA/cacert.pem) and installing it into a
4446         server database.  See your server manual for instructions.
4447
4448
4449 ==== obj.doc ========================================================
4450
4451 The Object library.
4452
4453 As part of my Crypto library, I found I required a method of identifying various
4454 objects.  These objects normally had 3 different values associated with
4455 them, a short text name, a long (or lower case) text name, and an
4456 ASN.1 Object Identifier (which is a sequence of numbers).
4457 This library contains a static list of objects and functions to lookup
4458 according to one type and to return the other types.
4459
4460 To use these routines, 'Object.h' needs to be included.
4461
4462 For each supported object, #define entries are defined as follows
4463 #define SN_Algorithm                    "Algorithm"
4464 #define LN_algorithm                    "algorithm"
4465 #define NID_algorithm                   38
4466 #define OBJ_algorithm                   1L,3L,14L,3L,2L
4467
4468 SN_  stands for short name.
4469 LN_  stands for either long name or lowercase name.
4470 NID_ stands for Numeric ID.  I each object has a unique NID and this
4471      should be used internally to identify objects.
4472 OBJ_ stands for ASN.1 Object Identifier or ASN1_OBJECT as defined in the
4473      ASN1 routines.  These values are used in ASN1 encoding.
4474
4475 The following functions are to be used to return pointers into a static
4476 definition of these types.  What this means is "don't try to free() any
4477 pointers returned from these functions.
4478
4479 ASN1_OBJECT *OBJ_nid2obj(
4480 int n);
4481         Return the ASN1_OBJECT that corresponds to a NID of n.
4482         
4483 char *OBJ_nid2ln(
4484 int n);
4485         Return the long/lower case name of the object represented by the
4486         NID of n.
4487         
4488 char *OBJ_nid2sn(
4489 int n);
4490         Return the short name for the object represented by the NID of n.
4491
4492 ASN1_OBJECT *OBJ_dup(
4493 ASN1_OBJECT *o);
4494         Duplicate and return a new ASN1_OBJECT that is the same as the
4495         passed parameter.
4496         
4497 int OBJ_obj2nid(
4498 ASN1_OBJECT *o);
4499         Given ASN1_OBJECT o, return the NID that corresponds.
4500         
4501 int OBJ_ln2nid(
4502 char *s);
4503         Given the long/lower case name 's', return the NID of the object.
4504         
4505 int OBJ_sn2nid(
4506 char *s);
4507         Given the short name 's', return the NID of the object.
4508         
4509 char *OBJ_bsearch(
4510 char *key,
4511 char *base,
4512 int num,
4513 int size,
4514 int (*cmp)());
4515         Since I have come across a few platforms that do not have the
4516         bsearch() function, OBJ_bsearch is my version of that function.
4517         Feel free to use this function, but you may as well just use the
4518         normal system bsearch(3) if it is present.  This version also
4519         has tolerance of being passed NULL pointers.
4520
4521 ==== rand.doc ========================================================
4522
4523 My Random number library.
4524
4525 These routines can be used to generate pseudo random numbers and can be
4526 used to 'seed' the pseudo random number generator (RNG).  The RNG make no
4527 effort to reproduce the same random number stream with each execution.
4528 Various other routines in the SSLeay library 'seed' the RNG when suitable
4529 'random' input data is available.  Read the section at the end for details
4530 on the design of the RNG.
4531
4532 void RAND_bytes(
4533 unsigned char *buf,
4534 int num);
4535         This routine puts 'num' random bytes into 'buf'.  One should make
4536         sure RAND_seed() has been called before using this routine.
4537         
4538 void RAND_seed(
4539 unsigned char *buf,
4540 int num);
4541         This routine adds more 'seed' data the RNG state.  'num' bytes
4542         are added to the RNG state, they are taken from 'buf'.  This
4543         routine can be called with sensitive data such as user entered
4544         passwords.  This sensitive data is in no way recoverable from
4545         the RAND library routines or state.  Try to pass as much data
4546         from 'random' sources as possible into the RNG via this function.
4547         Also strongly consider using the RAND_load_file() and
4548         RAND_write_file() routines.
4549
4550 void RAND_cleanup();
4551         When a program has finished with the RAND library, if it so
4552         desires, it can 'zero' all RNG state.
4553         
4554 The following 3 routines are convenience routines that can be used to
4555 'save' and 'restore' data from/to the RNG and it's state.
4556 Since the more 'random' data that is feed as seed data the better, why not
4557 keep it around between executions of the program?  Of course the
4558 application should pass more 'random' data in via RAND_seed() and 
4559 make sure no-one can read the 'random' data file.
4560         
4561 char *RAND_file_name(
4562 char *buf,
4563 int size);
4564         This routine returns a 'default' name for the location of a 'rand'
4565         file.  The 'rand' file should keep a sequence of random bytes used
4566         to initialise the RNG.  The filename is put in 'buf'.  Buf is 'size'
4567         bytes long.  Buf is returned if things go well, if they do not,
4568         NULL is returned.  The 'rand' file name is generated in the
4569         following way.  First, if there is a 'RANDFILE' environment
4570         variable, it is returned.  Second, if there is a 'HOME' environment
4571         variable, $HOME/.rand is returned.  Third, NULL is returned.  NULL
4572         is also returned if a buf would overflow.
4573
4574 int RAND_load_file(
4575 char *file,
4576 long number);
4577         This function 'adds' the 'file' into the RNG state.  It does this by
4578         doing a RAND_seed() on the value returned from a stat() system call
4579         on the file and if 'number' is non-zero, upto 'number' bytes read
4580         from the file.  The number of bytes passed to RAND_seed() is returned.
4581
4582 int RAND_write_file(
4583 char *file),
4584         RAND_write_file() writes N random bytes to the file 'file', where
4585         N is the size of the internal RND state (currently 1k).
4586         This is a suitable method of saving RNG state for reloading via
4587         RAND_load_file().
4588
4589 What follows is a description of this RNG and a description of the rational
4590 behind it's design.
4591
4592 It should be noted that this RNG is intended to be used to generate
4593 'random' keys for various ciphers including generation of DH and RSA keys.  
4594
4595 It should also be noted that I have just created a system that I am happy with.
4596 It may be overkill but that does not worry me.  I have not spent that much
4597 time on this algorithm so if there are glaring errors, please let me know.
4598 Speed has not been a consideration in the design of these routines.
4599
4600 First up I will state the things I believe I need for a good RNG.
4601 1) A good hashing algorithm to mix things up and to convert the RNG 'state'
4602    to random numbers.
4603 2) An initial source of random 'state'.
4604 3) The state should be very large.  If the RNG is being used to generate
4605    4096 bit RSA keys, 2 2048 bit random strings are required (at a minimum).
4606    If your RNG state only has 128 bits, you are obviously limiting the
4607    search space to 128 bits, not 2048.  I'm probably getting a little
4608    carried away on this last point but it does indicate that it may not be
4609    a bad idea to keep quite a lot of RNG state.  It should be easier to
4610    break a cipher than guess the RNG seed data.
4611 4) Any RNG seed data should influence all subsequent random numbers
4612    generated.  This implies that any random seed data entered will have
4613    an influence on all subsequent random numbers generated.
4614 5) When using data to seed the RNG state, the data used should not be
4615    extractable from the RNG state.  I believe this should be a
4616    requirement because one possible source of 'secret' semi random
4617    data would be a private key or a password.  This data must
4618    not be disclosed by either subsequent random numbers or a
4619    'core' dump left by a program crash.
4620 6) Given the same initial 'state', 2 systems should deviate in their RNG state
4621    (and hence the random numbers generated) over time if at all possible.
4622 7) Given the random number output stream, it should not be possible to determine
4623    the RNG state or the next random number.
4624
4625
4626 The algorithm is as follows.
4627
4628 There is global state made up of a 1023 byte buffer (the 'state'), a
4629 working message digest ('md') and a counter ('count').
4630
4631 Whenever seed data is added, it is inserted into the 'state' as
4632 follows.
4633         The input is chopped up into units of 16 bytes (or less for
4634         the last block).  Each of these blocks is run through the MD5
4635         message digest.  The data passed to the MD5 digest is the
4636         current 'md', the same number of bytes from the 'state'
4637         (the location determined by in incremented looping index) as
4638         the current 'block' and the new key data 'block'.  The result
4639         of this is kept in 'md' and also xored into the 'state' at the
4640         same locations that were used as input into the MD5.
4641         I believe this system addresses points 1 (MD5), 3 (the 'state'),
4642         4 (via the 'md'), 5 (by the use of MD5 and xor).
4643
4644 When bytes are extracted from the RNG, the following process is used.
4645 For each group of 8 bytes (or less), we do the following,
4646         Input into MD5, the top 8 bytes from 'md', the byte that are
4647         to be overwritten by the random bytes and bytes from the
4648         'state' (incrementing looping index).  From this digest output
4649         (which is kept in 'md'), the top (upto) 8 bytes are
4650         returned to the caller and the bottom (upto) 8 bytes are xored
4651         into the 'state'.
4652         Finally, after we have finished 'generation' random bytes for the
4653         called, 'count' (which is incremented) and 'md' are fed into MD5 and
4654         the results are kept in 'md'.
4655         I believe the above addressed points 1 (use of MD5), 6 (by
4656         hashing into the 'state' the 'old' data from the caller that
4657         is about to be overwritten) and 7 (by not using the 8 bytes
4658         given to the caller to update the 'state', but they are used
4659         to update 'md').
4660
4661 So of the points raised, only 2 is not addressed, but sources of
4662 random data will always be a problem.
4663         
4664
4665 ==== rc2.doc ========================================================
4666
4667 The RC2 library.
4668
4669 RC2 is a block cipher that operates on 64bit (8 byte) quantities.  It
4670 uses variable size key, but 128bit (16 byte) key would normally be considered
4671 good.  It can be used in all the modes that DES can be used.  This
4672 library implements the ecb, cbc, cfb64, ofb64 modes.
4673
4674 I have implemented this library from an article posted to sci.crypt on
4675 11-Feb-1996.  I personally don't know how far to trust the RC2 cipher.
4676 While it is capable of having a key of any size, not much reseach has
4677 publically been done on it at this point in time (Apr-1996)
4678 since the cipher has only been public for a few months :-)
4679 It is of a similar speed to DES and IDEA, so unless it is required for
4680 meeting some standard (SSLv2, perhaps S/MIME), it would probably be advisable
4681 to stick to IDEA, or for the paranoid, Tripple DES.
4682
4683 Mind you, having said all that, I should mention that I just read alot and
4684 implement ciphers, I'm a 'babe in the woods' when it comes to evaluating
4685 ciphers :-).
4686
4687 For all calls that have an 'input' and 'output' variables, they can be the
4688 same.
4689
4690 This library requires the inclusion of 'rc2.h'.
4691
4692 All of the encryption functions take what is called an RC2_KEY as an 
4693 argument.  An RC2_KEY is an expanded form of the RC2 key.
4694 For all modes of the RC2 algorithm, the RC2_KEY used for
4695 decryption is the same one that was used for encryption.
4696
4697 The define RC2_ENCRYPT is passed to specify encryption for the functions
4698 that require an encryption/decryption flag. RC2_DECRYPT is passed to
4699 specify decryption.
4700
4701 Please note that any of the encryption modes specified in my DES library
4702 could be used with RC2.  I have only implemented ecb, cbc, cfb64 and
4703 ofb64 for the following reasons.
4704 - ecb is the basic RC2 encryption.
4705 - cbc is the normal 'chaining' form for block ciphers.
4706 - cfb64 can be used to encrypt single characters, therefore input and output
4707   do not need to be a multiple of 8.
4708 - ofb64 is similar to cfb64 but is more like a stream cipher, not as
4709   secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
4710 - If you want triple RC2, thats 384 bits of key and you must be totally
4711   obsessed with security.  Still, if you want it, it is simple enough to
4712   copy the function from the DES library and change the des_encrypt to
4713   RC2_encrypt; an exercise left for the paranoid reader :-).
4714
4715 The functions are as follows:
4716
4717 void RC2_set_key(
4718 RC2_KEY *ks;
4719 int len;
4720 unsigned char *key;
4721 int bits;
4722         RC2_set_key converts an 'len' byte key into a RC2_KEY.
4723         A 'ks' is an expanded form of the 'key' which is used to
4724         perform actual encryption.  It can be regenerated from the RC2 key
4725         so it only needs to be kept when encryption or decryption is about
4726         to occur.  Don't save or pass around RC2_KEY's since they
4727         are CPU architecture dependent, 'key's are not.  RC2 is an
4728         interesting cipher in that it can be used with a variable length
4729         key.  'len' is the length of 'key' to be used as the key.
4730         A 'len' of 16 is recomended.  The 'bits' argument is an
4731         interesting addition which I only found out about in Aug 96.
4732         BSAFE uses this parameter to 'limit' the number of bits used
4733         for the key.  To use the 'key' unmodified, set bits to 1024.
4734         This is what old versions of my RC2 library did (SSLeay 0.6.3).
4735         RSAs BSAFE library sets this parameter to be 128 if 128 bit
4736         keys are being used.  So to be compatable with BSAFE, set it
4737         to 128, if you don't want to reduce RC2's key length, leave it
4738         at 1024.
4739         
4740 void RC2_encrypt(
4741 unsigned long *data,
4742 RC2_KEY *key,
4743 int encrypt);
4744         This is the RC2 encryption function that gets called by just about
4745         every other RC2 routine in the library.  You should not use this
4746         function except to implement 'modes' of RC2.  I say this because the
4747         functions that call this routine do the conversion from 'char *' to
4748         long, and this needs to be done to make sure 'non-aligned' memory
4749         access do not occur.
4750         Data is a pointer to 2 unsigned long's and key is the
4751         RC2_KEY to use.  Encryption or decryption is indicated by 'encrypt'.
4752         which can have the values RC2_ENCRYPT or RC2_DECRYPT.
4753
4754 void RC2_ecb_encrypt(
4755 unsigned char *in,
4756 unsigned char *out,
4757 RC2_KEY *key,
4758 int encrypt);
4759         This is the basic Electronic Code Book form of RC2 (in DES this
4760         mode is called Electronic Code Book so I'm going to use the term
4761         for rc2 as well.
4762         Input is encrypted into output using the key represented by
4763         key.  Depending on the encrypt, encryption or
4764         decryption occurs.  Input is 8 bytes long and output is 8 bytes.
4765         
4766 void RC2_cbc_encrypt(
4767 unsigned char *in,
4768 unsigned char *out,
4769 long length,
4770 RC2_KEY *ks,
4771 unsigned char *ivec,
4772 int encrypt);
4773         This routine implements RC2 in Cipher Block Chaining mode.
4774         Input, which should be a multiple of 8 bytes is encrypted
4775         (or decrypted) to output which will also be a multiple of 8 bytes.
4776         The number of bytes is in length (and from what I've said above,
4777         should be a multiple of 8).  If length is not a multiple of 8, bad 
4778         things will probably happen.  ivec is the initialisation vector.
4779         This function updates iv after each call so that it can be passed to
4780         the next call to RC2_cbc_encrypt().
4781         
4782 void RC2_cfb64_encrypt(
4783 unsigned char *in,
4784 unsigned char *out,
4785 long length,
4786 RC2_KEY *schedule,
4787 unsigned char *ivec,
4788 int *num,
4789 int encrypt);
4790         This is one of the more useful functions in this RC2 library, it
4791         implements CFB mode of RC2 with 64bit feedback.
4792         This allows you to encrypt an arbitrary number of bytes,
4793         you do not require 8 byte padding.  Each call to this
4794         routine will encrypt the input bytes to output and then update ivec
4795         and num.  Num contains 'how far' we are though ivec.
4796         'Encrypt' is used to indicate encryption or decryption.
4797         CFB64 mode operates by using the cipher to generate a stream
4798         of bytes which is used to encrypt the plain text.
4799         The cipher text is then encrypted to generate the next 64 bits to
4800         be xored (incrementally) with the next 64 bits of plain
4801         text.  As can be seen from this, to encrypt or decrypt,
4802         the same 'cipher stream' needs to be generated but the way the next
4803         block of data is gathered for encryption is different for
4804         encryption and decryption.
4805         
4806 void RC2_ofb64_encrypt(
4807 unsigned char *in,
4808 unsigned char *out,
4809 long length,
4810 RC2_KEY *schedule,
4811 unsigned char *ivec,
4812 int *num);
4813         This functions implements OFB mode of RC2 with 64bit feedback.
4814         This allows you to encrypt an arbitrary number of bytes,
4815         you do not require 8 byte padding.  Each call to this
4816         routine will encrypt the input bytes to output and then update ivec
4817         and num.  Num contains 'how far' we are though ivec.
4818         This is in effect a stream cipher, there is no encryption or
4819         decryption mode.
4820         
4821 For reading passwords, I suggest using des_read_pw_string() from my DES library.
4822 To generate a password from a text string, I suggest using MD5 (or MD2) to
4823 produce a 16 byte message digest that can then be passed directly to
4824 RC2_set_key().
4825
4826 =====
4827 For more information about the specific RC2 modes in this library
4828 (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
4829 documentation on my DES library.  What is said about DES is directly
4830 applicable for RC2.
4831
4832
4833 ==== rc4.doc ========================================================
4834
4835 The RC4 library.
4836 RC4 is a stream cipher that operates on a byte stream.  It can be used with
4837 any length key but I would recommend normally using 16 bytes.
4838
4839 This library requires the inclusion of 'rc4.h'.
4840
4841 The RC4 encryption function takes what is called an RC4_KEY as an argument.
4842 The RC4_KEY is generated by the RC4_set_key function from the key bytes.
4843
4844 RC4, being a stream cipher, does not have an encryption or decryption mode.
4845 It produces a stream of bytes that the input stream is xor'ed against and
4846 so decryption is just a case of 'encrypting' again with the same key.
4847
4848 I have only put in one 'mode' for RC4 which is the normal one.  This means
4849 there is no initialisation vector and there is no feedback of the cipher
4850 text into the cipher.  This implies that you should not ever use the
4851 same key twice if you can help it.  If you do, you leave yourself open to
4852 known plain text attacks; if you know the plain text and
4853 corresponding cipher text in one message, all messages that used the same
4854 key can have the cipher text decoded for the corresponding positions in the
4855 cipher stream.
4856
4857 The main positive feature of RC4 is that it is a very fast cipher; about 4
4858 times faster that DES.  This makes it ideally suited to protocols where the
4859 key is randomly chosen, like SSL.
4860
4861 The functions are as follows:
4862
4863 void RC4_set_key(
4864 RC4_KEY *key;
4865 int len;
4866 unsigned char *data);
4867         This function initialises the RC4_KEY structure with the key passed
4868         in 'data', which is 'len' bytes long.  The key data can be any
4869         length but 16 bytes seems to be a good number.
4870
4871 void RC4(
4872 RC4_KEY *key;
4873 unsigned long len;
4874 unsigned char *in;
4875 unsigned char *out);
4876         Do the actual RC4 encryption/decryption.  Using the 'key', 'len'
4877         bytes are transformed from 'in' to 'out'.  As mentioned above,
4878         decryption is the operation as encryption.
4879
4880 ==== ref.doc ========================================================
4881
4882 I have lots more references etc, and will update this list in the future,
4883 30 Aug 1996 - eay
4884
4885
4886 SSL     The SSL Protocol - from Netscapes.
4887
4888 RC4     Newsgroups: sci.crypt
4889         From: sterndark@netcom.com (David Sterndark)
4890         Subject: RC4 Algorithm revealed.
4891         Message-ID: <sternCvKL4B.Hyy@netcom.com>
4892
4893 RC2     Newsgroups: sci.crypt
4894         From: pgut01@cs.auckland.ac.nz (Peter Gutmann)
4895         Subject: Specification for Ron Rivests Cipher No.2
4896         Message-ID: <4fk39f$f70@net.auckland.ac.nz>
4897
4898 MD2     RFC1319 The MD2 Message-Digest Algorithm
4899 MD5     RFC1321 The MD5 Message-Digest Algorithm
4900
4901 X509 Certificates
4902         RFC1421 Privacy Enhancement for Internet Electronic Mail: Part I
4903         RFC1422 Privacy Enhancement for Internet Electronic Mail: Part II
4904         RFC1423 Privacy Enhancement for Internet Electronic Mail: Part III
4905         RFC1424 Privacy Enhancement for Internet Electronic Mail: Part IV
4906
4907 RSA and various standard encoding
4908         PKCS#1 RSA Encryption Standard
4909         PKCS#5 Password-Based Encryption Standard
4910         PKCS#7 Cryptographic Message Syntax Standard
4911         A Layman's Guide to a Subset of ASN.1, BER, and DER
4912         An Overview of the PKCS Standards
4913         Some Examples of the PKCS Standards
4914
4915 IDEA    Chapter 3 The Block Cipher IDEA
4916
4917 RSA, prime number generation and bignum algorithms
4918         Introduction To Algorithms,
4919         Thomas Cormen, Charles Leiserson, Ronald Rivest,
4920         Section 29 Arithmetic Circuits
4921         Section 33 Number-Theoretic Algorithms
4922
4923 Fast Private Key algorithm
4924         Fast Decipherment Algorithm for RSA Public-Key Cryptosystem
4925         J.-J. Quisquater and C. Couvreur, Electronics Letters,
4926         14th October 1982, Vol. 18 No. 21
4927
4928 Prime number generation and bignum algorithms.
4929         PGP-2.3a
4930
4931 ==== rsa.doc ========================================================
4932
4933 The RSA encryption and utility routines.
4934
4935 The RSA routines are built on top of a big number library (the BN library).
4936 There are support routines in the X509 library for loading and manipulating
4937 the various objects in the RSA library.  When errors are returned, read
4938 about the ERR library for how to access the error codes.
4939
4940 All RSA encryption is done according to the PKCS-1 standard which is
4941 compatible with PEM and RSAref.  This means that any values being encrypted
4942 must be less than the size of the modulus in bytes, minus 10, bytes long.
4943
4944 This library uses RAND_bytes()() for it's random data, make sure to feed
4945 RAND_seed() with lots of interesting and varied data before using these
4946 routines.
4947
4948 The RSA library has one specific data type, the RSA structure.
4949 It is composed of 8 BIGNUM variables (see the BN library for details) and
4950 can hold either a private RSA key or a public RSA key.
4951 Some RSA libraries have different structures for public and private keys, I
4952 don't.  For my libraries, a public key is determined by the fact that the
4953 RSA->d value is NULL.  These routines will operate on any size RSA keys.
4954 While I'm sure 4096 bit keys are very very secure, they take a lot longer
4955 to process that 1024 bit keys :-).
4956
4957 The function in the RSA library are as follows.
4958
4959 RSA *RSA_new();
4960         This function creates a new RSA object.  The sub-fields of the RSA
4961         type are also malloced so you should always use this routine to
4962         create RSA variables.
4963         
4964 void RSA_free(
4965 RSA *rsa);
4966         This function 'frees' an RSA structure.  This routine should always
4967         be used to free the RSA structure since it will also 'free' any
4968         sub-fields of the RSA type that need freeing.
4969         
4970 int RSA_size(
4971 RSA *rsa);      
4972         This function returns the size of the RSA modulus in bytes.  Why do
4973         I need this you may ask, well the reason is that when you encrypt
4974         with RSA, the output string will be the size of the RSA modulus.
4975         So the output for the RSA_encrypt and the input for the RSA_decrypt
4976         routines need to be RSA_size() bytes long, because this is how many
4977         bytes are expected.
4978         
4979 For the following 4 RSA encryption routines, it should be noted that
4980 RSA_private_decrypt() should be used on the output from 
4981 RSA_public_encrypt() and RSA_public_decrypt() should be used on
4982 the output from RSA_private_encrypt().
4983         
4984 int RSA_public_encrypt(
4985 int from_len;
4986 unsigned char *from     
4987 unsigned char *to       
4988 RSA *rsa);
4989         This function implements RSA public encryption, the rsa variable
4990         should be a public key (but can be a private key).  'from_len'
4991         bytes taken from 'from' and encrypted and put into 'to'.  'to' needs
4992         to be at least RSA_size(rsa) bytes long.  The number of bytes
4993         written into 'to' is returned.  -1 is returned on an error.  The
4994         operation performed is
4995         to = from^rsa->e mod rsa->n.
4996         
4997 int RSA_private_encrypt(
4998 int from_len;
4999 unsigned char *from     
5000 unsigned char *to       
5001 RSA *rsa);
5002         This function implements RSA private encryption, the rsa variable
5003         should be a private key.  'from_len' bytes taken from
5004         'from' and encrypted and put into 'to'.  'to' needs
5005         to be at least RSA_size(rsa) bytes long.  The number of bytes
5006         written into 'to' is returned.  -1 is returned on an error.  The
5007         operation performed is
5008         to = from^rsa->d mod rsa->n.
5009
5010 int RSA_public_decrypt(
5011 int from_len;
5012 unsigned char *from     
5013 unsigned char *to       
5014 RSA *rsa);
5015         This function implements RSA public decryption, the rsa variable
5016         should be a public key (but can be a private key).  'from_len'
5017         bytes are taken from 'from' and decrypted.  The decrypted data is
5018         put into 'to'.  The number of bytes encrypted is returned.  -1 is
5019         returned to indicate an error. The operation performed is
5020         to = from^rsa->e mod rsa->n.
5021
5022 int RSA_private_decrypt(
5023 int from_len;
5024 unsigned char *from     
5025 unsigned char *to       
5026 RSA *rsa);
5027         This function implements RSA private decryption, the rsa variable
5028         should be a private key.  'from_len' bytes are taken
5029         from 'from' and decrypted.  The decrypted data is
5030         put into 'to'.  The number of bytes encrypted is returned.  -1 is
5031         returned to indicate an error. The operation performed is
5032         to = from^rsa->d mod rsa->n.
5033
5034 int RSA_mod_exp(
5035 BIGNUM *n;
5036 BIGNUM *p;
5037 RSA *rsa);
5038         Normally you will never use this routine.
5039         This is really an internal function which is called by
5040         RSA_private_encrypt() and RSA_private_decrypt().  It performs
5041         n=n^p mod rsa->n except that it uses the 5 extra variables in the
5042         RSA structure to make this more efficient.
5043         
5044 RSA *RSA_generate_key(
5045 int bits;
5046 unsigned long e;
5047 void (*callback)();
5048 char *cb_arg;
5049         This routine is used to generate RSA private keys.  It takes
5050         quite a period of time to run and should only be used to
5051         generate initial private keys that should then be stored
5052         for later use.  The passed callback function 
5053         will be called periodically so that feedback can be given
5054         as to how this function is progressing.
5055         'bits' is the length desired for the modulus, so it would be 1024
5056         to generate a 1024 bit private key.
5057         'e' is the value to use for the public exponent 'e'.  Traditionally
5058         it is set to either 3 or 0x10001.
5059         The callback function (if not NULL) is called in the following
5060         situations.
5061         when we have generated a suspected prime number to test,
5062         callback(0,num1++,cb_arg).  When it passes a prime number test,
5063         callback(1,num2++,cb_arg).  When it is rejected as one of
5064         the 2 primes required due to gcd(prime,e value) != 0,
5065         callback(2,num3++,cb_arg).  When finally accepted as one
5066         of the 2 primes, callback(3,num4++,cb_arg).
5067
5068
5069 ==== rsaref.doc ========================================================
5070
5071 This package can be compiled to use the RSAref library.
5072 This library is not allowed outside of the USA but inside the USA it is
5073 claimed by RSA to be the only RSA public key library that can be used
5074 besides BSAFE..
5075
5076 There are 2 files, rsaref/rsaref.c and rsaref/rsaref.h that contain the glue
5077 code to use RSAref.  These files were written by looking at the PGP
5078 source code and seeing which routines it used to access RSAref.
5079 I have also been sent by some-one a copy of the RSAref header file that
5080 contains the library error codes.
5081
5082 [ Jun 1996 update - I have recently gotten hold of RSAref 2.0 from
5083   South Africa and have been doing some performace tests. ]
5084         
5085 They have now been tested against the recently announced RSAEURO
5086 library.
5087
5088 There are 2 ways to use SSLeay and RSAref.  First, to build so that
5089 the programs must be linked with RSAref, add '-DRSAref' to CFLAG in the top
5090 level makefile and -lrsaref (or where ever you are keeping RSAref) to
5091 EX_LIBS.
5092
5093 To build a makefile via util/mk1mf.pl to do this, use the 'rsaref' option.
5094
5095 The second method is to build as per normal and link applications with
5096 the RSAglue library.  The correct library order would be
5097 cc -o cmd cmd.o -lssl -lRSAglue -lcrypto -lrsaref -ldes
5098 The RSAglue library is built in the rsa directory and is NOT
5099 automatically installed.
5100
5101 Be warned that the RSAEURO library, that is claimed to be compatible
5102 with RSAref contains a different value for the maximum number of bits
5103 supported.  This changes structure sizes and so if you are using
5104 RSAEURO, change the value of RSAref_MAX_BITS in rsa/rsaref.h
5105
5106
5107 ==== s_mult.doc ========================================================
5108
5109 s_mult is a test program I hacked up on a Sunday for testing non-blocking
5110 IO.  It has a select loop at it's centre that handles multiple readers
5111 and writers.
5112
5113 Try the following command
5114 ssleay s_mult -echo -nbio -ssl -v
5115 echo - sends any sent text back to the sender
5116 nbio - turns on non-blocking IO
5117 ssl  - accept SSL connections, default is normal text
5118 v    - print lots
5119         type Q<cr> to quit
5120
5121 In another window, run the following
5122 ssleay s_client -pause </etc/termcap
5123
5124 The pause option puts in a 1 second pause in each read(2)/write(2) call
5125 so the other end will have read()s fail.
5126
5127 ==== session.doc ========================================================
5128
5129 I have just checked over and re-worked the session stuff.
5130 The following brief example will ignore all setup information to do with
5131 authentication.
5132
5133 Things operate as follows.
5134
5135 The SSL environment has a 'context', a SSL_CTX structure.  This holds the
5136 cached SSL_SESSIONS (which can be reused) and the certificate lookup
5137 information.  Each SSL structure needs to be associated with a SSL_CTX.
5138 Normally only one SSL_CTX structure is needed per program.
5139
5140 SSL_CTX *SSL_CTX_new(void ); 
5141 void    SSL_CTX_free(SSL_CTX *);
5142 These 2 functions create and destroy SSL_CTX structures
5143
5144 The SSL_CTX has a session_cache_mode which is by default,
5145 in SSL_SESS_CACHE_SERVER mode.  What this means is that the library
5146 will automatically add new session-id's to the cache apon sucsessful
5147 SSL_accept() calls.
5148 If SSL_SESS_CACHE_CLIENT is set, then client certificates are also added
5149 to the cache.
5150 SSL_set_session_cache_mode(ctx,mode)  will set the 'mode' and
5151 SSL_get_session_cache_mode(ctx) will get the cache 'mode'.
5152 The modes can be
5153 SSL_SESS_CACHE_OFF      - no caching
5154 SSL_SESS_CACHE_CLIENT   - only SSL_connect()
5155 SSL_SESS_CACHE_SERVER   - only SSL_accept()
5156 SSL_SESS_NO_CACHE_BOTH  - Either SSL_accept() or SSL_connect().
5157 If SSL_SESS_CACHE_NO_AUTO_CLEAR is set, old timed out sessions are
5158 not automatically removed each 255, SSL_connect()s or SSL_accept()s.
5159
5160 By default, apon every 255 successful SSL_connect() or SSL_accept()s,
5161 the cache is flush.  Please note that this could be expensive on
5162 a heavily loaded SSL server, in which case, turn this off and
5163 clear the cache of old entries 'manually' (with one of the functions
5164 listed below) every few hours.  Perhaps I should up this number, it is hard
5165 to say.  Remember, the '255' new calls is just a mechanims to get called
5166 every now and then, in theory at most 255 new session-id's will have been
5167 added but if 100 are added every minute, you would still have
5168 500 in the cache before any would start being flushed (assuming a 3 minute
5169 timeout)..
5170
5171 int SSL_CTX_sess_hits(SSL_CTX *ctx);
5172 int SSL_CTX_sess_misses(SSL_CTX *ctx);
5173 int SSL_CTX_sess_timeouts(SSL_CTX *ctx);
5174 These 3 functions return statistics about the SSL_CTX.  These 3 are the
5175 number of session id reuses.  hits is the number of reuses, misses are the
5176 number of lookups that failed, and timeouts is the number of cached
5177 entries ignored because they had timeouted.
5178
5179 ctx->new_session_cb is a function pointer to a function of type
5180 int new_session_callback(SSL *ssl,SSL_SESSION *new);
5181 This function, if set in the SSL_CTX structure is called whenever a new
5182 SSL_SESSION is added to the cache.  If the callback returns non-zero, it
5183 means that the application will have to do a SSL_SESSION_free()
5184 on the structure (this is
5185 to do with the cache keeping the reference counts correct, without the
5186 application needing to know about it.
5187 The 'active' parameter is the current SSL session for which this connection
5188 was created.
5189
5190 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,int (*cb)());
5191 to set the callback,
5192 int (*cb)() SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)
5193 to get the callback.
5194
5195 If the 'get session' callback is set, when a session id is looked up and
5196 it is not in the session-id cache, this callback is called.  The callback is
5197 of the form
5198 SSL_SESSION *get_session_callback(unsigned char *sess_id,int sess_id_len,
5199         int *copy);
5200
5201 The get_session_callback is intended to return null if no session id is found.
5202 The reference count on the SSL_SESSION in incremented by the SSL library,
5203 if copy is 1.  Otherwise, the reference count is not modified.
5204
5205 void SSL_CTX_sess_set_get_cb(ctx,cb) sets the callback and
5206 int (*cb)()SSL_CTX_sess_get_get_cb(ctx) returns the callback.
5207
5208 These callbacks are basically indended to be used by processes to
5209 send their session-id's to other processes.  I currently have not implemented
5210 non-blocking semantics for these callbacks, it is upto the appication
5211 to make the callbacks effiecent if they require blocking (perhaps
5212 by 'saving' them and then 'posting them' when control returns from
5213 the SSL_accept().
5214
5215 LHASH *SSL_CTX_sessions(SSL_CTX *ctx)
5216 This returns the session cache.  The lhash strucutre can be accessed for
5217 statistics about the cache.
5218
5219 void lh_stats(LHASH *lh, FILE *out);
5220 void lh_node_stats(LHASH *lh, FILE *out);
5221 void lh_node_usage_stats(LHASH *lh, FILE *out);
5222
5223 can be used to print details about it's activity and current state.
5224 You can also delve directly into the lhash structure for 14 different
5225 counters that are kept against the structure.  When I wrote the lhash library,
5226 I was interested in gathering statistics :-).
5227 Have a read of doc/lhash.doc in the SSLeay distribution area for more details
5228 on the lhash library.
5229
5230 Now as mentioned ealier, when a SSL is created, it needs a SSL_CTX.
5231 SSL *   SSL_new(SSL_CTX *);
5232
5233 This stores a session.  A session is secret information shared between 2
5234 SSL contexts.  It will only be created if both ends of the connection have
5235 authenticated their peer to their satisfaction.  It basically contains
5236 the information required to use a particular secret key cipher.
5237
5238 To retrieve the SSL_CTX being used by a SSL,
5239 SSL_CTX *SSL_get_SSL_CTX(SSL *s);
5240
5241 Now when a SSL session is established between to programs, the 'session'
5242 information that is cached in the SSL_CTX can me manipulated by the
5243 following functions.
5244 int SSL_set_session(SSL *s, SSL_SESSION *session);
5245 This will set the SSL_SESSION to use for the next SSL_connect().  If you use
5246 this function on an already 'open' established SSL connection, 'bad things
5247 will happen'.  This function is meaning-less when used on a ssl strucutre
5248 that is just about to be used in a SSL_accept() call since the
5249 SSL_accept() will either create a new session or retrieve one from the
5250 cache.
5251
5252 SSL_SESSION *SSL_get_session(SSL *s);
5253 This will return the SSL_SESSION for the current SSL, NULL if there is
5254 no session associated with the SSL structure.
5255
5256 The SSL sessions are kept in the SSL_CTX in a hash table, to remove a
5257 session
5258 void    SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c);
5259 and to add one
5260 int    SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c);
5261 SSL_CTX_add_session() returns 1 if the session was already in the cache (so it
5262 was not added).
5263 Whenever a new session is created via SSL_connect()/SSL_accept(),
5264 they are automatically added to the cache, depending on the session_cache_mode
5265 settings.  SSL_set_session()
5266 does not add it to the cache.  Just call SSL_CTX_add_session() if you do want the
5267 session added.  For a 'client' this would not normally be the case.
5268 SSL_CTX_add_session() is not normally ever used, except for doing 'evil' things
5269 which the next 2 funtions help you do.
5270
5271 int     i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp);
5272 SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a,unsigned char **pp,long length);
5273 These 2 functions are in the standard ASN1 library form and can be used to
5274 load and save to a byte format, the SSL_SESSION structure.
5275 With these functions, you can save and read these structures to a files or
5276 arbitary byte string.
5277 The PEM_write_SSL_SESSION(fp,x) and PEM_read_SSL_SESSION(fp,x,cb) will
5278 write to a file pointer in base64 encoding.
5279
5280 What you can do with this, is pass session information between separate
5281 processes.  Please note, that you will probably also need to modify the
5282 timeout information on the SSL_SESSIONs.
5283
5284 long SSL_get_time(SSL_SESSION *s)
5285 will return the 'time' that the session
5286 was loaded.  The timeout is relative to this time.  This information is
5287 saved when the SSL_SESSION is converted to binarary but it is stored
5288 in as a unix long, which is rather OS dependant, but easy to convert back.
5289
5290 long SSL_set_time(SSL_SESSION *s,long t) will set the above mentioned time.
5291 The time value is just the value returned from time(3), and should really
5292 be defined by be to be time_t.
5293
5294 long SSL_get_timeout(SSL_SESSION *s);
5295 long SSL_set_timeout(SSL_SESSION *s,long t);
5296 These 2 retrieve and set the timeout which is just a number of secconds
5297 from the 'SSL_get_time()' value.  When this time period has elapesed,
5298 the session will no longer be in the cache (well it will actually be removed
5299 the next time it is attempted to be retrieved, so you could 'bump'
5300 the timeout so it remains valid).
5301 The 'time' and 'timeout' are set on a session when it is created, not reset
5302 each time it is reused.  If you did wish to 'bump it', just after establishing
5303 a connection, do a
5304 SSL_set_time(ssl,time(NULL));
5305
5306 You can also use
5307 SSL_CTX_set_timeout(SSL_CTX *ctx,unsigned long t) and
5308 SSL_CTX_get_timeout(SSL_CTX *ctx) to manipulate the default timeouts for
5309 all SSL connections created against a SSL_CTX.  If you set a timeout in
5310 an SSL_CTX, all new SSL's created will inherit the timeout.  It can be over
5311 written by the SSL_set_timeout(SSL *s,unsigned long t) function call.
5312 If you 'set' the timeout back to 0, the system default will be used.
5313
5314 SSL_SESSION *SSL_SESSION_new();
5315 void SSL_SESSION_free(SSL_SESSION *ses);
5316 These 2 functions are used to create and dispose of SSL_SESSION functions.
5317 You should not ever normally need to use them unless you are using 
5318 i2d_SSL_SESSION() and/or d2i_SSL_SESSION().  If you 'load' a SSL_SESSION
5319 via d2i_SSL_SESSION(), you will need to SSL_SESSION_free() it.
5320 Both SSL_set_session() and SSL_CTX_add_session() will 'take copies' of the
5321 structure (via reference counts) when it is passed to them.
5322
5323 SSL_CTX_flush_sessions(ctx,time);
5324 The first function will clear all sessions from the cache, which have expired
5325 relative to 'time' (which could just be time(NULL)).
5326
5327 SSL_CTX_flush_sessions(ctx,0);
5328 This is a special case that clears everything.
5329
5330 As a final comment, a 'session' is not enough to establish a new
5331 connection.  If a session has timed out, a certificate and private key
5332 need to have been associated with the SSL structure.
5333 SSL_copy_session_id(SSL *to,SSL *from); will copy not only the session
5334 strucutre but also the private key and certificate associated with
5335 'from'.
5336
5337 EXAMPLES.
5338
5339 So lets play at being a wierd SSL server.
5340
5341 /* setup a context */
5342 ctx=SSL_CTX_new();
5343
5344 /* Lets load some session from binary into the cache, why one would do
5345  * this is not toally clear, but passing between programs does make sense
5346  * Perhaps you are using 4096 bit keys and are happy to keep them
5347  * valid for a week, to avoid the RSA overhead of 15 seconds, I'm not toally
5348  * sure, perhaps this is a process called from an SSL inetd and this is being 
5349  * passed to the application. */
5350 session=d2i_SSL_SESSION(....)
5351 SSL_CTX_add_session(ctx,session);
5352
5353 /* Lets even add a session from a file */
5354 session=PEM_read_SSL_SESSION(....)
5355 SSL_CTX_add_session(ctx,session);
5356
5357 /* create a new SSL structure */
5358 ssl=SSL_new(ctx);
5359
5360 /* At this point we want to be able to 'create' new session if
5361  * required, so we need a certificate and RSAkey. */
5362 SSL_use_RSAPrivateKey_file(ssl,...)
5363 SSL_use_certificate_file(ssl,...)
5364
5365 /* Now since we are a server, it make little sence to load a session against
5366  * the ssl strucutre since a SSL_accept() will either create a new session or
5367  * grab an existing one from the cache. */
5368
5369 /* grab a socket descriptor */
5370 fd=accept(...);
5371
5372 /* associated it with the ssl strucutre */
5373 SSL_set_fd(ssl,fd);
5374
5375 SSL_accept(ssl); /* 'do' SSL using out cert and RSA key */
5376
5377 /* Lets print out the session details or lets save it to a file,
5378  * perhaps with a secret key cipher, so that we can pass it to the FBI
5379  * when they want to decode the session :-).  While we have RSA
5380  * this does not matter much but when I do SSLv3, this will allow a mechanism
5381  * for the server/client to record the information needed to decode
5382  * the traffic that went over the wire, even when using Diffie-Hellman */
5383 PEM_write_SSL_SESSION(SSL_get_session(ssl),stdout,....)
5384
5385 Lets 'connect' back to the caller using the same session id.
5386
5387 ssl2=SSL_new(ctx);
5388 fd2=connect(them);
5389 SSL_set_fd(ssl2,fd2);
5390 SSL_set_session(ssl2,SSL_get_session(ssl));
5391 SSL_connect(ssl2);
5392
5393 /* what the hell, lets accept no more connections using this session */
5394 SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl),SSL_get_session(ssl));
5395
5396 /* we could have just as easily used ssl2 since they both are using the
5397  * same session.
5398  * You will note that both ssl and ssl2 are still using the session, and
5399  * the SSL_SESSION structure will be free()ed when both ssl and ssl2
5400  * finish using the session.  Also note that you could continue to initiate
5401  * connections using this session by doing SSL_get_session(ssl) to get the
5402  * existing session, but SSL_accept() will not be able to find it to
5403  * use for incoming connections.
5404  * Of corse, the session will timeout at the far end and it will no
5405  * longer be accepted after a while.  The time and timeout are ignored except
5406  * by SSL_accept(). */
5407
5408 /* Since we have had our server running for 10 weeks, and memory is getting
5409  * short, perhaps we should clear the session cache to remove those
5410  * 100000 session entries that have expired.  Some may consider this
5411  * a memory leak :-) */
5412
5413 SSL_CTX_flush_sessions(ctx,time(NULL));
5414
5415 /* Ok, after a bit more time we wish to flush all sessions from the cache
5416  * so that all new connections will be authenticated and incure the
5417  * public key operation overhead */
5418
5419 SSL_CTX_flush_sessions(ctx,0);
5420
5421 /* As a final note, to copy everything to do with a SSL, use */
5422 SSL_copy_session_id(SSL *to,SSL *from);
5423 /* as this also copies the certificate and RSA key so new session can
5424  * be established using the same details */
5425
5426
5427 ==== sha.doc ========================================================
5428
5429 The SHA (Secure Hash Algorithm) library.
5430 SHA is a message digest algorithm that can be used to condense an arbitrary
5431 length message down to a 20 byte hash.  The functions all need to be passed
5432 a SHA_CTX which is used to hold the SHA context during multiple SHA_Update()
5433 function calls.  The normal method of use for this library is as follows
5434 This library contains both SHA and SHA-1 digest algorithms.  SHA-1 is
5435 an update to SHA (which should really be called SHA-0 now) which
5436 tweaks the algorithm slightly.  The SHA-1 algorithm is used by simply
5437 using SHA1_Init(), SHA1_Update(), SHA1_Final() and SHA1() instead of the
5438 SHA*() calls
5439
5440 SHA_Init(...);
5441 SHA_Update(...);
5442 ...
5443 SHA_Update(...);
5444 SHA_Final(...);
5445
5446 This library requires the inclusion of 'sha.h'.
5447
5448 The functions are as follows:
5449
5450 void SHA_Init(
5451 SHA_CTX *c);
5452         This function needs to be called to initiate a SHA_CTX structure for
5453         use.
5454         
5455 void SHA_Update(
5456 SHA_CTX *c;
5457 unsigned char *data;
5458 unsigned long len);
5459         This updates the message digest context being generated with 'len'
5460         bytes from the 'data' pointer.  The number of bytes can be any
5461         length.
5462
5463 void SHA_Final(
5464 unsigned char *md;
5465 SHA_CTX *c;
5466         This function is called when a message digest of the data digested
5467         with SHA_Update() is wanted.  The message digest is put in the 'md'
5468         array and is SHA_DIGEST_LENGTH (20) bytes long.
5469
5470 unsigned char *SHA(
5471 unsigned char *d;
5472 unsigned long n;
5473 unsigned char *md;
5474         This function performs a SHA_Init(), followed by a SHA_Update()
5475         followed by a SHA_Final() (using a local SHA_CTX).
5476         The resulting digest is put into 'md' if it is not NULL.
5477         Regardless of the value of 'md', the message
5478         digest is returned from the function.  If 'md' was NULL, the message
5479         digest returned is being stored in a static structure.
5480         
5481
5482 ==== speed.doc ========================================================
5483
5484 To get an idea of the performance of this library, use
5485 ssleay speed
5486
5487 perl util/sp-diff.pl file1 file2
5488
5489 will print out the relative differences between the 2 files which are
5490 expected to be the output from the speed program.
5491
5492 The performace of the library is very dependant on the Compiler
5493 quality and various flags used to build.
5494
5495 ---
5496
5497 These are some numbers I did comparing RSAref and SSLeay on a Pentium 100.
5498 [ These numbers are all out of date, as of SSL - 0.6.1 the RSA
5499 operations are about 2 times faster, so check the version number ]
5500
5501 RSA performance.
5502
5503 SSLeay 0.6.0
5504 Pentium 100, 32meg, Windows NT Workstation 3.51
5505 linux - gcc v 2.7.0 -O3 -fomit-frame-pointer -m486
5506 and
5507 Windows NT  - Windows NT 3.51 - Visual C++ 4.1   - 586 code + 32bit assember
5508 Windows 3.1 - Windows NT 3.51 - Visual C++ 1.52c - 286 code + 32bit assember
5509 NT Dos Shell- Windows NT 3.51 - Visual C++ 1.52c - 286 code + 16bit assember
5510
5511 Times are how long it takes to do an RSA private key operation.
5512
5513                512bits 1024bits
5514 -------------------------------
5515 SSLeay NT dll   0.042s   0.202s see above
5516 SSLeay linux    0.046s   0.218s Assember inner loops (normal build) 
5517 SSLeay linux    0.067s   0.380s Pure C code with BN_LLONG defined
5518 SSLeay W3.1 dll 0.108s   0.478s see above
5519 SSLeay linux    0.109s   0.713s C without BN_LLONG.
5520 RSAref2.0 linux 0.149s   0.936s
5521 SSLeay MS-DOS   0.197s   1.049s see above
5522
5523 486DX66, 32meg, Windows NT Server 3.51
5524                512bits 1024bits
5525 -------------------------------
5526 SSLeay NT dll   0.084s   0.495s <- SSLeay 0.6.3
5527 SSLeay NT dll   0.154s   0.882s
5528 SSLeay W3.1 dll 0.335s   1.538s
5529 SSLeay MS-DOS   0.490s   2.790s
5530
5531 What I find cute is that I'm still faster than RSAref when using standard C,
5532 without using the 'long long' data type :-), %35 faster for 512bit and we
5533 scale up to 3.2 times faster for the 'default linux' build.  I should mention
5534 that people should 'try' to use either x86-lnx.s (elf), x86-lnxa.s or
5535 x86-sol.s for any x86 based unix they are building on.  The only problems
5536 with be with syntax but the performance gain is quite large, especially for
5537 servers.  The code is very simple, you just need to modify the 'header'.
5538
5539 The message is, if you are stuck using RSAref, the RSA performance will be
5540 bad. Considering the code was compiled for a pentium, the 486DX66 number
5541 would indicate 'Use RSAref and turn you Pentium 100 into a 486DX66' :-). 
5542 [ As of verson 0.6.1, it would be correct to say 'turn you pentium 100
5543  into a 486DX33' :-) ]
5544
5545 I won't tell people if the DLL's are using RSAref or my stuff if no-one
5546 asks :-).
5547
5548 eric
5549
5550 PS while I know I could speed things up further, I will probably not do
5551    so due to the effort involved.  I did do some timings on the
5552    SSLeay bignum format -> RSAref number format conversion that occurs
5553    each time RSAref is used by SSLeay, and the numbers are trivial.
5554    0.00012s a call for 512bit vs 0.149s for the time spent in the function.
5555    0.00018s for 1024bit vs 0.938s.  Insignificant.
5556    So the 'way to go', to support faster RSA libraries, if people are keen,
5557    is to write 'glue' code in a similar way that I do for RSAref and send it
5558    to me :-).
5559    My base library still has the advantage of being able to operate on 
5560    any size numbers, and is not that far from the performance from the
5561    leaders in the field. (-%30?)
5562    [ Well as of 0.6.1 I am now the leader in the filed on x86 (we at
5563      least very close :-) ]
5564
5565    I suppose I should also mention some other numbers RSAref numbers, again
5566    on my Pentium.
5567                 DES CBC         EDE-DES         MD5
5568    RSAref linux  830k/s          302k/s         4390k/s
5569    SSLeay linux  855k/s          319k/s        10025k/s
5570    SSLeay NT    1158k/s          410k/s        10470k/s
5571    SSLeay w31    378k/s          143k/s         2383k/s (fully 16bit)
5572
5573    Got to admit that Visual C++ 4.[01] is a damn fine compiler :-)
5574 --
5575 Eric Young                  | BOOL is tri-state according to Bill Gates.
5576 AARNet: eay@cryptsoft.com   | RTFM Win32 GetMessage().
5577
5578
5579
5580
5581 ==== ssl-ciph.doc ========================================================
5582
5583 This is a quick high level summery of how things work now.
5584
5585 Each SSLv2 and SSLv3 cipher is composed of 4 major attributes plus a few extra
5586 minor ones.
5587
5588 They are 'The key exchange algorithm', which is RSA for SSLv2 but can also
5589 be Diffle-Hellman for SSLv3.
5590
5591 An 'Authenticion algorithm', which can be RSA, Diffle-Helman, DSS or
5592 none.
5593
5594 The cipher
5595
5596 The MAC digest.
5597
5598 A cipher can also be an export cipher and is either an SSLv2 or a
5599 SSLv3 ciphers.
5600
5601 To specify which ciphers to use, one can either specify all the ciphers,
5602 one at a time, or use 'aliases' to specify the preference and order for
5603 the ciphers.
5604
5605 There are a large number of aliases, but the most importaint are
5606 kRSA, kDHr, kDHd and kEDH for key exchange types.
5607
5608 aRSA, aDSS, aNULL and aDH for authentication
5609 DES, 3DES, RC4, RC2, IDEA and eNULL for ciphers
5610 MD5, SHA0 and SHA1 digests
5611
5612 Now where this becomes interesting is that these can be put together to
5613 specify the order and ciphers you wish to use.
5614
5615 To speed this up there are also aliases for certian groups of ciphers.
5616 The main ones are
5617 SSLv2   - all SSLv2 ciphers
5618 SSLv3   - all SSLv3 ciphers
5619 EXP     - all export ciphers
5620 LOW     - all low strngth ciphers (no export ciphers, normally single DES)
5621 MEDIUM  - 128 bit encryption
5622 HIGH    - Triple DES
5623
5624 These aliases can be joined in a : separated list which specifies to
5625 add ciphers, move them to the current location and delete them.
5626
5627 A simpler way to look at all of this is to use the 'ssleay ciphers -v' command.
5628 The default library cipher spec is
5629 !ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP
5630 which means, first, remove from consideration any ciphers that do not
5631 authenticate.  Next up, use ciphers using RC4 and RSA.  Next include the HIGH,
5632 MEDIUM and the LOW security ciphers.  Finish up by adding all the export
5633 ciphers on the end, then 'pull' all the SSLv2 and export ciphers to
5634 the end of the list.
5635
5636 The results are
5637 $ ssleay ciphers -v '!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP'
5638
5639 RC4-SHA                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=SHA1
5640 RC4-MD5                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5 
5641 EDH-RSA-DES-CBC3-SHA    SSLv3 Kx=DH       Au=RSA  Enc=3DES(168) Mac=SHA1
5642 EDH-DSS-DES-CBC3-SHA    SSLv3 Kx=DH       Au=DSS  Enc=3DES(168) Mac=SHA1
5643 DES-CBC3-SHA            SSLv3 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=SHA1
5644 IDEA-CBC-MD5            SSLv3 Kx=RSA      Au=RSA  Enc=IDEA(128) Mac=SHA1
5645 EDH-RSA-DES-CBC-SHA     SSLv3 Kx=DH       Au=RSA  Enc=DES(56)   Mac=SHA1
5646 EDH-DSS-DES-CBC-SHA     SSLv3 Kx=DH       Au=DSS  Enc=DES(56)   Mac=SHA1
5647 DES-CBC-SHA             SSLv3 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=SHA1
5648 DES-CBC3-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=MD5 
5649 DES-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=MD5 
5650 IDEA-CBC-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=IDEA(128) Mac=MD5 
5651 RC2-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=RC2(128)  Mac=MD5 
5652 RC4-MD5                 SSLv2 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5 
5653 EXP-EDH-RSA-DES-CBC     SSLv3 Kx=DH(512)  Au=RSA  Enc=DES(40)   Mac=SHA1 export
5654 EXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=DSS  Enc=DES(40)   Mac=SHA1 export
5655 EXP-DES-CBC-SHA         SSLv3 Kx=RSA(512) Au=RSA  Enc=DES(40)   Mac=SHA1 export
5656 EXP-RC2-CBC-MD5         SSLv3 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
5657 EXP-RC4-MD5             SSLv3 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
5658 EXP-RC2-CBC-MD5         SSLv2 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
5659 EXP-RC4-MD5             SSLv2 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
5660
5661 I would recoment people use the 'ssleay ciphers -v "text"'
5662 command to check what they are going to use.
5663
5664 Anyway, I'm falling asleep here so I'll do some more tomorrow.
5665
5666 eric
5667
5668 ==== ssl.doc ========================================================
5669
5670 SSL_CTX_sessions(SSL_CTX *ctx) - the session-id hash table.
5671
5672 /* Session-id cache stats */
5673 SSL_CTX_sess_number
5674 SSL_CTX_sess_connect
5675 SSL_CTX_sess_connect_good
5676 SSL_CTX_sess_accept
5677 SSL_CTX_sess_accept_good
5678 SSL_CTX_sess_hits
5679 SSL_CTX_sess_cb_hits
5680 SSL_CTX_sess_misses
5681 SSL_CTX_sess_timeouts
5682
5683 /* Session-id application notification callbacks */
5684 SSL_CTX_sess_set_new_cb
5685 SSL_CTX_sess_get_new_cb
5686 SSL_CTX_sess_set_get_cb
5687 SSL_CTX_sess_get_get_cb
5688
5689 /* Session-id cache operation mode */
5690 SSL_CTX_set_session_cache_mode
5691 SSL_CTX_get_session_cache_mode
5692
5693 /* Set default timeout values to use. */
5694 SSL_CTX_set_timeout
5695 SSL_CTX_get_timeout
5696
5697 /* Global  SSL initalisation informational callback */
5698 SSL_CTX_set_info_callback
5699 SSL_CTX_get_info_callback
5700 SSL_set_info_callback
5701 SSL_get_info_callback
5702
5703 /* If the SSL_accept/SSL_connect returned with -1, these indicate when
5704  * we should re-call *.
5705 SSL_want
5706 SSL_want_nothing
5707 SSL_want_read
5708 SSL_want_write
5709 SSL_want_x509_lookup
5710
5711 /* Where we are in SSL initalisation, used in non-blocking, perhaps
5712  * have a look at ssl/bio_ssl.c */
5713 SSL_state
5714 SSL_is_init_finished
5715 SSL_in_init
5716 SSL_in_connect_init
5717 SSL_in_accept_init
5718
5719 /* Used to set the 'inital' state so SSL_in_connect_init and SSL_in_accept_init
5720  * can be used to work out which function to call. */
5721 SSL_set_connect_state
5722 SSL_set_accept_state
5723
5724 /* Where to look for certificates for authentication */
5725 SSL_set_default_verify_paths /* calles SSL_load_verify_locations */
5726 SSL_load_verify_locations
5727
5728 /* get info from an established connection */
5729 SSL_get_session
5730 SSL_get_certificate
5731 SSL_get_SSL_CTX
5732
5733 SSL_CTX_new
5734 SSL_CTX_free
5735 SSL_new
5736 SSL_clear
5737 SSL_free
5738
5739 SSL_CTX_set_cipher_list
5740 SSL_get_cipher
5741 SSL_set_cipher_list
5742 SSL_get_cipher_list
5743 SSL_get_shared_ciphers
5744
5745 SSL_accept
5746 SSL_connect
5747 SSL_read
5748 SSL_write
5749
5750 SSL_debug
5751
5752 SSL_get_read_ahead
5753 SSL_set_read_ahead
5754 SSL_set_verify
5755
5756 SSL_pending
5757
5758 SSL_set_fd
5759 SSL_set_rfd
5760 SSL_set_wfd
5761 SSL_set_bio
5762 SSL_get_fd
5763 SSL_get_rbio
5764 SSL_get_wbio
5765
5766 SSL_use_RSAPrivateKey
5767 SSL_use_RSAPrivateKey_ASN1
5768 SSL_use_RSAPrivateKey_file
5769 SSL_use_PrivateKey
5770 SSL_use_PrivateKey_ASN1
5771 SSL_use_PrivateKey_file
5772 SSL_use_certificate
5773 SSL_use_certificate_ASN1
5774 SSL_use_certificate_file
5775
5776 ERR_load_SSL_strings
5777 SSL_load_error_strings
5778
5779 /* human readable version of the 'state' of the SSL connection. */
5780 SSL_state_string
5781 SSL_state_string_long
5782 /* These 2 report what kind of IO operation the library was trying to
5783  * perform last.  Probably not very usefull. */
5784 SSL_rstate_string
5785 SSL_rstate_string_long
5786
5787 SSL_get_peer_certificate
5788
5789 SSL_SESSION_new
5790 SSL_SESSION_print_fp
5791 SSL_SESSION_print
5792 SSL_SESSION_free
5793 i2d_SSL_SESSION
5794 d2i_SSL_SESSION
5795
5796 SSL_get_time
5797 SSL_set_time
5798 SSL_get_timeout
5799 SSL_set_timeout
5800 SSL_copy_session_id
5801 SSL_set_session
5802 SSL_CTX_add_session
5803 SSL_CTX_remove_session
5804 SSL_CTX_flush_sessions
5805
5806 BIO_f_ssl
5807
5808 /* used to hold information as to why a certificate verification failed */
5809 SSL_set_verify_result
5810 SSL_get_verify_result
5811
5812 /* can be used by the application to associate data with an SSL structure.
5813  * It needs to be 'free()ed' by the application */
5814 SSL_set_app_data
5815 SSL_get_app_data
5816
5817 /* The following all set values that are kept in the SSL_CTX but
5818  * are used as the default values when an SSL session is created.
5819  * They are over writen by the relevent SSL_xxxx functions */
5820
5821 /* SSL_set_verify */
5822 void SSL_CTX_set_default_verify
5823
5824 /* This callback, if set, totaly overrides the normal SSLeay verification
5825  * functions and should return 1 on sucesss and 0 on failure */
5826 void SSL_CTX_set_cert_verify_callback
5827
5828 /* The following are the same as the equivilent SSL_xxx functions.
5829  * Only one copy of this information is kept and if a particular
5830  * SSL structure has a local override, it is totally separate structure.
5831  */
5832 int SSL_CTX_use_RSAPrivateKey
5833 int SSL_CTX_use_RSAPrivateKey_ASN1
5834 int SSL_CTX_use_RSAPrivateKey_file
5835 int SSL_CTX_use_PrivateKey
5836 int SSL_CTX_use_PrivateKey_ASN1
5837 int SSL_CTX_use_PrivateKey_file
5838 int SSL_CTX_use_certificate
5839 int SSL_CTX_use_certificate_ASN1
5840 int SSL_CTX_use_certificate_file
5841
5842
5843 ==== ssl_ctx.doc ========================================================
5844
5845 This is now a bit dated, quite a few of the SSL_ functions could be
5846 SSL_CTX_ functions.  I will update this in the future. 30 Aug 1996
5847
5848 From eay@orb.mincom.oz.au Mon Dec 11 21:37:08 1995
5849 Received: by orb.mincom.oz.au id AA00696
5850   (5.65c/IDA-1.4.4 for eay); Mon, 11 Dec 1995 11:37:08 +1000
5851 Date: Mon, 11 Dec 1995 11:37:08 +1000 (EST)
5852 From: Eric Young <eay@mincom.oz.au>
5853 X-Sender: eay@orb
5854 To: sameer <sameer@c2.org>
5855 Cc: Eric Young <eay@mincom.oz.au>
5856 Subject: Re: PEM_readX509 oesn't seem to be working
5857 In-Reply-To: <199512110102.RAA12521@infinity.c2.org>
5858 Message-Id: <Pine.SOL.3.91.951211112115.28608D-100000@orb>
5859 Mime-Version: 1.0
5860 Content-Type: TEXT/PLAIN; charset=US-ASCII
5861 Status: RO
5862 X-Status: 
5863
5864 On Sun, 10 Dec 1995, sameer wrote:
5865 >       OK, that's solved. I've found out that it is saying "no
5866 > certificate set" in SSL_accept because s->conn == NULL
5867 > so there is some place I need to initialize s->conn that I am
5868 > not initializing it.
5869
5870 The full order of things for a server should be.
5871
5872 ctx=SSL_CTX_new();
5873
5874 /* The next line should not really be using ctx->cert but I'll leave it 
5875  * this way right now... I don't want a X509_ routine to know about an SSL
5876  * structure, there should be an SSL_load_verify_locations... hmm, I may 
5877  * add it tonight.
5878  */
5879 X509_load_verify_locations(ctx->cert,CAfile,CApath);
5880
5881 /* Ok now for each new connection we do the following */
5882 con=SSL_new(ctx);
5883 SSL_set_fd(con,s);
5884 SSL_set_verify(con,verify,verify_callback);
5885
5886 /* set the certificate and private key to use. */
5887 SSL_use_certificate_ASN1(con,X509_certificate);
5888 SSL_use_RSAPrivateKey_ASN1(con,RSA_private_key);
5889
5890 SSL_accept(con);
5891
5892 SSL_read(con)/SSL_write(con);
5893
5894 There is a bit more than that but that is basically the structure.
5895
5896 Create a context and specify where to lookup certificates.
5897
5898 foreach connection
5899         {
5900         create a SSL structure
5901         set the certificate and private key
5902         do a SSL_accept
5903         
5904         we should now be ok
5905         }
5906
5907 eric
5908 --
5909 Eric Young                  | Signature removed since it was generating
5910 AARNet: eay@mincom.oz.au    | more followups than the message contents :-)
5911
5912
5913
5914 ==== ssleay.doc ========================================================
5915
5916 SSLeay: a cryptographic kitchen sink.
5917
5918 1st December 1995
5919 Way back at the start of April 1995, I was looking for a mindless
5920 programming project.  A friend of mine (Tim Hudson) said "why don't you do SSL,
5921 it has DES encryption in it and I would not mind using it in a SSL telnet".
5922 While it was true I had written a DES library in previous years, litle
5923 did I know what an expansive task SSL would turn into.
5924
5925 First of all, the SSL protocol contains DES encryption.  Well and good.  My
5926 DES library was fast and portable.  It also contained the RSA's RC4 stream
5927 cipher.  Again, not a problem, some-one had just posted to sci.crypt
5928 something that was claimed to be RC4.  It also contained IDEA, I had the
5929 specifications, not a problem to implement.  MD5, an RFC, trivial, at most
5930 I could spend a week or so trying to see if I could speed up the
5931 implementation.  All in all a nice set of ciphers.
5932 Then the first 'expantion of the scope', RSA public key
5933 encryption.  Since I did not knowing a thing about public key encryption
5934 or number theory, this appeared quite a daunting task.  Just writing a
5935 big number library would be problomatic in itself, let alone making it fast.
5936 At this point the scope of 'implementing SSL' expands eponentialy.
5937 First of all, the RSA private keys  were being kept in ASN.1 format.
5938 Thankfully the RSA PKCS series of documents explains this format.  So I now
5939 needed to be able to encode and decode arbitary ASN.1 objects.  The Public
5940 keys were embeded in X509 certificates.  Hmm... these are not only
5941 ASN.1 objects but they make up a heirachy of authentication.  To
5942 authenticate a X509 certificate one needs to retrieve it's issuers
5943 certificate etc etc.  Hmm..., so I also need to implement some kind
5944 of certificate management software.  I would also have to implement
5945 software to authenticate certificates.  At this point the support code made
5946 the SSL part of my library look quite small.
5947 Around this time, the first version of SSLeay was released.
5948
5949 Ah, but here was the problem, I was not happy with the code so far.  As may
5950 have become obvious, I had been treating all of this as a learning
5951 exersize, so I have completely written the library myself.  As such, due
5952 to the way it had grown like a fungus, much of the library was not
5953 'elagent' or neat.  There were global and static variables all over the
5954 place, the SSL part did not even handle non-blocking IO.
5955 The Great rewrite began.
5956
5957 As of this point in time, the 'Great rewrite' has almost finished.  So what
5958 follows is an approximate list of what is actually SSLeay 0.5.0
5959
5960 /********* This needs to be updated for 0.6.0+ *************/
5961
5962 ---
5963 The library contains the following routines.  Please note that most of these
5964 functions are not specfic for SSL or any other particular cipher
5965 implementation.  I have tried to make all the routines as general purpose
5966 as possible.  So you should not think of this library as an SSL
5967 implemtation, but rather as a library of cryptographic functions
5968 that also contains SSL.  I refer to each of these function groupings as
5969 libraries since they are often capable of functioning as independant
5970 libraries
5971
5972 First up, the general ciphers and message digests supported by the library.
5973
5974 MD2     rfc???, a standard 'by parts' interface to this algorithm.
5975 MD5     rfc???, the same type of interface as for the MD2 library except a
5976         different algorithm.
5977 SHA     THe Secure Hash Algorithm.  Again the same type of interface as
5978         MD2/MD5 except the digest is 20 bytes.
5979 SHA1    The 'revised' version of SHA.  Just about identical to SHA except
5980         for one tweak of an inner loop.
5981 DES     This is my libdes library that has been floating around for the last
5982         few years.  It has been enhanced for no other reason than completeness.
5983         It now supports ecb, cbc, cfb, ofb, cfb64, ofb64 in normal mode and
5984         triple DES modes of ecb, cbc, cfb64 and ofb64.  cfb64 and ofb64 are
5985         functional interfaces to the 64 bit modes of cfb and ofb used in
5986         such a way thay they function as single character interfaces.
5987 RC4     The RSA Inc. stream cipher.
5988 RC2     The RSA Inc. block cipher.
5989 IDEA    An implmentation of the IDEA cipher, the library supports ecb, cbc,
5990         cfb64 and ofb64 modes of operation.
5991
5992 Now all the above mentioned ciphers and digests libraries support high
5993 speed, minimal 'crap in the way' type interfaces.  For fastest and
5994 lowest level access, these routines should be used directly.
5995
5996 Now there was also the matter of public key crypto systems.  These are
5997 based on large integer arithmatic.
5998
5999 BN      This is my large integer library.  It supports all the normal
6000         arithmentic operations.  It uses malloc extensivly and as such has
6001         no limits of the size of the numbers being manipulated.  If you
6002         wish to use 4000 bit RSA moduli, these routines will handle it.
6003         This library also contains routines to 'generate' prime numbers and
6004         to test for primality.  The RSA and DH libraries sit on top of this
6005         library.  As of this point in time, I don't support SHA, but
6006         when I do add it, it will just sit on top of the routines contained
6007         in this library.
6008 RSA     This implements the RSA public key algorithm.  It also contains
6009         routines that will generate a new private/public key pair.
6010         All the RSA functions conform to the PKCS#1 standard.
6011 DH      This is an implementation of the
6012         Diffie-Hellman protocol.  There are all the require routines for
6013         the protocol, plus extra routines that can be used to generate a
6014         strong prime for use with a specified generator.  While this last
6015         routine is not generally required by applications implementing DH,
6016         It is present for completeness and because I thing it is much
6017         better to be able to 'generate' your own 'magic' numbers as oposed
6018         to using numbers suplied by others.  I conform to the PKCS#3
6019         standard where required.
6020
6021 You may have noticed the preceeding section mentions the 'generation' of
6022 prime numbers.  Now this requries the use of 'random numbers'. 
6023
6024 RAND    This psuedo-random number library is based on MD5 at it's core
6025         and a large internal state (2k bytes).  Once you have entered enough
6026         seed data into this random number algorithm I don't feel
6027         you will ever need to worry about it generating predictable output.
6028         Due to the way I am writing a portable library, I have left the
6029         issue of how to get good initial random seed data upto the
6030         application but I do have support routines for saving and loading a
6031         persistant random number state for use between program runs.
6032         
6033 Now to make all these ciphers easier to use, a higher level
6034 interface was required.  In this form, the same function would be used to
6035 encrypt 'by parts', via any one of the above mentioned ciphers.
6036
6037 EVP     The Digital EnVeloPe library is quite large.  At it's core are
6038         function to perform encryption and decryption by parts while using
6039         an initial parameter to specify which of the 17 different ciphers
6040         or 4 different message digests to use.  On top of these are implmented
6041         the digital signature functions, sign, verify, seal and open.
6042         Base64 encoding of binary data is also done in this library.
6043
6044 PEM     rfc???? describe the format for Privacy Enhanced eMail.
6045         As part of this standard, methods of encoding digital enveloped
6046         data is an ascii format are defined.  As such, I use a form of these
6047         to encode enveloped data.  While at this point in time full support
6048         for PEM has not been built into the library, a minimal subset of
6049         the secret key and Base64 encoding is present.  These reoutines are
6050         mostly used to Ascii encode binary data with a 'type' associated
6051         with it and perhaps details of private key encryption used to
6052         encrypt the data.
6053         
6054 PKCS7   This is another Digital Envelope encoding standard which uses ASN.1
6055         to encode the data.  At this point in time, while there are some
6056         routines to encode and decode this binary format, full support is
6057         not present.
6058         
6059 As Mentioned, above, there are several different ways to encode
6060 data structures.
6061
6062 ASN1    This library is more a set of primatives used to encode the packing
6063         and unpacking of data structures.  It is used by the X509
6064         certificate standard and by the PKCS standards which are used by
6065         this library.  It also contains routines for duplicating and signing
6066         the structures asocisated with X509.
6067         
6068 X509    The X509 library contains routines for packing and unpacking,
6069         verifying and just about every thing else you would want to do with
6070         X509 certificates.
6071
6072 PKCS7   PKCS-7 is a standard for encoding digital envelope data
6073         structures.  At this point in time the routines will load and save
6074         DER forms of these structees.  They need to be re-worked to support
6075         the BER form which is the normal way PKCS-7 is encoded.  If the
6076         previous 2 sentances don't make much sense, don't worry, this
6077         library is not used by this version of SSLeay anyway.
6078
6079 OBJ     ASN.1 uses 'object identifiers' to identify objects.  A set of
6080         functions were requred to translate from ASN.1 to an intenger, to a
6081         character string.  This library provieds these translations
6082         
6083 Now I mentioned an X509 library.  X509 specified a hieachy of certificates
6084 which needs to be traversed to authenticate particular certificates.
6085
6086 METH    This library is used to push 'methods' of retrieving certificates
6087         into the library.  There are some supplied 'methods' with SSLeay
6088         but applications can add new methods if they so desire.
6089         This library has not been finished and is not being used in this
6090         version.
6091         
6092 Now all the above are required for use in the initial point of this project.
6093
6094 SSL     The SSL protocol.  This is a full implmentation of SSL v 2.  It
6095         support both server and client authentication.  SSL v 3 support
6096         will be added when the SSL v 3 specification is released in it's
6097         final form.
6098
6099 Now quite a few of the above mentioned libraries rely on a few 'complex'
6100 data structures.  For each of these I have a library.
6101
6102 Lhash   This is a hash table library which is used extensivly.
6103
6104 STACK   An implemetation of a Stack data structure.
6105
6106 BUF     A simple character array structure that also support a function to
6107         check that the array is greater that a certain size, if it is not,
6108         it is realloced so that is it.
6109         
6110 TXT_DB  A simple memory based text file data base.  The application can specify
6111         unique indexes that will be enforced at update time.
6112
6113 CONF    Most of the programs written for this library require a configuration
6114         file.  Instead of letting programs constantly re-implment this
6115         subsystem, the CONF library provides a consistant and flexable
6116         interface to not only configuration files but also environment
6117         variables.
6118
6119 But what about when something goes wrong?
6120 The one advantage (and perhaps disadvantage) of all of these
6121 functions being in one library was the ability to implement a
6122 single error reporting system.
6123         
6124 ERR     This library is used to report errors.  The error system records
6125         library number, function number (in the library) and reason
6126         number.  Multiple errors can be reported so that an 'error' trace
6127         is created.  The errors can be printed in numeric or textual form.
6128
6129
6130 ==== ssluse.doc ========================================================
6131
6132 We have an SSL_CTX which contains global information for lots of
6133 SSL connections.  The session-id cache and the certificate verificate cache.
6134 It also contains default values for use when certificates are used.
6135
6136 SSL_CTX
6137         default cipher list
6138         session-id cache
6139         certificate cache
6140         default session-id timeout period
6141         New session-id callback
6142         Required session-id callback
6143         session-id stats
6144         Informational callback
6145         Callback that is set, overrides the SSLeay X509 certificate
6146           verification
6147         The default Certificate/Private Key pair
6148         Default read ahead mode.
6149         Default verify mode and verify callback.  These are not used
6150           if the over ride callback mentioned above is used.
6151         
6152 Each SSL can have the following defined for it before a connection is made.
6153
6154 Certificate
6155 Private key
6156 Ciphers to use
6157 Certificate verify mode and callback
6158 IO object to use in the comunication.
6159 Some 'read-ahead' mode information.
6160 A previous session-id to re-use.
6161
6162 A connection is made by using SSL_connect or SSL_accept.
6163 When non-blocking IO is being used, there are functions that can be used
6164 to determin where and why the SSL_connect or SSL_accept did not complete.
6165 This information can be used to recall the functions when the 'error'
6166 condition has dissapeared.
6167
6168 After the connection has been made, information can be retrived about the
6169 SSL session and the session-id values that have been decided apon.
6170 The 'peer' certificate can be retrieved.
6171
6172 The session-id values include
6173 'start time'
6174 'timeout length'
6175
6176
6177
6178 ==== stack.doc ========================================================
6179
6180 The stack data structure is used to store an ordered list of objects.
6181 It is basically misnamed to call it a stack but it can function that way
6182 and that is what I originally used it for.  Due to the way element
6183 pointers are kept in a malloc()ed array, the most efficient way to use this
6184 structure is to add and delete elements from the end via sk_pop() and
6185 sk_push().  If you wish to do 'lookups' sk_find() is quite efficient since
6186 it will sort the stack (if required) and then do a binary search to lookup 
6187 the requested item.  This sorting occurs automatically so just sk_push()
6188 elements on the stack and don't worry about the order.  Do remember that if
6189 you do a sk_find(), the order of the elements will change.
6190
6191 You should never need to 'touch' this structure directly.
6192 typedef struct stack_st
6193         {
6194         unsigned int num;
6195         char **data;
6196         int sorted;
6197
6198         unsigned int num_alloc;
6199         int (*comp)();
6200         } STACK;
6201
6202 'num' holds the number of elements in the stack, 'data' is the array of
6203 elements.  'sorted' is 1 is the list has been sorted, 0 if not.
6204
6205 num_alloc is the number of 'nodes' allocated in 'data'.  When num becomes
6206 larger than num_alloc, data is realloced to a larger size.
6207 If 'comp' is set, it is a function that is used to compare 2 of the items
6208 in the stack.  The function should return -1, 0 or 1, depending on the
6209 ordering.
6210
6211 #define sk_num(sk)      ((sk)->num)
6212 #define sk_value(sk,n)  ((sk)->data[n])
6213
6214 These 2 macros should be used to access the number of elements in the
6215 'stack' and to access a pointer to one of the values.
6216
6217 STACK *sk_new(int (*c)());
6218         This creates a new stack.  If 'c', the comparison function, is not
6219 specified, the various functions that operate on a sorted 'stack' will not
6220 work (sk_find()).  NULL is returned on failure.
6221
6222 void sk_free(STACK *);
6223         This function free()'s a stack structure.  The elements in the
6224 stack will not be freed so one should 'pop' and free all elements from the
6225 stack before calling this function or call sk_pop_free() instead.
6226
6227 void sk_pop_free(STACK *st; void (*func)());
6228         This function calls 'func' for each element on the stack, passing
6229 the element as the argument.  sk_free() is then called to free the 'stack'
6230 structure.
6231
6232 int sk_insert(STACK *sk,char *data,int where);
6233         This function inserts 'data' into stack 'sk' at location 'where'.
6234 If 'where' is larger that the number of elements in the stack, the element
6235 is put at the end.  This function tends to be used by other 'stack'
6236 functions.  Returns 0 on failure, otherwise the number of elements in the
6237 new stack.
6238
6239 char *sk_delete(STACK *st,int loc);
6240         Remove the item a location 'loc' from the stack and returns it.
6241 Returns NULL if the 'loc' is out of range.
6242
6243 char *sk_delete_ptr(STACK *st, char *p);
6244         If the data item pointed to by 'p' is in the stack, it is deleted
6245 from the stack and returned.  NULL is returned if the element is not in the
6246 stack.
6247
6248 int sk_find(STACK *st,char *data);
6249         Returns the location that contains a value that is equal to 
6250 the 'data' item.  If the comparison function was not set, this function
6251 does a linear search.  This function actually qsort()s the stack if it is not
6252 in order and then uses bsearch() to do the initial search.  If the
6253 search fails,, -1 is returned.  For mutliple items with the same
6254 value, the index of the first in the array is returned.
6255
6256 int sk_push(STACK *st,char *data);
6257         Append 'data' to the stack.  0 is returned if there is a failure
6258 (due to a malloc failure), else 1.  This is 
6259 sk_insert(st,data,sk_num(st));
6260
6261 int sk_unshift(STACK *st,char *data);
6262         Prepend 'data' to the front (location 0) of the stack.  This is
6263 sk_insert(st,data,0);
6264
6265 char *sk_shift(STACK *st);
6266         Return and delete from the stack the first element in the stack.
6267 This is sk_delete(st,0);
6268
6269 char *sk_pop(STACK *st);
6270         Return and delete the last element on the stack.  This is
6271 sk_delete(st,sk_num(sk)-1);
6272
6273 void sk_zero(STACK *st);
6274         Removes all items from the stack.  It does not 'free'
6275 pointers but is a quick way to clear a 'stack of references'.
6276
6277 ==== threads.doc ========================================================
6278
6279 How to compile SSLeay for multi-threading.
6280
6281 Well basically it is quite simple, set the compiler flags and build.
6282 I have only really done much testing under Solaris and Windows NT.
6283 If you library supports localtime_r() and gmtime_r() add,
6284 -DTHREADS to the makefile parameters.  You can probably survive with out
6285 this define unless you are going to have multiple threads generating
6286 certificates at once.  It will not affect the SSL side of things.
6287
6288 The approach I have taken to doing locking is to make the application provide
6289 callbacks to perform locking and so that the SSLeay library can distinguish
6290 between threads (for the error state).
6291
6292 To have a look at an example program, 'cd mt; vi mttest.c'.
6293 To build under solaris, sh solaris.sh, for Windows NT or Windows 95,
6294 win32.bat
6295
6296 This will build mttest which will fire up 10 threads that talk SSL
6297 to each other 10 times.
6298 To enable everything to work, the application needs to call
6299
6300 CRYPTO_set_id_callback(id_function);
6301 CRYPTO_set_locking_callback(locking_function);
6302
6303 before any multithreading is started.
6304 id_function does not need to be defined under Windows NT or 95, the
6305 correct function will be called if it is not.  Under unix, getpid()
6306 is call if the id_callback is not defined, for solaris this is wrong
6307 (since threads id's are not pid's) but under IRIX it is correct
6308 (threads are just processes sharing the data segement).
6309
6310 The locking_callback is used to perform locking by the SSLeay library.
6311 eg.
6312
6313 void solaris_locking_callback(mode,type,file,line)
6314 int mode;
6315 int type;
6316 char *file;
6317 int line;
6318         {
6319         if (mode & CRYPTO_LOCK)
6320                 mutex_lock(&(lock_cs[type]));
6321         else
6322                 mutex_unlock(&(lock_cs[type]));
6323         }
6324
6325 Now in this case I have used mutexes instead of read/write locks, since they
6326 are faster and there are not many read locks in SSLeay, you may as well
6327 always use write locks.  file and line are __FILE__ and __LINE__ from
6328 the compile and can be usefull when debugging.
6329
6330 Now as you can see, 'type' can be one of a range of values, these values are
6331 defined in crypto/crypto.h
6332 CRYPTO_get_lock_name(type) will return a text version of what the lock is.
6333 There are CRYPTO_NUM_LOCKS locks required, so under solaris, the setup
6334 for multi-threading can be
6335
6336 static mutex_t lock_cs[CRYPTO_NUM_LOCKS];
6337
6338 void thread_setup()
6339         {
6340         int i;
6341
6342         for (i=0; i<CRYPTO_NUM_LOCKS; i++)
6343                 mutex_init(&(lock_cs[i]),USYNC_THREAD,NULL);
6344         CRYPTO_set_id_callback((unsigned long (*)())solaris_thread_id);
6345         CRYPTO_set_locking_callback((void (*)())solaris_locking_callback);
6346         }
6347
6348 As a final note, under Windows NT or Windows 95, you have to be careful
6349 not to mix the various threaded, unthreaded and debug libraries.
6350 Normally if they are mixed incorrectly, mttest will crash just after printing
6351 out some usage statistics at the end.  This is because the
6352 different system libraries use different malloc routines and if
6353 data is malloc()ed inside crypt32.dll or ssl32.dll and then free()ed by a
6354 different library malloc, things get very confused.
6355
6356 The default SSLeay DLL builds use /MD, so if you use this on your
6357 application, things will work as expected.  If you use /MDd,
6358 you will probably have to rebuild SSLeay using this flag.
6359 I should modify util/mk1mf.pl so it does all this correctly, but 
6360 this has not been done yet.
6361
6362 One last warning.  Because locking overheads are actually quite large, the
6363 statistics collected against the SSL_CTX for successfull connections etc
6364 are not locked when updated.  This does make it possible for these
6365 values to be slightly lower than they should be, if you are
6366 running multithreaded on a multi-processor box, but this does not really
6367 matter much.
6368
6369
6370 ==== txt_db.doc ========================================================
6371
6372 TXT_DB, a simple text based in memory database.
6373
6374 It holds rows of ascii data, for which the only special character is '\0'.
6375 The rows can be of an unlimited length.
6376
6377 ==== why.doc ========================================================
6378
6379 This file is more of a note for other people who wish to understand why
6380 the build environment is the way it is :-).
6381
6382 The include files 'depend' as follows.
6383 Each of 
6384 crypto/*/*.c includes crypto/cryptlib.h
6385 ssl/*.c include ssl/ssl_locl.h
6386 apps/*.c include apps/apps.h
6387 crypto/cryptlib.h, ssl/ssl_locl.h and apps/apps.h
6388 all include e_os.h which contains OS/environment specific information.
6389 If you need to add something todo with a particular environment,
6390 add it to this file.  It is worth remembering that quite a few libraries,
6391 like lhash, des, md, sha etc etc do not include crypto/cryptlib.h.  This
6392 is because these libraries should be 'independantly compilable' and so I
6393 try to keep them this way.
6394 e_os.h is not so much a part of SSLeay, as the placing in one spot all the
6395 evil OS dependant muck.
6396
6397 I wanted to automate as many things as possible.  This includes
6398 error number generation.  A
6399 make errors
6400 will scan the source files for error codes, append them to the correct
6401 header files, and generate the functions to print the text version
6402 of the error numbers.  So don't even think about adding error numbers by
6403 hand, put them in the form
6404 XXXerr(XXXX_F_XXXX,YYYY_R_YYYY);
6405 on line and it will be automatically picked up my a make errors.
6406
6407 In a similar vein, programs to be added into ssleay in the apps directory
6408 just need to have an entry added to E_EXE in makefile.ssl and
6409 everthing will work as expected.  Don't edit progs.h by hand.
6410
6411 make links re-generates the symbolic links that are used.  The reason why
6412 I keep everything in its own directory, and don't put all the
6413 test programs and header files in 'test' and 'include' is because I want
6414 to keep the 'sub-libraries' independant.  I still 'pull' out
6415 indervidual libraries for use in specific projects where the code is
6416 required.  I have used the 'lhash' library in just about every software
6417 project I have worked on :-).
6418
6419 make depend generates dependancies and
6420 make dclean removes them.
6421
6422 You will notice that I use perl quite a bit when I could be using 'sed'.
6423 The reason I decided to do this was to just stick to one 'extra' program.
6424 For Windows NT, I have perl and no sed.
6425
6426 The util/mk1mf.pl program can be used to generate a single makefile.
6427 I use this because makefiles under Microsoft are horrific.
6428 Each C compiler seems to have different linker formats, which have
6429 to be used because the retarted C compilers explode when you do
6430 cl -o file *.o.
6431
6432 Now some would argue that I should just use the single makefile.  I don't
6433 like it during develoment for 2 reasons.  First, the actuall make
6434 command takes a long time.  For my current setup, if I'm in
6435 crypto/bn and I type make, only the crypto/bn directory gets rebuilt,
6436 which is nice when you are modifying prototypes in bn.h which
6437 half the SSLeay depends on.  The second is that to add a new souce file
6438 I just plonk it in at the required spot in the local makefile.  This
6439 then alows me to keep things local, I don't need to modify a 'global'
6440 tables (the make for unix, the make for NT, the make for w31...).
6441 When I am ripping apart a library structure, it is nice to only
6442 have to worry about one directory :-).
6443
6444 Having said all this, for the hell of it I put together 2 files that
6445 #include all the souce code (generated by doing a ls */*.o after a build).
6446 crypto.c takes only 30 seconds to build under NT and 2 minutes under linux
6447 for my pentium100.  Much faster that the normal build :-).
6448 Again, the problem is that when using libraries, every program linked
6449 to libcrypto.a would suddenly get 330k of library when it may only need
6450 1k.  This technique does look like a nice way to do shared libraries though.
6451
6452 Oh yes, as a final note, to 'build' a distribution, I just type
6453 make dist.
6454 This cleans and packages everything.  The directory needs to be called
6455 SSLeay since the make does a 'cd ..' and renames and tars things up.
6456
6457 ==== req.1 ========================================================
6458
6459 The 'req' command is used to manipulate and deal with pkcs#10
6460 certificate requests.
6461
6462 It's default mode of operation is to load a certificate and then
6463 write it out again.
6464
6465 By default the 'req' is read from stdin in 'PEM' format.
6466 The -inform option can be used to specify 'pem' format or 'der'
6467 format.  PEM format is the base64 encoding of the DER format.
6468
6469 By default 'req' then writes the request back out. -outform can be used
6470 to indicate the desired output format, be it 'pem' or 'der'.
6471
6472 To specify an input file, use the '-in' option and the '-out' option
6473 can be used to specify the output file.
6474
6475 If you wish to perform a command and not output the certificate
6476 request afterwards, use the '-noout' option.
6477
6478 When a certificate is loaded, it can be printed in a human readable
6479 ascii format via the '-text' option.
6480
6481 To check that the signature on a certificate request is correct, use
6482 the '-verify' option to make sure that the private key contained in the
6483 certificate request corresponds to the signature.
6484
6485 Besides the default mode, there is also the 'generate a certificate
6486 request' mode.  There are several flags that trigger this mode.
6487
6488 -new will generate a new RSA key (if required) and then prompts
6489 the user for details for the certificate request.
6490 -newkey has an argument that is the number of bits to make the new
6491 key.  This function also triggers '-new'.
6492
6493 The '-new' option can have a key to use specified instead of having to
6494 load one, '-key' is used to specify the file containg the key.
6495 -keyform can be used to specify the format of the key.  Only
6496 'pem' and 'der' formats are supported, later, 'netscape' format may be added.
6497
6498 Finally there is the '-x509' options which makes req output a self
6499 signed x509 certificate instead of a certificate request.
6500
6501 Now as you may have noticed, there are lots of default options that
6502 cannot be specified via the command line.  They are held in a 'template'
6503 or 'configuration file'.  The -config option specifies which configuration
6504 file to use.  See conf.doc for details on the syntax of this file.
6505
6506 The req command uses the 'req' section of the config file.
6507
6508 ---
6509 # The following variables are defined.  For this example I will populate
6510 # the various values
6511 [ req ]
6512 default_bits    = 512           # default number of bits to use.
6513 default_keyfile = testkey.pem   # Where to write the generated keyfile
6514                                 # if not specified.
6515 distinguished_name= req_dn      # The section that contains the
6516                                 # information about which 'object' we
6517                                 # want to put in the DN.
6518 attributes      = req_attr      # The objects we want for the
6519                                 # attributes field.
6520 encrypt_rsa_key = no            # Should we encrypt newly generated
6521                                 # keys.  I strongly recommend 'yes'.
6522
6523 # The distinguished name section.  For the following entries, the
6524 # object names must exist in the SSLeay header file objects.h.  If they
6525 # do not, they will be silently ignored.  The entries have the following
6526 # format.
6527 # <object_name>         => string to prompt with
6528 # <object_name>_default => default value for people
6529 # <object_name>_value   => Automatically use this value for this field.
6530 # <object_name>_min     => minimum number of characters for data (def. 0)
6531 # <object_name>_max     => maximum number of characters for data (def. inf.)
6532 # All of these entries are optional except for the first one.
6533 [ req_dn ]
6534 countryName                     = Country Name (2 letter code)
6535 countryName_default             = AU
6536
6537 stateOrProvinceName             = State or Province Name (full name)
6538 stateOrProvinceName_default     = Queensland
6539
6540 localityName                    = Locality Name (eg, city)
6541
6542 organizationName                = Organization Name (eg, company)
6543 organizationName_default        = Mincom Pty Ltd
6544
6545 organizationalUnitName          = Organizational Unit Name (eg, section)
6546 organizationalUnitName_default  = MTR
6547
6548 commonName                      = Common Name (eg, YOUR name)
6549 commonName_max                  = 64
6550
6551 emailAddress                    = Email Address
6552 emailAddress_max                = 40
6553
6554 # The next section is the attributes section.  This is exactly the
6555 # same as for the previous section except that the resulting objects are
6556 # put in the attributes field. 
6557 [ req_attr ]
6558 challengePassword               = A challenge password
6559 challengePassword_min           = 4
6560 challengePassword_max           = 20
6561
6562 unstructuredName                = An optional company name
6563
6564 ----
6565 Also note that the order that attributes appear in this file is the
6566 order they will be put into the distinguished name.
6567
6568 Once this request has been generated, it can be sent to a CA for
6569 certifying.
6570
6571 ----
6572 A few quick examples....
6573
6574 To generate a new request and a new key
6575 req -new
6576
6577 To generate a new request and a 1058 bit key
6578 req -newkey 1058
6579
6580 To generate a new request using a pre-existing key
6581 req -new -key key.pem
6582
6583 To generate a self signed x509 certificate from a certificate
6584 request using a supplied key, and we want to see the text form of the
6585 output certificate (which we will put in the file selfSign.pem
6586 req -x509 -in req.pem -key key.pem -text -out selfSign.pem
6587
6588 Verify that the signature is correct on a certificate request.
6589 req -verify -in req.pem
6590
6591 Verify that the signature was made using a specified public key.
6592 req -verify -in req.pem -key key.pem
6593
6594 Print the contents of a certificate request
6595 req -text -in req.pem
6596
6597 ==== danger ========================================================
6598
6599 If you specify a SSLv2 cipher, and the mode is SSLv23 and the server
6600 can talk SSLv3, it will claim there is no cipher since you should be
6601 using SSLv3.
6602
6603 When tracing debug stuff, remember BIO_s_socket() is different to
6604 BIO_s_connect().
6605
6606 BSD/OS assember is not working
6607