155714Skris
255714SkrisBundle of old SSLeay documentation files [OBSOLETE!]
355714Skris
489837Skris*** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! ***
589837Skris
689837SkrisOBSOLETE means that nothing in this document should be trusted.  This
789837Skrisdocument is provided mostly for historical purposes (it wasn't even up
889837Skristo date at the time SSLeay 0.8.1 was released) and as inspiration.  If
989837Skrisyou copy some snippet of code from this document, please _check_ that
1089837Skrisit really is correct from all points of view.  For example, you can
1189837Skrischeck with the other documents in this directory tree, or by comparing
1289837Skriswith relevant parts of the include files.
1389837Skris
1489837SkrisPeople have done the mistake of trusting what's written here.  Please
1589837Skrisdon't do that.
1689837Skris
1789837Skris*** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! ***
1889837Skris
1989837Skris
2055714Skris==== readme ========================================================
2155714Skris
2255714SkrisThis is the old 0.6.6 docuementation.  Most of the cipher stuff is still
23238405Sjkimrelevent but I'm working (very slowly) on new documentation.
2455714SkrisThe current version can be found online at
2555714Skris
2655714Skrishttp://www.cryptsoft.com/ssleay/doc
2755714Skris
2855714Skris==== API.doc ========================================================
2955714Skris
3055714SkrisSSL - SSLv2/v3/v23 etc.
3155714Skris
3255714SkrisBIO - methods and how they plug together
3355714Skris
3455714SkrisMEM - memory allocation callback
3555714Skris
3655714SkrisCRYPTO - locking for threads
3755714Skris
3855714SkrisEVP - Ciphers/Digests/signatures
3955714Skris
4055714SkrisRSA - methods
4155714Skris
4255714SkrisX509 - certificate retrieval
4355714Skris
4455714SkrisX509 - validation
4555714Skris
4655714SkrisX509 - X509v3 extensions
4755714Skris
4855714SkrisObjects - adding object identifiers
4955714Skris
5055714SkrisASN.1 - parsing
5155714Skris
5255714SkrisPEM - parsing
5355714Skris
5455714Skris==== ssl/readme =====================================================
5555714Skris
5655714Skris22 Jun 1996
5755714SkrisThis file belongs in ../apps, but I'll leave it here because it deals
5855714Skriswith SSL :-)  It is rather dated but it gives you an idea of how
5955714Skristhings work.
6055714Skris===
6155714Skris
6255714Skris17 Jul 1995
6355714SkrisI have been changing things quite a bit and have not fully updated
6455714Skristhis file, so take what you read with a grain of salt
6555714Skriseric
6655714Skris===
6755714SkrisThe s_client and s_server programs can be used to test SSL capable
6855714SkrisIP/port addresses and the verification of the X509 certificates in use
6955714Skrisby these services.  I strongly advise having a look at the code to get
7055714Skrisan idea of how to use the authentication under SSLeay.  Any feedback
7155714Skrison changes and improvements would be greatly accepted.
7255714Skris
7355714SkrisThis file will probably be gibberish unless you have read
7455714Skrisrfc1421, rfc1422, rfc1423 and rfc1424 which describe PEM
7555714Skrisauthentication.
7655714Skris
7755714SkrisA Brief outline (and examples) how to use them to do so.
7855714Skris
7955714SkrisNOTE:
8055714SkrisThe environment variable SSL_CIPER is used to specify the prefered
8155714Skriscipher to use, play around with setting it's value to combinations of
8255714SkrisRC4-MD5, EXP-RC4-MD5, CBC-DES-MD5, CBC3-DES-MD5, CFB-DES-NULL
8355714Skrisin a : separated list.
8455714Skris
8555714SkrisThis directory contains 3 X509 certificates which can be used by these programs.
8655714Skrisclient.pem: a file containing a certificate and private key to be used
8755714Skris	by s_client.
8855714Skrisserver.pem :a file containing a certificate and private key to be used
8955714Skris	by s_server.
9055714Skriseay1024.pem:the certificate used to sign client.pem and server.pem.
9155714Skris	This would be your CA's certificate.  There is also a link
9255714Skris	from the file a8556381.0 to eay1024.PEM.  The value a8556381
9355714Skris	is returned by 'x509 -hash -noout <eay1024.pem' and is the
9455714Skris	value used by X509 verification routines to 'find' this
9555714Skris	certificte when search a directory for it.
9655714Skris	[the above is not true any more, the CA cert is 
9755714Skris	 ../certs/testca.pem which is signed by ../certs/mincomca.pem]
9855714Skris
9955714SkrisWhen testing the s_server, you may get
10055714Skrisbind: Address already in use
10155714Skriserrors.  These indicate the port is still being held by the unix
10255714Skriskernel and you are going to have to wait for it to let go of it.  If
10355714Skristhis is the case, remember to use the port commands on the s_server and
10455714Skriss_client to talk on an alternative port.
10555714Skris
10655714Skris=====
10755714Skriss_client.
10855714SkrisThis program can be used to connect to any IP/hostname:port that is
10955714Skristalking SSL.  Once connected, it will attempt to authenticate the
11055714Skriscertificate it was passed and if everything works as expected, a 2
11155714Skrisdirectional channel will be open.  Any text typed will be sent to the
11255714Skrisother end.  type Q<cr> to exit.  Flags are as follows.
11355714Skris-host arg	: Arg is the host or IP address to connect to.
11455714Skris-port arg	: Arg is the port to connect to (https is 443).
11555714Skris-verify arg	: Turn on authentication of the server certificate.
11655714Skris		: Arg specifies the 'depth', this will covered below.
11755714Skris-cert arg	: The optional certificate to use.  This certificate
11855714Skris		: will be returned to the server if the server
11955714Skris		: requests it for client authentication.
12055714Skris-key arg	: The private key that matches the certificate
12155714Skris		: specified by the -cert option.  If this is not
12255714Skris		: specified (but -cert is), the -cert file will be
12355714Skris		: searched for the Private key.  Both files are
12455714Skris		: assumed to be in PEM format.
12555714Skris-CApath arg	: When to look for certificates when 'verifying' the
12655714Skris		: certificate from the server.
12755714Skris-CAfile arg	: A file containing certificates to be used for
12855714Skris		: 'verifying' the server certificate.
12955714Skris-reconnect	: Once a connection has been made, drop it and
13055714Skris		: reconnect with same session-id.  This is for testing :-).
13155714Skris
13255714SkrisThe '-verify n' parameter specifies not only to verify the servers
13355714Skriscertificate but to also only take notice of 'n' levels.  The best way
13455714Skristo explain is to show via examples.
13555714SkrisGiven
13655714Skriss_server -cert server.PEM is running.
13755714Skris
13855714Skriss_client
13955714Skris	CONNECTED
14055714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
14155714Skris	issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
14255714Skris	verify error:num=1:unable to get issuer certificate
14355714Skris	verify return:1
14455714Skris	CIPHER is CBC-DES-MD5
14555714SkrisWhat has happened is that the 'SSLeay demo server' certificate's
14655714Skrisissuer ('CA') could not be found but because verify is not on, we
14755714Skrisdon't care and the connection has been made anyway.  It is now 'up'
14855714Skrisusing CBC-DES-MD5 mode.  This is an unauthenticate secure channel.
14955714SkrisYou may not be talking to the right person but the data going to them
15055714Skrisis encrypted.
15155714Skris
15255714Skriss_client -verify 0
15355714Skris	CONNECTED
15455714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
15555714Skris	issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
15655714Skris	verify error:num=1:unable to get issuer certificate
15755714Skris	verify return:1
15855714Skris	CIPHER is CBC-DES-MD5
15955714SkrisWe are 'verifying' but only to depth 0, so since the 'SSLeay demo server'
16055714Skriscertificate passed the date and checksum, we are happy to proceed.
16155714Skris
16255714Skriss_client -verify 1
16355714Skris	CONNECTED
16455714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
16555714Skris	issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
16655714Skris	verify error:num=1:unable to get issuer certificate
16755714Skris	verify return:0
16855714Skris	ERROR
16955714Skris	verify error:unable to get issuer certificate
17055714SkrisIn this case we failed to make the connection because we could not
17155714Skrisauthenticate the certificate because we could not find the
17255714Skris'CA' certificate.
17355714Skris
17455714Skriss_client -verify 1 -CAfile eay1024.PEM
17555714Skris	CONNECTED
17655714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
17755714Skris	verify return:1
17855714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
17955714Skris	verify return:1
18055714Skris	CIPHER is CBC-DES-MD5
18155714SkrisWe loaded the certificates from the file eay1024.PEM.  Everything
18255714Skrischecked out and so we made the connection.
18355714Skris
18455714Skriss_client -verify 1 -CApath .
18555714Skris	CONNECTED
18655714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
18755714Skris	verify return:1
18855714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
18955714Skris	verify return:1
19055714Skris	CIPHER is CBC-DES-MD5
19155714SkrisWe looked in out local directory for issuer certificates and 'found'
19255714Skrisa8556381.0 and so everything is ok.
19355714Skris
19455714SkrisIt is worth noting that 'CA' is a self certified certificate.  If you
19555714Skrisare passed one of these, it will fail to 'verify' at depth 0 because
19655714Skriswe need to lookup the certifier of a certificate from some information
19755714Skristhat we trust and keep locally.
19855714Skris
19955714SkrisSSL_CIPHER=CBC3-DES-MD5:RC4-MD5
20055714Skrisexport SSL_CIPHER
20155714Skriss_client -verify 10 -CApath . -reconnect
20255714Skris	CONNECTED
20355714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
20455714Skris	verify return:1
20555714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
20655714Skris	verify return:1
20755714Skris	drop the connection and reconnect with the same session id
20855714Skris	CIPHER is CBC3-DES-MD5
20955714SkrisThis has done a full connection and then re-estabished it with the
21055714Skrissame session id but a new socket.  No RSA stuff occures on the second
21155714Skrisconnection.  Note that we said we would prefer to use CBC3-DES-MD5
21255714Skrisencryption and so, since the server supports it, we are.
21355714Skris
21455714Skris=====
21555714Skriss_server
21655714SkrisThis program accepts SSL connections on a specified port
21755714SkrisOnce connected, it will estabish an SSL connection and optionaly
21855714Skrisattempt to authenticate the client.  A 2 directional channel will be
21955714Skrisopen.  Any text typed will be sent to the other end.  Type Q<cr> to exit.
22055714SkrisFlags are as follows.
22155714Skris-port arg	: Arg is the port to listen on.
22255714Skris-verify arg	: Turn on authentication of the client if they have a
22355714Skris		: certificate.  Arg specifies the 'depth'.
22455714Skris-Verify arg	: Turn on authentication of the client. If they don't
22555714Skris		: have a valid certificate, drop the connection.
22655714Skris-cert arg	: The certificate to use.  This certificate
22755714Skris		: will be passed to the client.  If it is not
22855714Skris		: specified, it will default to server.PEM
22955714Skris-key arg	: The private key that matches the certificate
23055714Skris		: specified by the -cert option.  If this is not
23155714Skris		: specified (but -cert is), the -cert file will be
23255714Skris		: searched for the Private key.  Both files are
23355714Skris		: assumed to be in PEM format.  Default is server.PEM
23455714Skris-CApath arg	: When to look for certificates when 'verifying' the
23555714Skris		: certificate from the client.
23655714Skris-CAfile arg	: A file containing certificates to be used for
23755714Skris		: 'verifying' the client certificate.
23855714Skris
23955714SkrisFor the following 'demo'  I will specify the s_server command and
24055714Skristhe s_client command and then list the output from the s_server.
24155714Skriss_server
24255714Skriss_client
24355714Skris	CONNECTED
24455714Skris	CIPHER is CBC-DES-MD5
24555714SkrisEverything up and running
24655714Skris
24755714Skriss_server -verify 0
24855714Skriss_client  
24955714Skris	CONNECTED
25055714Skris	CIPHER is CBC-DES-MD5
25155714SkrisOk since no certificate was returned and we don't care.
25255714Skris
25355714Skriss_server -verify 0
25455714Skris./s_client -cert client.PEM
25555714Skris	CONNECTED
25655714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
25755714Skris	issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
25855714Skris	verify error:num=1:unable to get issuer certificate
25955714Skris	verify return:1
26055714Skris	CIPHER is CBC-DES-MD5
26155714SkrisOk since we were only verifying to level 0
26255714Skris
26355714Skriss_server -verify 4
26455714Skriss_client -cert client.PEM
26555714Skris	CONNECTED
26655714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
26755714Skris	issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
26855714Skris	verify error:num=1:unable to get issuer certificate
26955714Skris	verify return:0
27055714Skris	ERROR
27155714Skris	verify error:unable to get issuer certificate
27255714SkrisBad because we could not authenticate the returned certificate.
27355714Skris
27455714Skriss_server -verify 4 -CApath .
27555714Skriss_client -cert client.PEM
27655714Skris	CONNECTED
27755714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
27855714Skris	verify return:1
27955714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
28055714Skris	verify return:1
28155714Skris	CIPHER is CBC-DES-MD5
28255714SkrisOk because we could authenticate the returned certificate :-).
28355714Skris
28455714Skriss_server -Verify 0 -CApath .
28555714Skriss_client
28655714Skris	CONNECTED
28755714Skris	ERROR
28855714Skris	SSL error:function is:REQUEST_CERTIFICATE
28955714Skris		 :error is   :client end did not return a certificate
29055714SkrisError because no certificate returned.
29155714Skris
29255714Skriss_server -Verify 4 -CApath .
29355714Skriss_client -cert client.PEM
29455714Skris	CONNECTED
29555714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
29655714Skris	verify return:1
29755714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
29855714Skris	verify return:1
29955714Skris	CIPHER is CBC-DES-MD5
30055714SkrisFull authentication of the client.
30155714Skris
30255714SkrisSo in summary to do full authentication of both ends
30355714Skriss_server -Verify 9 -CApath .
30455714Skriss_client -cert client.PEM -CApath . -verify 9
30555714SkrisFrom the server side
30655714Skris	CONNECTED
30755714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
30855714Skris	verify return:1
30955714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
31055714Skris	verify return:1
31155714Skris	CIPHER is CBC-DES-MD5
31255714SkrisFrom the client side
31355714Skris	CONNECTED
31455714Skris	depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
31555714Skris	verify return:1
31655714Skris	depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
31755714Skris	verify return:1
31855714Skris	CIPHER is CBC-DES-MD5
31955714Skris
32055714SkrisFor general probing of the 'internet https' servers for the
32155714Skrisdistribution area, run
32255714Skriss_client -host www.netscape.com -port 443 -verify 4 -CApath ../rsa/hash
32355714SkrisThen enter
32455714SkrisGET /
32555714Skrisand you should be talking to the https server on that host.
32655714Skris
32755714Skriswww.rsa.com was refusing to respond to connections on 443 when I was
32855714Skristesting.
32955714Skris
33055714Skrishave fun :-).
33155714Skris
33255714Skriseric
33355714Skris
33455714Skris==== a_verify.doc ========================================================
33555714Skris
33655714SkrisFrom eay@mincom.com Fri Oct  4 18:29:06 1996
33755714SkrisReceived: by orb.mincom.oz.au id AA29080
33855714Skris  (5.65c/IDA-1.4.4 for eay); Fri, 4 Oct 1996 08:29:07 +1000
33955714SkrisDate: Fri, 4 Oct 1996 08:29:06 +1000 (EST)
34055714SkrisFrom: Eric Young <eay@mincom.oz.au>
34155714SkrisX-Sender: eay@orb
34255714SkrisTo: wplatzer <wplatzer@iaik.tu-graz.ac.at>
34355714SkrisCc: Eric Young <eay@mincom.oz.au>, SSL Mailing List <ssl-users@mincom.com>
34455714SkrisSubject: Re: Netscape's Public Key
34555714SkrisIn-Reply-To: <19961003134837.NTM0049@iaik.tu-graz.ac.at>
34655714SkrisMessage-Id: <Pine.SOL.3.91.961004081346.8018K-100000@orb>
34755714SkrisMime-Version: 1.0
34855714SkrisContent-Type: TEXT/PLAIN; charset=US-ASCII
34955714SkrisStatus: RO
35055714SkrisX-Status: 
35155714Skris
35255714SkrisOn Thu, 3 Oct 1996, wplatzer wrote:
35355714Skris> I get Public Key from Netscape (Gold 3.0b4), but cannot do anything
35455714Skris> with it... It looks like (asn1parse):
35555714Skris> 
35655714Skris> 0:d=0 hl=3 l=180 cons: SEQUENCE
35755714Skris> 3:d=1 hl=2 l= 96 cons: SEQUENCE
35855714Skris> 5:d=2 hl=2 l= 92 cons: SEQUENCE
35955714Skris> 7:d=3 hl=2 l= 13 cons: SEQUENCE
36055714Skris> 9:d=4 hl=2 l= 9 prim: OBJECT :rsaEncryption
36155714Skris> 20:d=4 hl=2 l= 0 prim: NULL
36255714Skris> 22:d=3 hl=2 l= 75 prim: BIT STRING
36355714Skris> 99:d=2 hl=2 l= 0 prim: IA5STRING :
36455714Skris> 101:d=1 hl=2 l= 13 cons: SEQUENCE
36555714Skris> 103:d=2 hl=2 l= 9 prim: OBJECT :md5withRSAEncryption
36655714Skris> 114:d=2 hl=2 l= 0 prim: NULL
36755714Skris> 116:d=1 hl=2 l= 65 prim: BIT STRING
36855714Skris> 
36955714Skris> The first BIT STRING is the public key and the second BIT STRING is 
37055714Skris> the signature.
37155714Skris> But a public key consists of the public exponent and the modulus. Are 
37255714Skris> both numbers in the first BIT STRING?
37355714Skris> Is there a document simply describing this coding stuff (checking 
37455714Skris> signature, get the public key, etc.)?
37555714Skris
37655714SkrisMinimal in SSLeay.  If you want to see what the modulus and exponent are,
37755714Skristry asn1parse -offset 25 -length 75 <key.pem
37855714Skrisasn1parse will currently stuff up on the 'length 75' part (fixed in next 
37955714Skrisrelease) but it will print the stuff.  If you are after more 
38055714Skrisdocumentation on ASN.1, have a look at www.rsa.com and get their PKCS 
38155714Skrisdocuments, most of my initial work on SSLeay was done using them.
38255714Skris
38355714SkrisAs for SSLeay,
38455714Skrisutil/crypto.num and util/ssl.num are lists of all exported functions in 
38555714Skristhe library (but not macros :-(.
38655714Skris
38755714SkrisThe ones for extracting public keys from certificates and certificate 
38855714Skrisrequests are EVP_PKEY *      X509_REQ_extract_key(X509_REQ *req);
38955714SkrisEVP_PKEY *      X509_extract_key(X509 *x509);
39055714Skris
39155714SkrisTo verify a signature on a signed ASN.1 object
39255714Skrisint X509_verify(X509 *a,EVP_PKEY *key);
39355714Skrisint X509_REQ_verify(X509_REQ *a,EVP_PKEY *key);
39455714Skrisint X509_CRL_verify(X509_CRL *a,EVP_PKEY *key);
39555714Skrisint NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a,EVP_PKEY *key);
39655714Skris
39755714SkrisI should mention that EVP_PKEY can be used to hold a public or a private key,
39855714Skrissince for  things like RSA and DSS, a public key is just a subset of what 
39955714Skrisis stored for the private key.
40055714Skris
40155714SkrisTo sign any of the above structures
40255714Skris
40355714Skrisint X509_sign(X509 *a,EVP_PKEY *key,EVP_MD *md);
40455714Skrisint X509_REQ_sign(X509_REQ *a,EVP_PKEY *key,EVP_MD *md);
40555714Skrisint X509_CRL_sign(X509_CRL *a,EVP_PKEY *key,EVP_MD *md);
40655714Skrisint NETSCAPE_SPKI_sign(NETSCAPE_SPKI *a,EVP_PKEY *key,EVP_MD *md);
40755714Skris
40855714Skriswhere md is the message digest to sign with.
40955714Skris
41055714SkrisThere are all defined in x509.h and all the _sign and _verify functions are
41155714Skrisactually macros to the ASN1_sign() and ASN1_verify() functions.
41255714SkrisThese functions will put the correct algorithm identifiers in the correct 
41355714Skrisplaces in the structures.
41455714Skris
41555714Skriseric
41655714Skris--
41755714SkrisEric Young                  | BOOL is tri-state according to Bill Gates.
41855714SkrisAARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
41955714Skris
42055714Skris==== x509 =======================================================
42155714Skris
42255714SkrisX509_verify()
42355714SkrisX509_sign()
42455714Skris
42555714SkrisX509_get_version()
42655714SkrisX509_get_serialNumber()
42755714SkrisX509_get_issuer()
42855714SkrisX509_get_subject()
42955714SkrisX509_get_notBefore()
43055714SkrisX509_get_notAfter()
43155714SkrisX509_get_pubkey()
43255714Skris
43355714SkrisX509_set_version()
43455714SkrisX509_set_serialNumber()
43555714SkrisX509_set_issuer()
43655714SkrisX509_set_subject()
43755714SkrisX509_set_notBefore()
43855714SkrisX509_set_notAfter()
43955714SkrisX509_set_pubkey()
44055714Skris
44155714SkrisX509_get_extensions()
44255714SkrisX509_set_extensions()
44355714Skris
44455714SkrisX509_EXTENSIONS_clear()
44555714SkrisX509_EXTENSIONS_retrieve()
44655714SkrisX509_EXTENSIONS_add()
44755714SkrisX509_EXTENSIONS_delete()
44855714Skris
44955714Skris==== x509 attribute ================================================
45055714Skris
45155714SkrisPKCS7
45255714Skris	STACK of X509_ATTRIBUTES
45355714Skris		ASN1_OBJECT
45455714Skris		STACK of ASN1_TYPE
45555714Skris
45655714SkrisSo it is
45755714Skris
45855714Skrisp7.xa[].obj
45955714Skrisp7.xa[].data[]
46055714Skris
46155714Skrisget_obj_by_nid(STACK , nid)
46255714Skrisget_num_by_nid(STACK , nid)
46355714Skrisget_data_by_nid(STACK , nid, index)
46455714Skris
46555714SkrisX509_ATTRIBUTE *X509_ATTRIBUTE_new(void );
46655714Skrisvoid		X509_ATTRIBUTE_free(X509_ATTRIBUTE *a);
46755714Skris
46855714SkrisX509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **ex,
46955714Skris			int nid, STACK *value);
47055714Skris
47155714SkrisX509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **ex,
47255714Skris			int nid, STACK *value);
47355714Skris
47455714Skrisint		X509_ATTRIBUTE_set_object(X509_ATTRIBUTE *ex,ASN1_OBJECT *obj);
47555714Skrisint		X509_ATTRIBUTE_add_data(X509_ATTRIBUTE *ex, int index,
47655714Skris			ASN1_TYPE *value);
47755714Skris
47855714SkrisASN1_OBJECT *	X509_ATTRIBUTE_get_object(X509_ATTRIBUTE *ex);
47955714Skrisint 		X509_ATTRIBUTE_get_num(X509_ATTRIBUTE *ne);
48055714SkrisASN1_TYPE *	X509_ATTRIBUTE_get_data(X509_ATTRIBUTE *ne,int index);
48155714Skris
48255714SkrisASN1_TYPE *	X509_ATTRIBUTE_get_data_by_NID(X509_ATTRIBUTE *ne,
48355714Skris			ASN1_OBJECT *obj);
48455714Skris
48555714SkrisX509_ATTRIBUTE *PKCS7_get_s_att_by_NID(PKCS7 *p7,int nid);
48655714SkrisX509_ATTRIBUTE *PKCS7_get_u_att_by_NID(PKCS7 *p7,int nid);
48755714Skris
48855714Skris==== x509 v3 ========================================================
48955714Skris
49055714SkrisThe 'new' system.
49155714Skris
49255714SkrisThe X509_EXTENSION_METHOD includes extensions and attributes and/or names. 
49355714SkrisBasically everthing that can be added to an X509 with an OID identifying it.
49455714Skris
49555714SkrisIt operates via 2 methods per object id.
49655714Skrisint a2i_XXX(X509 *x,char *str,int len);
49755714Skrisint i2a_XXX(BIO *bp,X509 *x);
49855714Skris
49955714SkrisThe a2i_XXX function will add the object with a value converted from the
50055714Skrisstring into the X509.  Len can be -1 in which case the length is calculated
50155714Skrisvia strlen(str).   Applications can always use direct knowledge to load and
50255714Skrisunload the relevent objects themselves.
50355714Skris
50455714Skrisi2a_XXX will print to the passed BIO, a text representation of the
50555714Skrisrelevet object.  Use a memory BIO if you want it printed to a buffer :-).
50655714Skris
50755714SkrisX509_add_by_NID(X509 *x,int nid,char *str,int len);
50855714SkrisX509_add_by_OBJ(X509 *x,ASN1_OBJECT *obj,char *str,int len);
50955714Skris
51055714SkrisX509_print_by_name(BIO *bp,X509 *x);
51155714SkrisX509_print_by_NID(BIO *bp,X509 *x);
51255714SkrisX509_print_by_OBJ(BIO *bp,X509 *x);
51355714Skris
51455714Skris==== verify ========================================================
51555714Skris
51655714SkrisX509_verify_cert_chain(
51755714Skris	CERT_STORE *cert_store,
51855714Skris	STACK /* X509 */ *certs,
51955714Skris	int *verify_result,
52055714Skris	int (*verify_error_callback)()
52155714Skris	char *argument_to_callback, /* SSL */
52255714Skris
52355714Skrisapp_verify_callback(
52455714Skris	char *app_verify_arg, /* from SSL_CTX */
52555714Skris	STACK /* X509 */ *certs,
52655714Skris	int *verify_result,
52755714Skris	int (*verify_error_callback)()
52855714Skris	SSL *s,
52955714Skris
53055714Skrisint X509_verify_cert(
53155714Skris	CERT_STORE *cert_store,
53255714Skris	X509 *x509,
53355714Skris	int *verify_result,
53455714Skris	int (*verify_error_callback)(),
53555714Skris	char *arg,
53655714Skris
53755714Skris==== apps.doc ========================================================
53855714Skris
53955714SkrisThe applications
54055714Skris
54155714SkrisOk, where to begin....
54255714SkrisIn the begining, when SSLeay was small (April 1995), there
54355714Skriswere but few applications, they did happily cohabit in
54455714Skristhe one bin directory.  Then over time, they did multiply and grow,
54555714Skrisand they started to look like microsoft software; 500k to print 'hello world'.
54655714SkrisA new approach was needed.  They were coalessed into one 'Monolithic'
54755714Skrisapplication, ssleay.  This one program is composed of many programs that
54855714Skriscan all be compiled independantly.
54955714Skris
55055714Skrisssleay has 3 modes of operation.
551238405Sjkim1) If the ssleay binary has the name of one of its component programs, it
552238405Sjkimexecutes that program and then exits.  This can be achieved by using hard or
55355714Skrissymbolic links, or failing that, just renaming the binary.
55455714Skris2) If the first argument to ssleay is the name of one of the component
55555714Skrisprograms, that program runs that program and then exits.
55655714Skris3) If there are no arguments, ssleay enters a 'command' mode.  Each line is
55755714Skrisinterpreted as a program name plus arguments.  After each 'program' is run,
55855714Skrisssleay returns to the comand line.
55955714Skris
56055714Skrisdgst	- message digests
56155714Skrisenc	- encryption and base64 encoding
56255714Skris
56355714Skrisans1parse - 'pulls' appart ASN.1 encoded objects like certificates.
56455714Skris
56555714Skrisdh	- Diffle-Hellman parameter manipulation.
56655714Skrisrsa	- RSA manipulations.
56755714Skriscrl	- Certificate revokion list manipulations
56855714Skrisx509	- X509 cert fiddles, including signing.
56955714Skrispkcs7	- pkcs7 manipulation, only DER versions right now.
57055714Skris
57155714Skrisgenrsa	- generate an RSA private key.
57255714Skrisgendh	- Generate a set of Diffle-Hellman parameters.
57355714Skrisreq	- Generate a PKCS#10 object, a certificate request.
57455714Skris
57555714Skriss_client - SSL client program
57655714Skriss_server - SSL server program
57755714Skriss_time	 - A SSL protocol timing program
57855714Skriss_mult	 - Another SSL server, but it multiplexes
57955714Skris	   connections.
58055714Skriss_filter - under development
58155714Skris
58255714Skriserrstr	- Convert SSLeay error numbers to strings.
58355714Skrisca	- Sign certificate requests, and generate
58455714Skris	  certificate revokion lists
58555714Skriscrl2pkcs7 - put a crl and certifcates into a pkcs7 object.
58655714Skrisspeed	- Benchmark the ciphers.
58755714Skrisverify	- Check certificates
58855714Skrishashdir - under development
58955714Skris
59055714Skris[ there a now a few more options, play with the program to see what they
59155714Skris  are ]
59255714Skris
59355714Skris==== asn1.doc ========================================================
59455714Skris
59555714SkrisThe ASN.1 Routines.
59655714Skris
59755714SkrisASN.1 is a specification for how to encode structured 'data' in binary form.
59855714SkrisThe approach I have take to the manipulation of structures and their encoding
59955714Skrisinto ASN.1 is as follows.
60055714Skris
60155714SkrisFor each distinct structure there are 4 function of the following form
60255714SkrisTYPE *TYPE_new(void);
60355714Skrisvoid TYPE_free(TYPE *);
60455714SkrisTYPE *d2i_TYPE(TYPE **a,unsigned char **pp,long length);
60555714Skrislong i2d_TYPE(TYPE *a,unsigned char **pp); 	/* CHECK RETURN VALUE */
60655714Skris
60755714Skriswhere TYPE is the type of the 'object'.  The TYPE that have these functions
60855714Skriscan be in one of 2 forms, either the internal C malloc()ed data structure
60955714Skrisor in the DER (a variant of ASN.1 encoding) binary encoding which is just
61055714Skrisan array of unsigned bytes.  The 'i2d' functions converts from the internal
61155714Skrisform to the DER form and the 'd2i' functions convert from the DER form to
61255714Skristhe internal form.
61355714Skris
61455714SkrisThe 'new' function returns a malloc()ed version of the structure with all
61555714Skrissubstructures either created or left as NULL pointers.  For 'optional'
61655714Skrisfields, they are normally left as NULL to indicate no value.  For variable
61755714Skrissize sub structures (often 'SET OF' or 'SEQUENCE OF' in ASN.1 syntax) the
61855714SkrisSTACK data type is used to hold the values.  Have a read of stack.doc
61955714Skrisand have a look at the relevant header files to see what I mean.  If there
62055714Skrisis an error while malloc()ing the structure, NULL is returned.
62155714Skris
62255714SkrisThe 'free' function will free() all the sub components of a particular
62355714Skrisstructure.  If any of those sub components have been 'removed', replace
62455714Skristhem with NULL pointers, the 'free' functions are tolerant of NULL fields.
62555714Skris
62655714SkrisThe 'd2i' function copies a binary representation into a C structure.  It
62755714Skrisoperates as follows.  'a' is a pointer to a pointer to
62855714Skristhe structure to populate, 'pp' is a pointer to a pointer to where the DER
62955714Skrisbyte string is located and 'length' is the length of the '*pp' data.
63055714SkrisIf there are no errors, a pointer to the populated structure is returned.
63155714SkrisIf there is an error, NULL is returned.  Errors can occur because of
63255714Skrismalloc() failures but normally they will be due to syntax errors in the DER
63355714Skrisencoded data being parsed. It is also an error if there was an
63455714Skrisattempt to read more that 'length' bytes from '*p'.  If
63555714Skriseverything works correctly, the value in '*p' is updated
63655714Skristo point at the location just beyond where the DER
63755714Skrisstructure was read from.  In this way, chained calls to 'd2i' type
63855714Skrisfunctions can be made, with the pointer into the 'data' array being
63955714Skris'walked' along the input byte array.
64055714SkrisDepending on the value passed for 'a', different things will be done.  If
64155714Skris'a' is NULL, a new structure will be malloc()ed and returned.  If '*a' is
64255714SkrisNULL, a new structure will be malloc()ed and put into '*a' and returned.
64355714SkrisIf '*a' is not NULL, the structure in '*a' will be populated, or in the
64455714Skriscase of an error, free()ed and then returned.
64555714SkrisHaving these semantics means that a structure
64655714Skriscan call a 'd2i' function to populate a field and if the field is currently
64755714SkrisNULL, the structure will be created.
64855714Skris
64955714SkrisThe 'i2d' function type is used to copy a C structure to a byte array.
65055714SkrisThe parameter 'a' is the structure to convert and '*p' is where to put it.
65155714SkrisAs for the 'd2i' type structure, 'p' is updated to point after the last
65255714Skrisbyte written.  If p is NULL, no data is written.  The function also returns
65355714Skristhe number of bytes written.  Where this becomes useful is that if the
65455714Skrisfunction is called with a NULL 'p' value, the length is returned.  This can
65555714Skristhen be used to malloc() an array of bytes and then the same function can
65655714Skrisbe recalled passing the malloced array to be written to. e.g.
65755714Skris
65855714Skrisint len;
65955714Skrisunsigned char *bytes,*p;
66055714Skrislen=i2d_X509(x,NULL);	/* get the size of the ASN1 encoding of 'x' */
66155714Skrisif ((bytes=(unsigned char *)malloc(len)) == NULL)
66255714Skris	goto err;
66355714Skrisp=bytes;
66455714Skrisi2d_X509(x,&p);
66555714Skris
66655714SkrisPlease note that a new variable, 'p' was passed to i2d_X509.  After the
66755714Skriscall to i2d_X509 p has been incremented by len bytes.
66855714Skris
66955714SkrisNow the reason for this functional organisation is that it allows nested
67055714Skrisstructures to be built up by calling these functions as required.  There
67155714Skrisare various macros used to help write the general 'i2d', 'd2i', 'new' and
67255714Skris'free' functions.  They are discussed in another file and would only be
67355714Skrisused by some-one wanting to add new structures to the library.  As you
67455714Skrismight be able to guess, the process of writing ASN.1 files can be a bit CPU
67555714Skrisexpensive for complex structures.  I'm willing to live with this since the
67655714Skrissimpler library code make my life easier and hopefully most programs using
67755714Skristhese routines will have their execution profiles dominated by cipher or
67855714Skrismessage digest routines.
67955714SkrisWhat follows is a list of 'TYPE' values and the corresponding ASN.1
68055714Skrisstructure and where it is used.
68155714Skris
68255714SkrisTYPE			ASN.1
68355714SkrisASN1_INTEGER		INTEGER
68455714SkrisASN1_BIT_STRING		BIT STRING
68555714SkrisASN1_OCTET_STRING	OCTET STRING
68655714SkrisASN1_OBJECT		OBJECT IDENTIFIER
68755714SkrisASN1_PRINTABLESTRING	PrintableString
68855714SkrisASN1_T61STRING		T61String
68955714SkrisASN1_IA5STRING		IA5String
69055714SkrisASN1_UTCTIME		UTCTime
69155714SkrisASN1_TYPE		Any of the above mentioned types plus SEQUENCE and SET
69255714Skris
69355714SkrisMost of the above mentioned types are actualled stored in the
69455714SkrisASN1_BIT_STRING type and macros are used to differentiate between them.
69555714SkrisThe 3 types used are
69655714Skris
69755714Skristypedef struct asn1_object_st
69855714Skris	{
69955714Skris	/* both null if a dynamic ASN1_OBJECT, one is
70055714Skris	 * defined if a 'static' ASN1_OBJECT */
70155714Skris	char *sn,*ln;
70255714Skris	int nid;
70355714Skris	int length;
70455714Skris	unsigned char *data;
70555714Skris	} ASN1_OBJECT;
70655714SkrisThis is used to store ASN1 OBJECTS.  Read 'objects.doc' for details ono
70755714Skrisroutines to manipulate this structure.  'sn' and 'ln' are used to hold text
70855714Skrisstrings that represent the object (short name and long or lower case name).
70955714SkrisThese are used by the 'OBJ' library.  'nid' is a number used by the OBJ
71055714Skrislibrary to uniquely identify objects.  The ASN1 routines will populate the
71155714Skris'length' and 'data' fields which will contain the bit string representing
71255714Skristhe object.
71355714Skris
71455714Skristypedef struct asn1_bit_string_st
71555714Skris	{
71655714Skris	int length;
71755714Skris	int type;
71855714Skris	unsigned char *data;
71955714Skris	} ASN1_BIT_STRING;
72055714SkrisThis structure is used to hold all the other base ASN1 types except for
72155714SkrisASN1_UTCTIME (which is really just a 'char *').  Length is the number of
72255714Skrisbytes held in data and type is the ASN1 type of the object (there is a list
72355714Skrisin asn1.h).
72455714Skris
72555714Skristypedef struct asn1_type_st
72655714Skris	{
72755714Skris	int type;
72855714Skris	union	{
72955714Skris		char *ptr;
73055714Skris		ASN1_INTEGER *		integer;
73155714Skris		ASN1_BIT_STRING *	bit_string;
73255714Skris		ASN1_OCTET_STRING *	octet_string;
73355714Skris		ASN1_OBJECT *		object;
73455714Skris		ASN1_PRINTABLESTRING *	printablestring;
73555714Skris		ASN1_T61STRING *	t61string;
73655714Skris		ASN1_IA5STRING *	ia5string;
73755714Skris		ASN1_UTCTIME *		utctime;
73855714Skris		ASN1_BIT_STRING *	set;
73955714Skris		ASN1_BIT_STRING *	sequence;
74055714Skris		} value;
74155714Skris	} ASN1_TYPE;
74255714SkrisThis structure is used in a few places when 'any' type of object can be
74355714Skrisexpected.
74455714Skris
74555714SkrisX509			Certificate
74655714SkrisX509_CINF		CertificateInfo
74755714SkrisX509_ALGOR		AlgorithmIdentifier
74855714SkrisX509_NAME		Name			
74955714SkrisX509_NAME_ENTRY		A single sub component of the name.
75055714SkrisX509_VAL		Validity
75155714SkrisX509_PUBKEY		SubjectPublicKeyInfo
75255714SkrisThe above mentioned types are declared in x509.h. They are all quite
75355714Skrisstraight forward except for the X509_NAME/X509_NAME_ENTRY pair.
75455714SkrisA X509_NAME is a STACK (see stack.doc) of X509_NAME_ENTRY's.
75555714Skristypedef struct X509_name_entry_st
75655714Skris	{
75755714Skris	ASN1_OBJECT *object;
75855714Skris	ASN1_BIT_STRING *value;
75955714Skris	int set;
76055714Skris	int size; 	/* temp variable */
76155714Skris	} X509_NAME_ENTRY;
76255714SkrisThe size is a temporary variable used by i2d_NAME and set is the set number
76355714Skrisfor the particular NAME_ENTRY.  A X509_NAME is encoded as a sequence of
76455714Skrissequence of sets.  Normally each set contains only a single item.
76555714SkrisSometimes it contains more.  Normally throughout this library there will be
76655714Skrisonly one item per set.  The set field contains the 'set' that this entry is
76755714Skrisa member of.  So if you have just created a X509_NAME structure and
76855714Skrispopulated it with X509_NAME_ENTRYs, you should then traverse the X509_NAME
76955714Skris(which is just a STACK) and set the 'set/' field to incrementing numbers.
77055714SkrisFor more details on why this is done, read the ASN.1 spec for Distinguished
77155714SkrisNames.
77255714Skris
77355714SkrisX509_REQ		CertificateRequest
77455714SkrisX509_REQ_INFO		CertificateRequestInfo
77555714SkrisThese are used to hold certificate requests.
77655714Skris
77755714SkrisX509_CRL		CertificateRevocationList
77855714SkrisThese are used to hold a certificate revocation list
77955714Skris
78055714SkrisRSAPrivateKey		PrivateKeyInfo
78155714SkrisRSAPublicKey		PublicKeyInfo
78255714SkrisBoth these 'function groups' operate on 'RSA' structures (see rsa.doc).
78355714SkrisThe difference is that the RSAPublicKey operations only manipulate the m
78455714Skrisand e fields in the RSA structure.
78555714Skris
78655714SkrisDSAPrivateKey		DSS private key
78755714SkrisDSAPublicKey		DSS public key
78855714SkrisBoth these 'function groups' operate on 'DSS' structures (see dsa.doc).
78955714SkrisThe difference is that the RSAPublicKey operations only manipulate the 
79055714SkrisXXX fields in the DSA structure.
79155714Skris
79255714SkrisDHparams		DHParameter
79355714SkrisThis is used to hold the p and g value for The Diffie-Hellman operation.
79455714SkrisThe function deal with the 'DH' strucure (see dh.doc).
79555714Skris
79655714SkrisNow all of these function types can be used with several other functions to give
79755714Skrisquite useful set of general manipulation routines.  Normally one would
79855714Skrisnot uses these functions directly but use them via macros. 
79955714Skris
80055714Skrischar *ASN1_dup(int (*i2d)(),char *(*d2i)(),char *x);
80155714Skris'x' is the input structure case to a 'char *', 'i2d' is the 'i2d_TYPE'
80255714Skrisfunction for the type that 'x' is and d2i is the 'd2i_TYPE' function for the
80355714Skristype that 'x' is.  As is obvious from the parameters, this function
80455714Skrisduplicates the strucutre by transforming it into the DER form and then
80555714Skrisre-loading it into a new strucutre and returning the new strucutre.  This
80655714Skrisis obviously a bit cpu intensive but when faced with a complex dynamic
80755714Skrisstructure this is the simplest programming approach.  There are macros for
80855714Skrisduplicating the major data types but is simple to add extras.
80955714Skris
81055714Skrischar *ASN1_d2i_fp(char *(*new)(),char *(*d2i)(),FILE *fp,unsigned char **x);
81155714Skris'x' is a pointer to a pointer of the 'desired type'.  new and d2i are the
81255714Skriscorresponding 'TYPE_new' and 'd2i_TYPE' functions for the type and 'fp' is
81355714Skrisan open file pointer to read from.  This function reads from 'fp' as much
81455714Skrisdata as it can and then uses 'd2i' to parse the bytes to load and return
81555714Skristhe parsed strucutre in 'x' (if it was non-NULL) and to actually return the
81655714Skrisstrucutre.  The behavior of 'x' is as per all the other d2i functions.
81755714Skris
81855714Skrischar *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
81955714SkrisThe 'BIO' is the new IO type being used in SSLeay (see bio.doc).  This
82055714Skrisfunction is the same as ASN1_d2i_fp() except for the BIO argument.
82155714SkrisASN1_d2i_fp() actually calls this function.
82255714Skris
82355714Skrisint ASN1_i2d_fp(int (*i2d)(),FILE *out,unsigned char *x);
82455714Skris'x' is converted to bytes by 'i2d' and then written to 'out'.  ASN1_i2d_fp
82555714Skrisand ASN1_d2i_fp are not really symetric since ASN1_i2d_fp will read all
82655714Skrisavailable data from the file pointer before parsing a single item while
82755714SkrisASN1_i2d_fp can be used to write a sequence of data objects.  To read a
82855714Skrisseries of objects from a file I would sugest loading the file into a buffer
82955714Skrisand calling the relevent 'd2i' functions.
83055714Skris
83155714Skrischar *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
83255714SkrisThis function is the same as ASN1_i2d_fp() except for the BIO argument.
83355714SkrisASN1_i2d_fp() actually calls this function.
83455714Skris
83555714Skrischar *	PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
83655714SkrisThis function will read the next PEM encoded (base64) object of the same
83755714Skristype as 'x' (loaded by the d2i function).  'name' is the name that is in
83855714Skristhe '-----BEGIN name-----' that designates the start of that object type.
83955714SkrisIf the data is encrypted, 'cb' will be called to prompt for a password.  If
84055714Skrisit is NULL a default function will be used to prompt from the password.
84155714Skris'x' is delt with as per the standard 'd2i' function interface.  This
84255714Skrisfunction can be used to read a series of objects from a file.  While any
84355714Skrisdata type can be encrypted (see PEM_ASN1_write) only RSA private keys tend
84455714Skristo be encrypted.
84555714Skris
84655714Skrischar *	PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *fp,
84755714Skris	char **x,int (*cb)());
84855714SkrisSame as PEM_ASN1_read() except using a BIO.  This is called by
84955714SkrisPEM_ASN1_read().
85055714Skris
85155714Skrisint	PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,EVP_CIPHER *enc,
85255714Skris		unsigned char *kstr,int klen,int (*callback)());
85355714Skris
85455714Skrisint	PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *fp,
85555714Skris		char *x,EVP_CIPHER *enc,unsigned char *kstr,int klen,
85655714Skris		int (*callback)());
85755714Skris
85855714Skrisint ASN1_sign(int (*i2d)(), X509_ALGOR *algor1, X509_ALGOR *algor2,
85955714Skris	ASN1_BIT_STRING *signature, char *data, RSA *rsa, EVP_MD *type);
86055714Skrisint ASN1_verify(int (*i2d)(), X509_ALGOR *algor1,
86155714Skris	ASN1_BIT_STRING *signature,char *data, RSA *rsa);
86255714Skris
86355714Skrisint ASN1_BIT_STRING_cmp(ASN1_BIT_STRING *a, ASN1_BIT_STRING *b);
86455714SkrisASN1_BIT_STRING *ASN1_BIT_STRING_type_new(int type );
86555714Skris
86655714Skrisint ASN1_UTCTIME_check(ASN1_UTCTIME *a);
86755714Skrisvoid ASN1_UTCTIME_print(BIO *fp,ASN1_UTCTIME *a);
86855714SkrisASN1_UTCTIME *ASN1_UTCTIME_dup(ASN1_UTCTIME *a);
86955714Skris
87055714SkrisASN1_BIT_STRING *d2i_asn1_print_type(ASN1_BIT_STRING **a,unsigned char **pp,
87155714Skris		long length,int type);
87255714Skris
87355714Skrisint		i2d_ASN1_SET(STACK *a, unsigned char **pp,
87455714Skris			int (*func)(), int ex_tag, int ex_class);
87555714SkrisSTACK *		d2i_ASN1_SET(STACK **a, unsigned char **pp, long length,
87655714Skris			char *(*func)(), int ex_tag, int ex_class);
87755714Skris
87855714Skrisint i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *object);
87955714Skrisint i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
88055714Skrisint a2i_ASN1_INTEGER(BIO *bp,ASN1_INTEGER *bs,char *buf,int size);
88155714Skris
88255714Skrisint ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
88355714Skrislong ASN1_INTEGER_get(ASN1_INTEGER *a);
88455714SkrisASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
88555714SkrisBIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
88655714Skris
88755714Skris/* given a string, return the correct type.  Max is the maximum number
88855714Skris * of bytes to parse.  It stops parsing when 'max' bytes have been
88955714Skris * processed or a '\0' is hit */
89055714Skrisint ASN1_PRINTABLE_type(unsigned char *s,int max);
89155714Skris
89255714Skrisvoid ASN1_parse(BIO *fp,unsigned char *pp,long len);
89355714Skris
89455714Skrisint i2d_ASN1_bytes(ASN1_BIT_STRING *a, unsigned char **pp, int tag, int class);
89555714SkrisASN1_BIT_STRING *d2i_ASN1_bytes(ASN1_OCTET_STRING **a, unsigned char **pp,
89655714Skris	long length, int Ptag, int Pclass);
89755714Skris
89855714Skris/* PARSING */
89955714Skrisint asn1_Finish(ASN1_CTX *c);
90055714Skris
90155714Skris/* SPECIALS */
90255714Skrisint ASN1_get_object(unsigned char **pp, long *plength, int *ptag,
90355714Skris	int *pclass, long omax);
90455714Skrisint ASN1_check_infinite_end(unsigned char **p,long len);
90555714Skrisvoid ASN1_put_object(unsigned char **pp, int constructed, int length,
90655714Skris	int tag, int class);
90755714Skrisint ASN1_object_size(int constructed, int length, int tag);
90855714Skris
90955714SkrisX509 *	X509_get_cert(CERTIFICATE_CTX *ctx,X509_NAME * name,X509 *tmp_x509);
91055714Skrisint  	X509_add_cert(CERTIFICATE_CTX *ctx,X509 *);
91155714Skris
91255714Skrischar *	X509_cert_verify_error_string(int n);
91355714Skrisint 	X509_add_cert_file(CERTIFICATE_CTX *c,char *file, int type);
91455714Skrischar *	X509_gmtime (char *s, long adj);
91555714Skrisint	X509_add_cert_dir (CERTIFICATE_CTX *c,char *dir, int type);
91655714Skrisint	X509_load_verify_locations (CERTIFICATE_CTX *ctx,
91755714Skris		char *file_env, char *dir_env);
91855714Skrisint	X509_set_default_verify_paths(CERTIFICATE_CTX *cts);
91955714SkrisX509 *	X509_new_D2i_X509(int len, unsigned char *p);
92055714Skrischar *	X509_get_default_cert_area(void );
92155714Skrischar *	X509_get_default_cert_dir(void );
92255714Skrischar *	X509_get_default_cert_file(void );
92355714Skrischar *	X509_get_default_cert_dir_env(void );
92455714Skrischar *	X509_get_default_cert_file_env(void );
92555714Skrischar *	X509_get_default_private_dir(void );
92655714SkrisX509_REQ *X509_X509_TO_req(X509 *x, RSA *rsa);
92755714Skrisint	X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)()); 
92855714Skris
92955714SkrisCERTIFICATE_CTX *CERTIFICATE_CTX_new();
93055714Skrisvoid CERTIFICATE_CTX_free(CERTIFICATE_CTX *c);
93155714Skris
93255714Skrisvoid X509_NAME_print(BIO *fp, X509_NAME *name, int obase);
93355714Skrisint		X509_print_fp(FILE *fp,X509 *x);
93455714Skrisint		X509_print(BIO *fp,X509 *x);
93555714Skris
93655714SkrisX509_INFO *	X509_INFO_new(void);
93755714Skrisvoid		X509_INFO_free(X509_INFO *a);
93855714Skris
93955714Skrischar *		X509_NAME_oneline(X509_NAME *a);
94055714Skris
94155714Skris#define X509_verify(x,rsa)
94255714Skris#define X509_REQ_verify(x,rsa)
94355714Skris#define X509_CRL_verify(x,rsa)
94455714Skris
94555714Skris#define X509_sign(x,rsa,md)
94655714Skris#define X509_REQ_sign(x,rsa,md)
94755714Skris#define X509_CRL_sign(x,rsa,md)
94855714Skris
94955714Skris#define X509_dup(x509)
95055714Skris#define d2i_X509_fp(fp,x509)
95155714Skris#define i2d_X509_fp(fp,x509)
95255714Skris#define d2i_X509_bio(bp,x509)
95355714Skris#define i2d_X509_bio(bp,x509)
95455714Skris
95555714Skris#define X509_CRL_dup(crl)
95655714Skris#define d2i_X509_CRL_fp(fp,crl)
95755714Skris#define i2d_X509_CRL_fp(fp,crl)
95855714Skris#define d2i_X509_CRL_bio(bp,crl)
95955714Skris#define i2d_X509_CRL_bio(bp,crl)
96055714Skris
96155714Skris#define X509_REQ_dup(req)
96255714Skris#define d2i_X509_REQ_fp(fp,req)
96355714Skris#define i2d_X509_REQ_fp(fp,req)
96455714Skris#define d2i_X509_REQ_bio(bp,req)
96555714Skris#define i2d_X509_REQ_bio(bp,req)
96655714Skris
96755714Skris#define RSAPrivateKey_dup(rsa)
96855714Skris#define d2i_RSAPrivateKey_fp(fp,rsa)
96955714Skris#define i2d_RSAPrivateKey_fp(fp,rsa)
97055714Skris#define d2i_RSAPrivateKey_bio(bp,rsa)
97155714Skris#define i2d_RSAPrivateKey_bio(bp,rsa)
97255714Skris
97355714Skris#define X509_NAME_dup(xn)
97455714Skris#define X509_NAME_ENTRY_dup(ne)
97555714Skris
97655714Skrisvoid X509_REQ_print_fp(FILE *fp,X509_REQ *req);
97755714Skrisvoid X509_REQ_print(BIO *fp,X509_REQ *req);
97855714Skris
97955714SkrisRSA *X509_REQ_extract_key(X509_REQ *req);
98055714SkrisRSA *X509_extract_key(X509 *x509);
98155714Skris
98255714Skrisint		X509_issuer_and_serial_cmp(X509 *a, X509 *b);
98355714Skrisunsigned long	X509_issuer_and_serial_hash(X509 *a);
98455714Skris
98555714SkrisX509_NAME *	X509_get_issuer_name(X509 *a);
98655714Skrisint		X509_issuer_name_cmp(X509 *a, X509 *b);
98755714Skrisunsigned long	X509_issuer_name_hash(X509 *a);
98855714Skris
98955714SkrisX509_NAME *	X509_get_subject_name(X509 *a);
99055714Skrisint		X509_subject_name_cmp(X509 *a,X509 *b);
99155714Skrisunsigned long	X509_subject_name_hash(X509 *x);
99255714Skris
99355714Skrisint		X509_NAME_cmp (X509_NAME *a, X509_NAME *b);
99455714Skrisunsigned long	X509_NAME_hash(X509_NAME *x);
99555714Skris
99655714Skris
99755714Skris==== bio.doc ========================================================
99855714Skris
99955714SkrisBIO Routines
100055714Skris
100155714SkrisThis documentation is rather sparse, you are probably best 
100255714Skrisoff looking at the code for specific details.
100355714Skris
100455714SkrisThe BIO library is a IO abstraction that was originally 
100555714Skrisinspired by the need to have callbacks to perform IO to FILE 
100655714Skrispointers when using Windows 3.1 DLLs.  There are two types 
100755714Skrisof BIO; a source/sink type and a filter type.
100855714SkrisThe source/sink methods are as follows:
100955714Skris-	BIO_s_mem()  memory buffer - a read/write byte array that
101055714Skris	grows until memory runs out :-).
101155714Skris-	BIO_s_file()  FILE pointer - A wrapper around the normal 
101255714Skris	'FILE *' commands, good for use with stdin/stdout.
101355714Skris-	BIO_s_fd()  File descriptor - A wrapper around file 
101455714Skris	descriptors, often used with pipes.
101555714Skris-	BIO_s_socket()  Socket - Used around sockets.  It is 
101655714Skris	mostly in the Microsoft world that sockets are different 
101755714Skris	from file descriptors and there are all those ugly winsock 
101855714Skris	commands.
101955714Skris-	BIO_s_null()  Null - read nothing and write nothing.; a 
102055714Skris	useful endpoint for filter type BIO's specifically things 
102155714Skris	like the message digest BIO.
102255714Skris
102355714SkrisThe filter types are
102455714Skris-	BIO_f_buffer()  IO buffering - does output buffering into 
102555714Skris	larger chunks and performs input buffering to allow gets() 
102655714Skris	type functions.
102755714Skris-	BIO_f_md()  Message digest - a transparent filter that can 
102855714Skris	be asked to return a message digest for the data that has 
102955714Skris	passed through it.
103055714Skris-	BIO_f_cipher()  Encrypt or decrypt all data passing 
103155714Skris	through the filter.
103255714Skris-	BIO_f_base64()  Base64 decode on read and encode on write.
103355714Skris-	BIO_f_ssl()  A filter that performs SSL encryption on the 
103455714Skris	data sent through it.
103555714Skris
103655714SkrisBase BIO functions.
103755714SkrisThe BIO library has a set of base functions that are 
103855714Skrisimplemented for each particular type.  Filter BIOs will 
103955714Skrisnormally call the equivalent function on the source/sink BIO 
104055714Skristhat they are layered on top of after they have performed 
104155714Skrissome modification to the data stream.  Multiple filter BIOs 
104255714Skriscan be 'push' into a stack of modifers, so to read from a 
104355714Skrisfile, unbase64 it, then decrypt it, a BIO_f_cipher, 
104455714SkrisBIO_f_base64 and a BIO_s_file would probably be used.  If a 
104555714Skrissha-1 and md5 message digest needed to be generated, a stack 
104655714Skristwo BIO_f_md() BIOs and a BIO_s_null() BIO could be used.
104755714SkrisThe base functions are
104855714Skris-	BIO *BIO_new(BIO_METHOD *type); Create  a new BIO of  type 'type'.
104955714Skris-	int BIO_free(BIO *a); Free a BIO structure.  Depending on 
105055714Skris	the configuration, this will free the underlying data 
105155714Skris	object for a source/sink BIO.
105255714Skris-	int BIO_read(BIO *b, char *data, int len); Read upto 'len' 
105355714Skris	bytes into 'data'. 
105455714Skris-	int BIO_gets(BIO *bp,char *buf, int size); Depending on 
105555714Skris	the BIO, this can either be a 'get special' or a get one 
105655714Skris	line of data, as per fgets();
105755714Skris-	int BIO_write(BIO *b, char *data, int len); Write 'len' 
105855714Skris	bytes from 'data' to the 'b' BIO.
105955714Skris-	int BIO_puts(BIO *bp,char *buf); Either a 'put special' or 
106055714Skris	a write null terminated string as per fputs().
106155714Skris-	long BIO_ctrl(BIO *bp,int cmd,long larg,char *parg);  A 
106255714Skris	control function which is used to manipulate the BIO 
106355714Skris	structure and modify it's state and or report on it.  This 
106455714Skris	function is just about never used directly, rather it 
106555714Skris	should be used in conjunction with BIO_METHOD specific 
106655714Skris	macros.
106755714Skris-	BIO *BIO_push(BIO *new_top, BIO *old); new_top is apped to the
106855714Skris	top of the 'old' BIO list.  new_top should be a filter BIO.
106955714Skris	All writes will go through 'new_top' first and last on read.
107055714Skris	'old' is returned.
107155714Skris-	BIO *BIO_pop(BIO *bio); the new topmost BIO is returned, NULL if
107255714Skris	there are no more.
107355714Skris
107455714SkrisIf a particular low level BIO method is not supported 
107555714Skris(normally BIO_gets()), -2 will be returned if that method is 
107655714Skriscalled.  Otherwise the IO methods (read, write, gets, puts) 
107755714Skriswill return the number of bytes read or written, and 0 or -1 
107855714Skrisfor error (or end of input).  For the -1 case, 
107955714SkrisBIO_should_retry(bio) can be called to determine if it was a 
108055714Skrisgenuine error or a temporary problem.  -2 will also be 
108155714Skrisreturned if the BIO has not been initalised yet, in all 
108255714Skriscases, the correct error codes are set (accessible via the 
108355714SkrisERR library).
108455714Skris
108555714Skris
108655714SkrisThe following functions are convenience functions:
108755714Skris-	int BIO_printf(BIO *bio, char * format, ..);  printf but 
108855714Skris	to a BIO handle.
108955714Skris-	long BIO_ctrl_int(BIO *bp,int cmd,long larg,int iarg); a 
109055714Skris	convenience function to allow a different argument types 
109155714Skris	to be passed to BIO_ctrl().
109255714Skris-	int BIO_dump(BIO *b,char *bytes,int len); output 'len' 
109355714Skris	bytes from 'bytes' in a hex dump debug format.
109455714Skris-	long BIO_debug_callback(BIO *bio, int cmd, char *argp, int 
109555714Skris	argi, long argl, long ret) - a default debug BIO callback, 
109655714Skris	this is mentioned below.  To use this one normally has to 
109755714Skris	use the BIO_set_callback_arg() function to assign an 
109855714Skris	output BIO for the callback to use.
109955714Skris-	BIO *BIO_find_type(BIO *bio,int type); when there is a 'stack'
110055714Skris	of BIOs, this function scan the list and returns the first
110155714Skris	that is of type 'type', as listed in buffer.h under BIO_TYPE_XXX.
110255714Skris-	void BIO_free_all(BIO *bio); Free the bio and all other BIOs
110355714Skris	in the list.  It walks the bio->next_bio list.
110455714Skris
110555714Skris
110655714Skris
110755714SkrisExtra commands are normally implemented as macros calling BIO_ctrl().
110855714Skris-	BIO_number_read(BIO *bio) - the number of bytes processed 
110955714Skris	by BIO_read(bio,.).
111055714Skris-	BIO_number_written(BIO *bio) - the number of bytes written 
111155714Skris	by BIO_write(bio,.).
111255714Skris-	BIO_reset(BIO *bio) - 'reset' the BIO.
111355714Skris-	BIO_eof(BIO *bio) - non zero if we are at the current end 
111455714Skris	of input.
111555714Skris-	BIO_set_close(BIO *bio, int close_flag) - set the close flag.
111655714Skris-	BIO_get_close(BIO *bio) - return the close flag.
111755714Skris	BIO_pending(BIO *bio) - return the number of bytes waiting 
111855714Skris	to be read (normally buffered internally).
111955714Skris-	BIO_flush(BIO *bio) - output any data waiting to be output.
112055714Skris-	BIO_should_retry(BIO *io) - after a BIO_read/BIO_write 
112155714Skris	operation returns 0 or -1, a call to this function will 
112255714Skris	return non zero if you should retry the call later (this 
112355714Skris	is for non-blocking IO).
112455714Skris-	BIO_should_read(BIO *io) - we should retry when data can 
112555714Skris	be read.
112655714Skris-	BIO_should_write(BIO *io) - we should retry when data can 
112755714Skris	be written.
112855714Skris-	BIO_method_name(BIO *io) - return a string for the method name.
112955714Skris-	BIO_method_type(BIO *io) - return the unique ID of the BIO method.
113055714Skris-	BIO_set_callback(BIO *io,  long (*callback)(BIO *io, int 
113155714Skris	cmd, char *argp, int argi, long argl, long ret); - sets 
113255714Skris	the debug callback.
113355714Skris-	BIO_get_callback(BIO *io) - return the assigned function 
113455714Skris	as mentioned above.
113555714Skris-	BIO_set_callback_arg(BIO *io, char *arg)  - assign some 
113655714Skris	data against the BIO.  This is normally used by the debug 
113755714Skris	callback but could in reality be used for anything.  To 
113855714Skris	get an idea of how all this works, have a look at the code 
113955714Skris	in the default debug callback mentioned above.  The 
114055714Skris	callback can modify the return values.
114155714Skris
114255714SkrisDetails of the BIO_METHOD structure.
114355714Skristypedef struct bio_method_st
114455714Skris        {
114555714Skris	int type;
114655714Skris	char *name;
114755714Skris	int (*bwrite)();
114855714Skris	int (*bread)();
114955714Skris	int (*bputs)();
115055714Skris	int (*bgets)();
115155714Skris	long (*ctrl)();
115255714Skris	int (*create)();
115355714Skris	int (*destroy)();
115455714Skris	} BIO_METHOD;
115555714Skris
115655714SkrisThe 'type' is the numeric type of the BIO, these are listed in buffer.h;
115755714Skris'Name' is a textual representation of the BIO 'type'.
115855714SkrisThe 7 function pointers point to the respective function 
115955714Skrismethods, some of which can be NULL if not implemented.
116055714SkrisThe BIO structure
116155714Skristypedef struct bio_st
116255714Skris	{
116355714Skris	BIO_METHOD *method;
116455714Skris	long (*callback)(BIO * bio, int mode, char *argp, int 
116555714Skris		argi, long argl, long ret);
116655714Skris	char *cb_arg; /* first argument for the callback */
116755714Skris	int init;
116855714Skris	int shutdown;
116955714Skris	int flags;      /* extra storage */
117055714Skris	int num;
117155714Skris	char *ptr;
117255714Skris	struct bio_st *next_bio; /* used by filter BIOs */
117355714Skris	int references;
117455714Skris	unsigned long num_read;
117555714Skris	unsigned long num_write;
117655714Skris	} BIO;
117755714Skris
117855714Skris-	'Method' is the BIO method.
117955714Skris-	'callback', when configured, is called before and after 
118055714Skris	each BIO method is called for that particular BIO.  This 
118155714Skris	is intended primarily for debugging and of informational feedback.
118255714Skris-	'init' is 0 when the BIO can be used for operation.  
118355714Skris	Often, after a BIO is created, a number of operations may 
118455714Skris	need to be performed before it is available for use.  An 
118555714Skris	example is for BIO_s_sock().  A socket needs to be 
118655714Skris	assigned to the BIO before it can be used.
118755714Skris-	'shutdown', this flag indicates if the underlying 
1188238405Sjkim	communication primitive being used should be closed/freed 
118955714Skris	when the BIO is closed.
119055714Skris-	'flags' is used to hold extra state.  It is primarily used 
119155714Skris	to hold information about why a non-blocking operation 
119255714Skris	failed and to record startup protocol information for the 
119355714Skris	SSL BIO.
119455714Skris-	'num' and 'ptr' are used to hold instance specific state 
119555714Skris	like file descriptors or local data structures.
119655714Skris-	'next_bio' is used by filter BIOs to hold the pointer of the
119755714Skris	next BIO in the chain. written data is sent to this BIO and
119855714Skris	data read is taken from it.
119955714Skris-	'references' is used to indicate the number of pointers to 
120055714Skris	this structure.  This needs to be '1' before a call to 
120155714Skris	BIO_free() is made if the BIO_free() function is to 
120255714Skris	actually free() the structure, otherwise the reference 
120355714Skris	count is just decreased.  The actual BIO subsystem does 
120455714Skris	not really use this functionality but it is useful when 
120555714Skris	used in more advanced applicaion.
120655714Skris-	num_read and num_write are the total number of bytes 
120755714Skris	read/written via the 'read()' and 'write()' methods.
120855714Skris
120955714SkrisBIO_ctrl operations.
121055714SkrisThe following is the list of standard commands passed as the 
121155714Skrissecond parameter to BIO_ctrl() and should be supported by 
121255714Skrisall BIO as best as possible.  Some are optional, some are 
121355714Skrismanditory, in any case, where is makes sense, a filter BIO 
121455714Skrisshould pass such requests to underlying BIO's.
121555714Skris-	BIO_CTRL_RESET	- Reset the BIO back to an initial state.
121655714Skris-	BIO_CTRL_EOF	- return 0 if we are not at the end of input, 
121755714Skris	non 0 if we are.
121855714Skris-	BIO_CTRL_INFO	- BIO specific special command, normal
121955714Skris	information return.
122055714Skris-	BIO_CTRL_SET	- set IO specific parameter.
122155714Skris-	BIO_CTRL_GET	- get IO specific parameter.
122255714Skris-	BIO_CTRL_GET_CLOSE - Get the close on BIO_free() flag, one 
122355714Skris	of BIO_CLOSE or BIO_NOCLOSE.
122455714Skris-	BIO_CTRL_SET_CLOSE - Set the close on BIO_free() flag.
122555714Skris-	BIO_CTRL_PENDING - Return the number of bytes available 
122655714Skris	for instant reading
122755714Skris-	BIO_CTRL_FLUSH	- Output pending data, return number of bytes output.
122855714Skris-	BIO_CTRL_SHOULD_RETRY - After an IO error (-1 returned) 
122955714Skris	should we 'retry' when IO is possible on the underlying IO object.
123055714Skris-	BIO_CTRL_RETRY_TYPE - What kind of IO are we waiting on.
123155714Skris
123255714SkrisThe following command is a special BIO_s_file() specific option.
123355714Skris-	BIO_CTRL_SET_FILENAME - specify a file to open for IO.
123455714Skris
123555714SkrisThe BIO_CTRL_RETRY_TYPE needs a little more explanation.  
123655714SkrisWhen performing non-blocking IO, or say reading on a memory 
123755714SkrisBIO, when no data is present (or cannot be written), 
123855714SkrisBIO_read() and/or BIO_write() will return -1.  
123955714SkrisBIO_should_retry(bio) will return true if this is due to an 
124055714SkrisIO condition rather than an actual error.  In the case of 
124155714SkrisBIO_s_mem(), a read when there is no data will return -1 and 
124255714Skrisa should retry when there is more 'read' data.
124355714SkrisThe retry type is deduced from 2 macros
124455714SkrisBIO_should_read(bio) and BIO_should_write(bio).
124555714SkrisNow while it may appear obvious that a BIO_read() failure 
124655714Skrisshould indicate that a retry should be performed when more 
124755714Skrisread data is available, this is often not true when using 
124855714Skristhings like an SSL BIO.  During the SSL protocol startup 
124955714Skrismultiple reads and writes are performed, triggered by any 
125055714SkrisSSL_read or SSL_write.
125155714SkrisSo to write code that will transparently handle either a 
125255714Skrissocket or SSL BIO,
125355714Skris	i=BIO_read(bio,..)
125455714Skris	if (I == -1)
125555714Skris		{
125655714Skris		if (BIO_should_retry(bio))
125755714Skris			{
125855714Skris			if (BIO_should_read(bio))
125955714Skris				{
126055714Skris				/* call us again when BIO can be read */
126155714Skris				}
126255714Skris			if (BIO_should_write(bio))
126355714Skris				{
126455714Skris				/* call us again when BIO can be written */
126555714Skris				}
126655714Skris			}
126755714Skris		}
126855714Skris
126955714SkrisAt this point in time only read and write conditions can be 
127055714Skrisused but in the future I can see the situation for other 
127155714Skrisconditions, specifically with SSL there could be a condition 
127255714Skrisof a X509 certificate lookup taking place and so the non-
127355714Skrisblocking BIO_read would require a retry when the certificate 
127455714Skrislookup subsystem has finished it's lookup.  This is all 
127555714Skrismakes more sense and is easy to use in a event loop type 
127655714Skrissetup.
127755714SkrisWhen using the SSL BIO, either SSL_read() or SSL_write()s 
127855714Skriscan be called during the protocol startup and things will 
127955714Skrisstill work correctly.
128055714SkrisThe nice aspect of the use of the BIO_should_retry() macro 
128155714Skrisis that all the errno codes that indicate a non-fatal error 
128255714Skrisare encapsulated in one place.  The Windows specific error 
128355714Skriscodes and WSAGetLastError() calls are also hidden from the 
128455714Skrisapplication.
128555714Skris
128655714SkrisNotes on each BIO method.
128755714SkrisNormally buffer.h is just required but depending on the 
128855714SkrisBIO_METHOD, ssl.h or evp.h will also be required.
128955714Skris
129055714SkrisBIO_METHOD *BIO_s_mem(void);
129155714Skris-	BIO_set_mem_buf(BIO *bio, BUF_MEM *bm, int close_flag) - 
129255714Skris	set the underlying BUF_MEM structure for the BIO to use.
129355714Skris-	BIO_get_mem_ptr(BIO *bio, char **pp) - if pp is not NULL, 
129455714Skris	set it to point to the memory array and return the number 
129555714Skris	of bytes available.
129655714SkrisA read/write BIO.  Any data written is appended to the 
129755714Skrismemory array and any read is read from the front.  This BIO 
129855714Skriscan be used for read/write at the same time. BIO_gets() is 
129955714Skrissupported in the fgets() sense.
130055714SkrisBIO_CTRL_INFO can be used to retrieve pointers to the memory 
130155714Skrisbuffer and it's length.
130255714Skris
130355714SkrisBIO_METHOD *BIO_s_file(void);
130455714Skris-	BIO_set_fp(BIO *bio, FILE *fp, int close_flag) - set 'FILE *' to use.
130555714Skris-	BIO_get_fp(BIO *bio, FILE **fp) - get the 'FILE *' in use.
130655714Skris-	BIO_read_filename(BIO *bio, char *name) - read from file.
130755714Skris-	BIO_write_filename(BIO *bio, char *name) - write to file.
130855714Skris-	BIO_append_filename(BIO *bio, char *name) - append to file.
130955714SkrisThis BIO sits over the normal system fread()/fgets() type 
131055714Skrisfunctions. Gets() is supported.  This BIO in theory could be 
131155714Skrisused for read and write but it is best to think of each BIO 
131255714Skrisof this type as either a read or a write BIO, not both.
131355714Skris
131455714SkrisBIO_METHOD *BIO_s_socket(void);
131555714SkrisBIO_METHOD *BIO_s_fd(void);
131655714Skris-	BIO_sock_should_retry(int i) - the underlying function 
131755714Skris	used to determine if a call should be retried; the 
131855714Skris	argument is the '0' or '-1' returned by the previous BIO 
131955714Skris	operation.
132055714Skris-	BIO_fd_should_retry(int i) - same as the 
132155714Skris-	BIO_sock_should_retry() except that it is different internally.
132255714Skris-	BIO_set_fd(BIO *bio, int fd, int close_flag) - set the 
132355714Skris	file descriptor to use
132455714Skris-	BIO_get_fd(BIO *bio, int *fd) - get the file descriptor.
132555714SkrisThese two methods are very similar.  Gets() is not 
132655714Skrissupported, if you want this functionality, put a 
132755714SkrisBIO_f_buffer() onto it.  This BIO is bi-directional if the 
132855714Skrisunderlying file descriptor is.  This is normally the case 
132955714Skrisfor sockets but not the case for stdio descriptors.
133055714Skris
133155714SkrisBIO_METHOD *BIO_s_null(void);
133255714SkrisRead and write as much data as you like, it all disappears 
133355714Skrisinto this BIO.
133455714Skris
133555714SkrisBIO_METHOD *BIO_f_buffer(void);
133655714Skris-	BIO_get_buffer_num_lines(BIO *bio) - return the number of 
133755714Skris	complete lines in the buffer.
133855714Skris-	BIO_set_buffer_size(BIO *bio, long size) - set the size of 
133955714Skris	the buffers.
134055714SkrisThis type performs input and output buffering.  It performs 
134155714Skrisboth at the same time.  The size of the buffer can be set 
134255714Skrisvia the set buffer size option.  Data buffered for output is 
134355714Skrisonly written when the buffer fills.
134455714Skris
134555714SkrisBIO_METHOD *BIO_f_ssl(void);
134655714Skris-	BIO_set_ssl(BIO *bio, SSL *ssl, int close_flag) - the SSL 
134755714Skris	structure to use.
134855714Skris-	BIO_get_ssl(BIO *bio, SSL **ssl) - get the SSL structure 
134955714Skris	in use.
135055714SkrisThe SSL bio is a little different from normal BIOs because 
135155714Skristhe underlying SSL structure is a little different.  A SSL 
135255714Skrisstructure performs IO via a read and write BIO.  These can 
135355714Skrisbe different and are normally set via the
135455714SkrisSSL_set_rbio()/SSL_set_wbio() calls.  The SSL_set_fd() calls 
135555714Skrisare just wrappers that create socket BIOs and then call 
135655714SkrisSSL_set_bio() where the read and write BIOs are the same.  
135755714SkrisThe BIO_push() operation makes the SSLs IO BIOs the same, so 
135855714Skrismake sure the BIO pushed is capable of two directional 
135955714Skristraffic.  If it is not, you will have to install the BIOs 
136055714Skrisvia the more conventional SSL_set_bio() call.  BIO_pop() will retrieve
136155714Skristhe 'SSL read' BIO.
136255714Skris
136355714SkrisBIO_METHOD *BIO_f_md(void);
136455714Skris-	BIO_set_md(BIO *bio, EVP_MD *md) - set the message digest 
136555714Skris	to use.
136655714Skris-	BIO_get_md(BIO *bio, EVP_MD **mdp) - return the digest 
136755714Skris	method in use in mdp, return 0 if not set yet.
136855714Skris-	BIO_reset() reinitializes the digest (EVP_DigestInit()) 
136955714Skris	and passes the reset to the underlying BIOs.
137055714SkrisAll data read or written via BIO_read() or BIO_write() to 
137155714Skristhis BIO will be added to the calculated digest.  This 
137255714Skrisimplies that this BIO is only one directional.  If read and 
137355714Skriswrite operations are performed, two separate BIO_f_md() BIOs 
137455714Skrisare reuqired to generate digests on both the input and the 
137555714Skrisoutput.  BIO_gets(BIO *bio, char *md, int size) will place the 
137655714Skrisgenerated digest into 'md' and return the number of bytes.  
137755714SkrisThe EVP_MAX_MD_SIZE should probably be used to size the 'md' 
137855714Skrisarray.  Reading the digest will also reset it.
137955714Skris
138055714SkrisBIO_METHOD *BIO_f_cipher(void);
138155714Skris-	BIO_reset() reinitializes the cipher.
138255714Skris-	BIO_flush() should be called when the last bytes have been 
138355714Skris	output to flush the final block of block ciphers.
138455714Skris-	BIO_get_cipher_status(BIO *b), when called after the last 
138555714Skris	read from a cipher BIO, returns non-zero if the data 
138655714Skris	decrypted correctly, otherwise, 0.
138755714Skris-	BIO_set_cipher(BIO *b, EVP_CIPHER *c, unsigned char *key, 
138855714Skris	unsigned char *iv, int encrypt)   This function is used to 
138955714Skris	setup a cipher BIO.  The length of key and iv are 
139055714Skris	specified by the choice of EVP_CIPHER.  Encrypt is 1 to 
139155714Skris	encrypt and 0 to decrypt.
139255714Skris
139355714SkrisBIO_METHOD *BIO_f_base64(void);
139455714Skris-	BIO_flush() should be called when the last bytes have been output.
139555714SkrisThis BIO base64 encodes when writing and base64 decodes when 
139655714Skrisreading.  It will scan the input until a suitable begin line 
139755714Skrisis found.  After reading data, BIO_reset() will reset the 
139855714SkrisBIO to start scanning again.  Do not mix reading and writing 
139955714Skrison the same base64 BIO.  It is meant as a single stream BIO.
140055714Skris
140155714SkrisDirections	type
140255714Skrisboth		BIO_s_mem()
140355714Skrisone/both	BIO_s_file()
140455714Skrisboth		BIO_s_fd()
140555714Skrisboth		BIO_s_socket() 
140655714Skrisboth		BIO_s_null()
140755714Skrisboth		BIO_f_buffer()
140855714Skrisone		BIO_f_md()  
140955714Skrisone		BIO_f_cipher()  
141055714Skrisone		BIO_f_base64()  
141155714Skrisboth		BIO_f_ssl()
141255714Skris
141355714SkrisIt is easy to mix one and two directional BIOs, all one has 
141455714Skristo do is to keep two separate BIO pointers for reading and 
141555714Skriswriting and be careful about usage of underlying BIOs.  The 
141655714SkrisSSL bio by it's very nature has to be two directional but 
141755714Skristhe BIO_push() command will push the one BIO into the SSL 
141855714SkrisBIO for both reading and writing.
141955714Skris
142055714SkrisThe best example program to look at is apps/enc.c and/or perhaps apps/dgst.c.
142155714Skris
142255714Skris
142355714Skris==== blowfish.doc ========================================================
142455714Skris
142555714SkrisThe Blowfish library.
142655714Skris
142755714SkrisBlowfish is a block cipher that operates on 64bit (8 byte) quantities.  It
142855714Skrisuses variable size key, but 128bit (16 byte) key would normally be considered
142955714Skrisgood.  It can be used in all the modes that DES can be used.  This
143055714Skrislibrary implements the ecb, cbc, cfb64, ofb64 modes.
143155714Skris
143255714SkrisBlowfish is quite a bit faster that DES, and much faster than IDEA or
143355714SkrisRC2.  It is one of the faster block ciphers.
143455714Skris
143555714SkrisFor all calls that have an 'input' and 'output' variables, they can be the
143655714Skrissame.
143755714Skris
143855714SkrisThis library requires the inclusion of 'blowfish.h'.
143955714Skris
144055714SkrisAll of the encryption functions take what is called an BF_KEY as an 
144155714Skrisargument.  An BF_KEY is an expanded form of the Blowfish key.
144255714SkrisFor all modes of the Blowfish algorithm, the BF_KEY used for
144355714Skrisdecryption is the same one that was used for encryption.
144455714Skris
144555714SkrisThe define BF_ENCRYPT is passed to specify encryption for the functions
144655714Skristhat require an encryption/decryption flag. BF_DECRYPT is passed to
144755714Skrisspecify decryption.
144855714Skris
144955714SkrisPlease note that any of the encryption modes specified in my DES library
145055714Skriscould be used with Blowfish.  I have only implemented ecb, cbc, cfb64 and
145155714Skrisofb64 for the following reasons.
145255714Skris- ecb is the basic Blowfish encryption.
145355714Skris- cbc is the normal 'chaining' form for block ciphers.
145455714Skris- cfb64 can be used to encrypt single characters, therefore input and output
145555714Skris  do not need to be a multiple of 8.
145655714Skris- ofb64 is similar to cfb64 but is more like a stream cipher, not as
145755714Skris  secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
145855714Skris- If you want triple Blowfish, thats 384 bits of key and you must be totally
145955714Skris  obsessed with security.  Still, if you want it, it is simple enough to
146055714Skris  copy the function from the DES library and change the des_encrypt to
146155714Skris  BF_encrypt; an exercise left for the paranoid reader :-).
146255714Skris
146355714SkrisThe functions are as follows:
146455714Skris
146555714Skrisvoid BF_set_key(
146655714SkrisBF_KEY *ks;
146755714Skrisint len;
146855714Skrisunsigned char *key;
146955714Skris        BF_set_key converts an 'len' byte key into a BF_KEY.
147055714Skris        A 'ks' is an expanded form of the 'key' which is used to
147155714Skris        perform actual encryption.  It can be regenerated from the Blowfish key
147255714Skris        so it only needs to be kept when encryption or decryption is about
147355714Skris        to occur.  Don't save or pass around BF_KEY's since they
147455714Skris        are CPU architecture dependent, 'key's are not.  Blowfish is an
147555714Skris	interesting cipher in that it can be used with a variable length
147655714Skris	key.  'len' is the length of 'key' to be used as the key.
147755714Skris	A 'len' of 16 is recomended by me, but blowfish can use upto
147855714Skris	72 bytes.  As a warning, blowfish has a very very slow set_key
147955714Skris	function, it actually runs BF_encrypt 521 times.
148055714Skris	
148155714Skrisvoid BF_encrypt(unsigned long *data, BF_KEY *key);
148255714Skrisvoid BF_decrypt(unsigned long *data, BF_KEY *key);
148355714Skris	These are the Blowfish encryption function that gets called by just
148455714Skris	about every other Blowfish routine in the library.  You should not
148555714Skris	use this function except to implement 'modes' of Blowfish.
148655714Skris	I say this because the
148755714Skris	functions that call this routine do the conversion from 'char *' to
148855714Skris	long, and this needs to be done to make sure 'non-aligned' memory
148955714Skris	access do not occur.
149055714Skris	Data is a pointer to 2 unsigned long's and key is the
149155714Skris	BF_KEY to use. 
149255714Skris
149355714Skrisvoid BF_ecb_encrypt(
149455714Skrisunsigned char *in,
149555714Skrisunsigned char *out,
149655714SkrisBF_KEY *key,
149755714Skrisint encrypt);
149855714Skris	This is the basic Electronic Code Book form of Blowfish (in DES this
149955714Skris	mode is called Electronic Code Book so I'm going to use the term
150055714Skris	for blowfish as well.
150155714Skris	Input is encrypted into output using the key represented by
150255714Skris	key.  Depending on the encrypt, encryption or
150355714Skris	decryption occurs.  Input is 8 bytes long and output is 8 bytes.
150455714Skris	
150555714Skrisvoid BF_cbc_encrypt(
150655714Skrisunsigned char *in,
150755714Skrisunsigned char *out,
150855714Skrislong length,
150955714SkrisBF_KEY *ks,
151055714Skrisunsigned char *ivec,
151155714Skrisint encrypt);
151255714Skris	This routine implements Blowfish in Cipher Block Chaining mode.
151355714Skris	Input, which should be a multiple of 8 bytes is encrypted
151455714Skris	(or decrypted) to output which will also be a multiple of 8 bytes.
151555714Skris	The number of bytes is in length (and from what I've said above,
151655714Skris	should be a multiple of 8).  If length is not a multiple of 8, bad 
151755714Skris	things will probably happen.  ivec is the initialisation vector.
151855714Skris	This function updates iv after each call so that it can be passed to
151955714Skris	the next call to BF_cbc_encrypt().
152055714Skris	
152155714Skrisvoid BF_cfb64_encrypt(
152255714Skrisunsigned char *in,
152355714Skrisunsigned char *out,
152455714Skrislong length,
152555714SkrisBF_KEY *schedule,
152655714Skrisunsigned char *ivec,
152755714Skrisint *num,
152855714Skrisint encrypt);
152955714Skris	This is one of the more useful functions in this Blowfish library, it
153055714Skris	implements CFB mode of Blowfish with 64bit feedback.
153155714Skris	This allows you to encrypt an arbitrary number of bytes,
153255714Skris	you do not require 8 byte padding.  Each call to this
153355714Skris	routine will encrypt the input bytes to output and then update ivec
153455714Skris	and num.  Num contains 'how far' we are though ivec.
153555714Skris	'Encrypt' is used to indicate encryption or decryption.
153655714Skris	CFB64 mode operates by using the cipher to generate a stream
153755714Skris	of bytes which is used to encrypt the plain text.
153855714Skris	The cipher text is then encrypted to generate the next 64 bits to
153955714Skris	be xored (incrementally) with the next 64 bits of plain
154055714Skris	text.  As can be seen from this, to encrypt or decrypt,
154155714Skris	the same 'cipher stream' needs to be generated but the way the next
154255714Skris	block of data is gathered for encryption is different for
154355714Skris	encryption and decryption.
154455714Skris	
154555714Skrisvoid BF_ofb64_encrypt(
154655714Skrisunsigned char *in,
154755714Skrisunsigned char *out,
154855714Skrislong length,
154955714SkrisBF_KEY *schedule,
155055714Skrisunsigned char *ivec,
155155714Skrisint *num);
155255714Skris	This functions implements OFB mode of Blowfish with 64bit feedback.
155355714Skris	This allows you to encrypt an arbitrary number of bytes,
155455714Skris	you do not require 8 byte padding.  Each call to this
155555714Skris	routine will encrypt the input bytes to output and then update ivec
155655714Skris	and num.  Num contains 'how far' we are though ivec.
155755714Skris	This is in effect a stream cipher, there is no encryption or
155855714Skris	decryption mode.
155955714Skris	
156055714SkrisFor reading passwords, I suggest using des_read_pw_string() from my DES library.
156155714SkrisTo generate a password from a text string, I suggest using MD5 (or MD2) to
156255714Skrisproduce a 16 byte message digest that can then be passed directly to
156355714SkrisBF_set_key().
156455714Skris
156555714Skris=====
156655714SkrisFor more information about the specific Blowfish modes in this library
156755714Skris(ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
156855714Skrisdocumentation on my DES library.  What is said about DES is directly
156955714Skrisapplicable for Blowfish.
157055714Skris
157155714Skris
157255714Skris==== bn.doc ========================================================
157355714Skris
157455714SkrisThe Big Number library.
157555714Skris
157655714Skris#include "bn.h" when using this library.
157755714Skris
157855714SkrisThis big number library was written for use in implementing the RSA and DH
157955714Skrispublic key encryption algorithms.  As such, features such as negative
158055714Skrisnumbers have not been extensively tested but they should work as expected.
158155714SkrisThis library uses dynamic memory allocation for storing its data structures
158255714Skrisand so there are no limit on the size of the numbers manipulated by these
158355714Skrisroutines but there is always the requirement to check return codes from
158455714Skrisfunctions just in case a memory allocation error has occurred.
158555714Skris
158655714SkrisThe basic object in this library is a BIGNUM.  It is used to hold a single
158755714Skrislarge integer.  This type should be considered opaque and fields should not
158855714Skrisbe modified or accessed directly.
158955714Skristypedef struct bignum_st
159055714Skris	{
159155714Skris	int top;	/* Index of last used d. */
159255714Skris	BN_ULONG *d;	/* Pointer to an array of 'BITS2' bit chunks. */
159355714Skris	int max;	/* Size of the d array. */
159455714Skris	int neg;
159555714Skris	} BIGNUM;
159655714SkrisThe big number is stored in a malloced array of BN_ULONG's.  A BN_ULONG can
159755714Skrisbe either 16, 32 or 64 bits in size, depending on the 'number of  bits'
159855714Skrisspecified in bn.h. 
159955714SkrisThe 'd' field is this array.  'max' is the size of the 'd' array that has
160055714Skrisbeen allocated.  'top' is the 'last' entry being used, so for a value of 4,
160155714Skrisbn.d[0]=4 and bn.top=1.  'neg' is 1 if the number is negative.
160255714SkrisWhen a BIGNUM is '0', the 'd' field can be NULL and top == 0.
160355714Skris
160455714SkrisVarious routines in this library require the use of 'temporary' BIGNUM
160555714Skrisvariables during their execution.  Due to the use of dynamic memory
160655714Skrisallocation to create BIGNUMs being rather expensive when used in
160755714Skrisconjunction with repeated subroutine calls, the BN_CTX structure is
160855714Skrisused.  This structure contains BN_CTX BIGNUMs.  BN_CTX
160955714Skrisis the maximum number of temporary BIGNUMs any publicly exported 
161055714Skrisfunction will use.
161155714Skris
161255714Skris#define BN_CTX	12
161355714Skristypedef struct bignum_ctx
161455714Skris	{
161555714Skris	int tos;			/* top of stack */
161655714Skris	BIGNUM *bn[BN_CTX];	/* The variables */
161755714Skris	} BN_CTX;
161855714Skris
161955714SkrisThe functions that follow have been grouped according to function.  Most
162055714Skrisarithmetic functions return a result in the first argument, sometimes this
162155714Skrisfirst argument can also be an input parameter, sometimes it cannot.  These
162255714Skrisrestrictions are documented.
162355714Skris
162455714Skrisextern BIGNUM *BN_value_one;
162555714SkrisThere is one variable defined by this library, a BIGNUM which contains the
162655714Skrisnumber 1.  This variable is useful for use in comparisons and assignment.
162755714Skris
162855714SkrisGet Size functions.
162955714Skris
163055714Skrisint BN_num_bits(BIGNUM *a);
163155714Skris	This function returns the size of 'a' in bits.
163255714Skris	
163355714Skrisint BN_num_bytes(BIGNUM *a);
163455714Skris	This function (macro) returns the size of 'a' in bytes.
163555714Skris	For conversion of BIGNUMs to byte streams, this is the number of
163655714Skris	bytes the output string will occupy.  If the output byte
163755714Skris	format specifies that the 'top' bit indicates if the number is
163855714Skris	signed, so an extra '0' byte is required if the top bit on a
163955714Skris	positive number is being written, it is upto the application to
164055714Skris	make this adjustment.  Like I said at the start, I don't
164155714Skris	really support negative numbers :-).
164255714Skris
164355714SkrisCreation/Destruction routines.
164455714Skris
164555714SkrisBIGNUM *BN_new();
164655714Skris	Return a new BIGNUM object.  The number initially has a value of 0.  If
164755714Skris	there is an error, NULL is returned.
164855714Skris	
164955714Skrisvoid	BN_free(BIGNUM *a);
165055714Skris	Free()s a BIGNUM.
165155714Skris	
165255714Skrisvoid	BN_clear(BIGNUM *a);
165355714Skris	Sets 'a' to a value of 0 and also zeros all unused allocated
165455714Skris	memory.  This function is used to clear a variable of 'sensitive'
165555714Skris	data that was held in it.
165655714Skris	
165755714Skrisvoid	BN_clear_free(BIGNUM *a);
165855714Skris	This function zeros the memory used by 'a' and then free()'s it.
165955714Skris	This function should be used to BN_free() BIGNUMS that have held
166055714Skris	sensitive numeric values like RSA private key values.  Both this
166155714Skris	function and BN_clear tend to only be used by RSA and DH routines.
166255714Skris
166355714SkrisBN_CTX *BN_CTX_new(void);
166455714Skris	Returns a new BN_CTX.  NULL on error.
166555714Skris	
166655714Skrisvoid	BN_CTX_free(BN_CTX *c);
166755714Skris	Free a BN_CTX structure.  The BIGNUMs in 'c' are BN_clear_free()ed.
166855714Skris	
166955714SkrisBIGNUM *bn_expand(BIGNUM *b, int bits);
167055714Skris	This is an internal function that should not normally be used.  It
167155714Skris	ensures that 'b' has enough room for a 'bits' bit number.  It is
167255714Skris	mostly used by the various BIGNUM routines.  If there is an error,
167355714Skris	NULL is returned. if not, 'b' is returned.
167455714Skris	
167555714SkrisBIGNUM *BN_copy(BIGNUM *to, BIGNUM *from);
167655714Skris	The 'from' is copied into 'to'.  NULL is returned if there is an
167755714Skris	error, otherwise 'to' is returned.
167855714Skris
167955714SkrisBIGNUM *BN_dup(BIGNUM *a);
168055714Skris	A new BIGNUM is created and returned containing the value of 'a'.
168155714Skris	NULL is returned on error.
168255714Skris
168355714SkrisComparison and Test Functions.
168455714Skris
168555714Skrisint BN_is_zero(BIGNUM *a)
168655714Skris	Return 1 if 'a' is zero, else 0.
168755714Skris
168855714Skrisint BN_is_one(a)
168955714Skris	Return 1 is 'a' is one, else 0.
169055714Skris
169155714Skrisint BN_is_word(a,w)
169255714Skris	Return 1 if 'a' == w, else 0.  'w' is a BN_ULONG.
169355714Skris
169455714Skrisint BN_cmp(BIGNUM *a, BIGNUM *b);
169555714Skris	Return -1 if 'a' is less than 'b', 0 if 'a' and 'b' are the same
169655714Skris	and 1 is 'a' is greater than 'b'.  This is a signed comparison.
169755714Skris	
169855714Skrisint BN_ucmp(BIGNUM *a, BIGNUM *b);
169955714Skris	This function is the same as BN_cmp except that the comparison
170055714Skris	ignores the sign of the numbers.
170155714Skris	
170255714SkrisArithmetic Functions
170355714SkrisFor all of these functions, 0 is returned if there is an error and 1 is
170455714Skrisreturned for success.  The return value should always be checked.  eg.
170555714Skrisif (!BN_add(r,a,b)) goto err;
170655714SkrisUnless explicitly mentioned, the 'return' value can be one of the
170755714Skris'parameters' to the function.
170855714Skris
170955714Skrisint BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b);
171055714Skris	Add 'a' and 'b' and return the result in 'r'.  This is r=a+b.
171155714Skris	
171255714Skrisint BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b);
171355714Skris	Subtract 'a' from 'b' and put the result in 'r'. This is r=a-b.
171455714Skris	
171555714Skrisint BN_lshift(BIGNUM *r, BIGNUM *a, int n);
171655714Skris	Shift 'a' left by 'n' bits.  This is r=a*(2^n).
171755714Skris	
171855714Skrisint BN_lshift1(BIGNUM *r, BIGNUM *a);
171955714Skris	Shift 'a' left by 1 bit.  This form is more efficient than
172055714Skris	BN_lshift(r,a,1).  This is r=a*2.
172155714Skris	
172255714Skrisint BN_rshift(BIGNUM *r, BIGNUM *a, int n);
172355714Skris	Shift 'a' right by 'n' bits.  This is r=int(a/(2^n)).
172455714Skris	
172555714Skrisint BN_rshift1(BIGNUM *r, BIGNUM *a);
172655714Skris	Shift 'a' right by 1 bit.  This form is more efficient than
172755714Skris	BN_rshift(r,a,1).  This is r=int(a/2).
172855714Skris	
172955714Skrisint BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b);
173055714Skris	Multiply a by b and return the result in 'r'. 'r' must not be
173155714Skris	either 'a' or 'b'.  It has to be a different BIGNUM.
173255714Skris	This is r=a*b.
173355714Skris
173455714Skrisint BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
173555714Skris	Multiply a by a and return the result in 'r'. 'r' must not be
173655714Skris	'a'.  This function is alot faster than BN_mul(r,a,a).  This is r=a*a.
173755714Skris
173855714Skrisint BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
173955714Skris	Divide 'm' by 'd' and return the result in 'dv' and the remainder
174055714Skris	in 'rem'.  Either of 'dv' or 'rem' can be NULL in which case that
174155714Skris	value is not returned.  'ctx' needs to be passed as a source of
174255714Skris	temporary BIGNUM variables.
174355714Skris	This is dv=int(m/d), rem=m%d.
174455714Skris	
174555714Skrisint BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
174655714Skris	Find the remainder of 'm' divided by 'd' and return it in 'rem'.
174755714Skris	'ctx' holds the temporary BIGNUMs required by this function.
174855714Skris	This function is more efficient than BN_div(NULL,rem,m,d,ctx);
174955714Skris	This is rem=m%d.
175055714Skris
175155714Skrisint BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *m,BN_CTX *ctx);
175255714Skris	Multiply 'a' by 'b' and return the remainder when divided by 'm'.
175355714Skris	'ctx' holds the temporary BIGNUMs required by this function.
175455714Skris	This is r=(a*b)%m.
175555714Skris
175655714Skrisint BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx);
175755714Skris	Raise 'a' to the 'p' power and return the remainder when divided by
175855714Skris	'm'.  'ctx' holds the temporary BIGNUMs required by this function.
175955714Skris	This is r=(a^p)%m.
176055714Skris
176155714Skrisint BN_reciprocal(BIGNUM *r, BIGNUM *m, BN_CTX *ctx);
176255714Skris	Return the reciprocal of 'm'.  'ctx' holds the temporary variables
176355714Skris	required.  This function returns -1 on error, otherwise it returns
176455714Skris	the number of bits 'r' is shifted left to make 'r' into an integer.
176555714Skris	This number of bits shifted is required in BN_mod_mul_reciprocal().
176655714Skris	This is r=(1/m)<<(BN_num_bits(m)+1).
176755714Skris	
176855714Skrisint BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *x, BIGNUM *y, BIGNUM *m, 
176955714Skris	BIGNUM *i, int nb, BN_CTX *ctx);
177055714Skris	This function is used to perform an efficient BN_mod_mul()
177155714Skris	operation.  If one is going to repeatedly perform BN_mod_mul() with
177255714Skris	the same modulus is worth calculating the reciprocal of the modulus
177355714Skris	and then using this function.  This operation uses the fact that
177455714Skris	a/b == a*r where r is the reciprocal of b.  On modern computers
177555714Skris	multiplication is very fast and big number division is very slow.
177655714Skris	'x' is multiplied by 'y' and then divided by 'm' and the remainder
177755714Skris	is returned.  'i' is the reciprocal of 'm' and 'nb' is the number
177855714Skris	of bits as returned from BN_reciprocal().  Normal usage is as follows.
177955714Skris	bn=BN_reciprocal(i,m);
178055714Skris	for (...)
178155714Skris		{ BN_mod_mul_reciprocal(r,x,y,m,i,bn,ctx); }
178255714Skris	This is r=(x*y)%m.  Internally it is approximately
178355714Skris	r=(x*y)-m*(x*y/m) or r=(x*y)-m*((x*y*i) >> bn)
178455714Skris	This function is used in BN_mod_exp() and BN_is_prime().
178555714Skris
178655714SkrisAssignment Operations
178755714Skris
178855714Skrisint BN_one(BIGNUM *a)
178955714Skris	Set 'a' to hold the value one.
179055714Skris	This is a=1.
179155714Skris	
179255714Skrisint BN_zero(BIGNUM *a)
179355714Skris	Set 'a' to hold the value zero.
179455714Skris	This is a=0.
179555714Skris	
179655714Skrisint BN_set_word(BIGNUM *a, unsigned long w);
179755714Skris	Set 'a' to hold the value of 'w'.  'w' is an unsigned long.
179855714Skris	This is a=w.
179955714Skris
180055714Skrisunsigned long BN_get_word(BIGNUM *a);
180155714Skris	Returns 'a' in an unsigned long.  Not remarkably, often 'a' will
1802238405Sjkim	be bigger than a word, in which case 0xffffffffL is returned.
180355714Skris
180455714SkrisWord Operations
180555714SkrisThese functions are much more efficient that the normal bignum arithmetic
180655714Skrisoperations.
180755714Skris
180855714SkrisBN_ULONG BN_mod_word(BIGNUM *a, unsigned long w);
180955714Skris	Return the remainder of 'a' divided by 'w'.
181055714Skris	This is return(a%w).
181155714Skris	
181255714Skrisint BN_add_word(BIGNUM *a, unsigned long w);
181355714Skris	Add 'w' to 'a'.  This function does not take the sign of 'a' into
181455714Skris	account.  This is a+=w;
181555714Skris	
181655714SkrisBit operations.
181755714Skris
181855714Skrisint BN_is_bit_set(BIGNUM *a, int n);
181955714Skris	This function return 1 if bit 'n' is set in 'a' else 0.
182055714Skris
182155714Skrisint BN_set_bit(BIGNUM *a, int n);
182255714Skris	This function sets bit 'n' to 1 in 'a'. 
182355714Skris	This is a&= ~(1<<n);
182455714Skris
182555714Skrisint BN_clear_bit(BIGNUM *a, int n);
182655714Skris	This function sets bit 'n' to zero in 'a'.  Return 0 if less
182755714Skris	than 'n' bits in 'a' else 1.  This is a&= ~(1<<n);
182855714Skris
182955714Skrisint BN_mask_bits(BIGNUM *a, int n);
183055714Skris	Truncate 'a' to n bits long.  This is a&= ~((~0)<<n)
183155714Skris
183255714SkrisFormat conversion routines.
183355714Skris
183455714SkrisBIGNUM *BN_bin2bn(unsigned char *s, int len,BIGNUM *ret);
183555714Skris	This function converts 'len' bytes in 's' into a BIGNUM which
183655714Skris	is put in 'ret'.  If ret is NULL, a new BIGNUM is created.
183755714Skris	Either this new BIGNUM or ret is returned.  The number is
183855714Skris	assumed to be in bigendian form in 's'.  By this I mean that
183955714Skris	to 'ret' is created as follows for 'len' == 5.
184055714Skris	ret = s[0]*2^32 + s[1]*2^24 + s[2]*2^16 + s[3]*2^8 + s[4];
184155714Skris	This function cannot be used to convert negative numbers.  It
184255714Skris	is always assumed the number is positive.  The application
184355714Skris	needs to diddle the 'neg' field of th BIGNUM its self.
184455714Skris	The better solution would be to save the numbers in ASN.1 format
184555714Skris	since this is a defined standard for storing big numbers.
184655714Skris	Look at the functions
184755714Skris
184855714Skris	ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
184955714Skris	BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
185055714Skris	int i2d_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp);
185155714Skris	ASN1_INTEGER *d2i_ASN1_INTEGER(ASN1_INTEGER **a,unsigned char **pp,
185255714Skris		long length;
185355714Skris
185455714Skrisint BN_bn2bin(BIGNUM *a, unsigned char *to);
185555714Skris	This function converts 'a' to a byte string which is put into
185655714Skris	'to'.  The representation is big-endian in that the most
185755714Skris	significant byte of 'a' is put into to[0].  This function
185855714Skris	returns the number of bytes used to hold 'a'.  BN_num_bytes(a)
185955714Skris	would return the same value and can be used to determine how
186055714Skris	large 'to' needs to be.  If the number is negative, this
186155714Skris	information is lost.  Since this library was written to
186255714Skris	manipulate large positive integers, the inability to save and
186355714Skris	restore them is not considered to be a problem by me :-).
186455714Skris	As for BN_bin2bn(), look at the ASN.1 integer encoding funtions
186555714Skris	for SSLeay.  They use BN_bin2bn() and BN_bn2bin() internally.
186655714Skris	
186755714Skrischar *BN_bn2ascii(BIGNUM *a);
186855714Skris	This function returns a malloc()ed string that contains the
186955714Skris	ascii hexadecimal encoding of 'a'.  The number is in bigendian
187055714Skris	format with a '-' in front if the number is negative.
187155714Skris
187255714Skrisint BN_ascii2bn(BIGNUM **bn, char *a);
187355714Skris	The inverse of BN_bn2ascii.  The function returns the number of
187455714Skris	characters from 'a' were processed in generating a the bignum.
187555714Skris	error is inticated by 0 being returned.  The number is a
187655714Skris	hex digit string, optionally with a leading '-'.  If *bn
187755714Skris	is null, a BIGNUM is created and returned via that variable.
187855714Skris	
187955714Skrisint BN_print_fp(FILE *fp, BIGNUM *a);
188055714Skris	'a' is printed to file pointer 'fp'.  It is in the same format
188155714Skris	that is output from BN_bn2ascii().  0 is returned on error,
188255714Skris	1 if things are ok.
188355714Skris
188455714Skrisint BN_print(BIO *bp, BIGNUM *a);
188555714Skris	Same as BN_print except that the output is done to the SSLeay libraries
188655714Skris	BIO routines.  BN_print_fp() actually calls this function.
188755714Skris
188855714SkrisMiscellaneous Routines.
188955714Skris
189055714Skrisint BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
189155714Skris	This function returns in 'rnd' a random BIGNUM that is bits
189255714Skris	long.  If bottom is 1, the number returned is odd.  If top is set,
189355714Skris	the top 2 bits of the number are set.  This is useful because if
189455714Skris	this is set, 2 'n; bit numbers multiplied together will return a 2n
189555714Skris	bit number.  If top was not set, they could produce a 2n-1 bit
189655714Skris	number.
189755714Skris
189855714SkrisBIGNUM *BN_mod_inverse(BIGNUM *a, BIGNUM *n,BN_CTX *ctx);
189955714Skris	This function create a new BIGNUM and returns it.  This number
190055714Skris	is the inverse mod 'n' of 'a'.  By this it is meant that the
190155714Skris	returned value 'r' satisfies (a*r)%n == 1.  This function is
190255714Skris	used in the generation of RSA keys.  'ctx', as per usual,
190355714Skris	is used to hold temporary variables that are required by the
190455714Skris	function.  NULL is returned on error.
190555714Skris
190655714Skrisint BN_gcd(BIGNUM *r,BIGNUM *a,BIGNUM *b,BN_CTX *ctx);
190755714Skris	'r' has the greatest common divisor of 'a' and 'b'.  'ctx' is
190855714Skris	used for temporary variables and 0 is returned on error.
190955714Skris
191055714Skrisint BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(),BN_CTX *ctx,
191155714Skris	char *cb_arg);
191255714Skris	This function is used to check if a BIGNUM ('p') is prime.
191355714Skris	It performs this test by using the Miller-Rabin randomised
191455714Skris	primality test.  This is a probalistic test that requires a
191555714Skris	number of rounds to ensure the number is prime to a high
191655714Skris	degree of probability.  Since this can take quite some time, a
191755714Skris	callback function can be passed and it will be called each
191855714Skris	time 'p' passes a round of the prime testing.  'callback' will
191955714Skris	be called as follows, callback(1,n,cb_arg) where n is the number of
192055714Skris	the round, just passed.  As per usual 'ctx' contains temporary
192155714Skris	variables used.  If ctx is NULL, it does not matter, a local version
192255714Skris	will be malloced.  This parameter is present to save some mallocing
192355714Skris	inside the function but probably could be removed.
192455714Skris	0 is returned on error.
192555714Skris	'ncheck' is the number of Miller-Rabin tests to run.  It is
192655714Skris	suggested to use the value 'BN_prime_checks' by default.
192755714Skris
192855714SkrisBIGNUM *BN_generate_prime(
192955714Skrisint bits,
193055714Skrisint strong,
193155714SkrisBIGNUM *a,
193255714SkrisBIGNUM *rems,
193355714Skrisvoid (*callback)());
193455714Skrischar *cb_arg
193555714Skris	This function is used to generate prime numbers.  It returns a
193655714Skris	new BIGNUM that has a high probability of being a prime.
193755714Skris	'bits' is the number of bits that
193855714Skris	are to be in the prime.  If 'strong' is true, the returned prime
193955714Skris	will also be a strong prime ((p-1)/2 is also prime).
194055714Skris	While searching for the prime ('p'), we
194155714Skris	can add the requirement that the prime fill the following
194255714Skris	condition p%a == rem.  This can be used to help search for
194355714Skris	primes with specific features, which is required when looking
194455714Skris	for primes suitable for use with certain 'g' values in the
194555714Skris	Diffie-Hellman key exchange algorithm.  If 'a' is NULL,
194655714Skris	this condition is not checked.  If rem is NULL, rem is assumed
194755714Skris	to be 1.  Since this search for a prime
194855714Skris	can take quite some time, if callback is not NULL, it is called
194955714Skris	in the following situations.
195055714Skris	We have a suspected prime (from a quick sieve),
195155714Skris	callback(0,sus_prime++,cb_arg). Each item to be passed to BN_is_prime().
195255714Skris	callback(1,round++,cb_arg).  Each successful 'round' in BN_is_prime().
195355714Skris	callback(2,round,cb_arg). For each successful BN_is_prime() test.
195455714Skris
195555714SkrisHints
195655714Skris-----
195755714Skris
195855714SkrisDSA wants 64*32 to use word mont mul, but RSA wants to use full.
195955714Skris
196055714Skris==== callback.doc ========================================================
196155714Skris
196255714SkrisCallback functions used in SSLeay.
196355714Skris
196455714Skris--------------------------
196555714SkrisThe BIO library.  
196655714Skris
196755714SkrisEach BIO structure can have a callback defined against it.  This callback is
196855714Skriscalled 2 times for each BIO 'function'.  It is passed 6 parameters.
196955714SkrisBIO_debug_callback() is an example callback which is defined in
197055714Skriscrypto/buffer/bio_cb.c and is used in apps/dgst.c  This is intended mostly
197155714Skrisfor debuging or to notify the application of IO.
197255714Skris
197355714Skrislong BIO_debug_callback(BIO *bio,int cmd,char *argp,int argi,long argl,
197455714Skris	long ret);
197555714Skrisbio is the BIO being called, cmd is the type of BIO function being called.
197655714SkrisLook at the BIO_CB_* defines in buffer.h.  Argp and argi are the arguments
197755714Skrispassed to BIO_read(), BIO_write, BIO_gets(), BIO_puts().  In the case of
197855714SkrisBIO_ctrl(), argl is also defined.  The first time the callback is called,
197955714Skrisbefore the underlying function has been executed, 0 is passed as 'ret', and
198055714Skrisif the return code from the callback is not > 0, the call is aborted
198155714Skrisand the returned <= 0 value is returned.
198255714SkrisThe second time the callback is called, the 'cmd' value also has
198355714SkrisBIO_CB_RETURN logically 'or'ed with it.  The 'ret' value is the value returned
198455714Skrisfrom the actuall function call and whatever the callback returns is returned
198555714Skrisfrom the BIO function.
198655714Skris
198755714SkrisBIO_set_callback(b,cb) can be used to set the callback function
198855714Skris(b is a BIO), and BIO_set_callback_arg(b,arg) can be used to
198955714Skrisset the cb_arg argument in the BIO strucutre.  This field is only intended
199055714Skristo be used by application, primarily in the callback function since it is
199155714Skrisaccessable since the BIO is passed.
199255714Skris
199355714Skris--------------------------
199455714SkrisThe PEM library.
199555714Skris
199655714SkrisThe pem library only really uses one type of callback,
199755714Skrisstatic int def_callback(char *buf, int num, int verify);
199855714Skriswhich is used to return a password string if required.
199955714Skris'buf' is the buffer to put the string in.  'num' is the size of 'buf'
200055714Skrisand 'verify' is used to indicate that the password should be checked.
200155714SkrisThis last flag is mostly used when reading a password for encryption.
200255714Skris
200355714SkrisFor all of these functions, a NULL callback will call the above mentioned
200455714Skrisdefault callback.  This default function does not work under Windows 3.1.
200555714SkrisFor other machines, it will use an application defined prompt string
200655714Skris(EVP_set_pw_prompt(), which defines a library wide prompt string)
200755714Skrisif defined, otherwise it will use it's own PEM password prompt.
200855714SkrisIt will then call EVP_read_pw_string() to get a password from the console.
200955714SkrisIf your application wishes to use nice fancy windows to retrieve passwords,
201055714Skrisreplace this function.  The callback should return the number of bytes read
201155714Skrisinto 'buf'.  If the number of bytes <= 0, it is considered an error.
201255714Skris
201355714SkrisFunctions that take this callback are listed below.  For the 'read' type
201455714Skrisfunctions, the callback will only be required if the PEM data is encrypted.
201555714Skris
201655714SkrisFor the Write functions, normally a password can be passed in 'kstr', of
201755714Skris'klen' bytes which will be used if the 'enc' cipher is not NULL.  If
201855714Skris'kstr' is NULL, the callback will be used to retrieve a password.
201955714Skris
202055714Skrisint PEM_do_header (EVP_CIPHER_INFO *cipher, unsigned char *data,long *len,
202155714Skris	int (*callback)());
202255714Skrischar *PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *bp,char **x,int (*cb)());
202355714Skrischar *PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
202455714Skrisint PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *bp,char *x,
202555714Skris	EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
202655714Skrisint PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,
202755714Skris	EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
202855714SkrisSTACK *PEM_X509_INFO_read(FILE *fp, STACK *sk, int (*cb)());
202955714SkrisSTACK *PEM_X509_INFO_read_bio(BIO *fp, STACK *sk, int (*cb)());
203055714Skris
203155714Skris#define	PEM_write_RSAPrivateKey(fp,x,enc,kstr,klen,cb)
203255714Skris#define	PEM_write_DSAPrivateKey(fp,x,enc,kstr,klen,cb)
203355714Skris#define	PEM_write_bio_RSAPrivateKey(bp,x,enc,kstr,klen,cb)
203455714Skris#define	PEM_write_bio_DSAPrivateKey(bp,x,enc,kstr,klen,cb)
203555714Skris#define	PEM_read_SSL_SESSION(fp,x,cb)
203655714Skris#define	PEM_read_X509(fp,x,cb)
203755714Skris#define	PEM_read_X509_REQ(fp,x,cb)
203855714Skris#define	PEM_read_X509_CRL(fp,x,cb)
203955714Skris#define	PEM_read_RSAPrivateKey(fp,x,cb)
204055714Skris#define	PEM_read_DSAPrivateKey(fp,x,cb)
204155714Skris#define	PEM_read_PrivateKey(fp,x,cb)
204255714Skris#define	PEM_read_PKCS7(fp,x,cb)
204355714Skris#define	PEM_read_DHparams(fp,x,cb)
204455714Skris#define	PEM_read_bio_SSL_SESSION(bp,x,cb)
204555714Skris#define	PEM_read_bio_X509(bp,x,cb)
204655714Skris#define	PEM_read_bio_X509_REQ(bp,x,cb)
204755714Skris#define	PEM_read_bio_X509_CRL(bp,x,cb)
204855714Skris#define	PEM_read_bio_RSAPrivateKey(bp,x,cb)
204955714Skris#define	PEM_read_bio_DSAPrivateKey(bp,x,cb)
205055714Skris#define	PEM_read_bio_PrivateKey(bp,x,cb)
205155714Skris#define	PEM_read_bio_PKCS7(bp,x,cb)
205255714Skris#define	PEM_read_bio_DHparams(bp,x,cb)
205355714Skrisint i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
205455714SkrisRSA *d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
205555714Skris
205655714SkrisNow you will notice that macros like
205755714Skris#define PEM_write_X509(fp,x) \
205855714Skris                PEM_ASN1_write((int (*)())i2d_X509,PEM_STRING_X509,fp, \
205955714Skris		                        (char *)x, NULL,NULL,0,NULL)
206055714SkrisDon't do encryption normally.  If you want to PEM encrypt your X509 structure,
2061238405Sjkimeither just call PEM_ASN1_write directly or just define your own
206255714Skrismacro variant.  As you can see, this macro just sets all encryption related
206355714Skrisparameters to NULL.
206455714Skris
206555714Skris
206655714Skris--------------------------
206755714SkrisThe SSL library.
206855714Skris
206955714Skris#define SSL_set_info_callback(ssl,cb)
207055714Skris#define SSL_CTX_set_info_callback(ctx,cb)
207155714Skrisvoid callback(SSL *ssl,int location,int ret)
207255714SkrisThis callback is called each time around the SSL_connect()/SSL_accept() 
207355714Skrisstate machine.  So it will be called each time the SSL protocol progresses.
207455714SkrisIt is mostly present for use when debugging.  When SSL_connect() or
207555714SkrisSSL_accept() return, the location flag is SSL_CB_ACCEPT_EXIT or
207655714SkrisSSL_CB_CONNECT_EXIT and 'ret' is the value about to be returned.
207755714SkrisHave a look at the SSL_CB_* defines in ssl.h.  If an info callback is defined
207855714Skrisagainst the SSL_CTX, it is called unless there is one set against the SSL.
207955714SkrisHave a look at
208055714Skrisvoid client_info_callback() in apps/s_client() for an example.
208155714Skris
208255714SkrisCertificate verification.
208355714Skrisvoid SSL_set_verify(SSL *s, int mode, int (*callback) ());
208455714Skrisvoid SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*callback)());
208555714SkrisThis callback is used to help verify client and server X509 certificates.
208655714SkrisIt is actually passed to X509_cert_verify(), along with the SSL structure
208755714Skrisso you have to read about X509_cert_verify() :-).  The SSL_CTX version is used
208855714Skrisif the SSL version is not defined.  X509_cert_verify() is the function used
208955714Skrisby the SSL part of the library to verify certificates.  This function is
209055714Skrisnearly always defined by the application.
209155714Skris
209255714Skrisvoid SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx, int (*cb)(),char *arg);
209355714Skrisint callback(char *arg,SSL *s,X509 *xs,STACK *cert_chain);
209455714SkrisThis call is used to replace the SSLeay certificate verification code.
209555714SkrisThe 'arg' is kept in the SSL_CTX and is passed to the callback.
209655714SkrisIf the callback returns 0, the certificate is rejected, otherwise it
209755714Skrisis accepted.  The callback is replacing the X509_cert_verify() call.
209855714SkrisThis feature is not often used, but if you wished to implement
209955714Skrissome totally different certificate authentication system, this 'hook' is
210055714Skrisvital.
210155714Skris
210255714SkrisSSLeay keeps a cache of session-ids against each SSL_CTX.  These callbacks can
210355714Skrisbe used to notify the application when a SSL_SESSION is added to the cache
210455714Skrisor to retrieve a SSL_SESSION that is not in the cache from the application.
210555714Skris#define SSL_CTX_sess_set_get_cb(ctx,cb)
210655714SkrisSSL_SESSION *callback(SSL *s,char *session_id,int session_id_len,int *copy);
210755714SkrisIf defined, this callback is called to return the SESSION_ID for the
210855714Skrissession-id in 'session_id', of 'session_id_len' bytes.  'copy' is set to 1
210955714Skrisif the server is to 'take a copy' of the SSL_SESSION structure.  It is 0
211055714Skrisif the SSL_SESSION is being 'passed in' so the SSLeay library is now
211155714Skrisresponsible for 'free()ing' the structure.  Basically it is used to indicate
211255714Skrisif the reference count on the SSL_SESSION structure needs to be incremented.
211355714Skris
211455714Skris#define SSL_CTX_sess_set_new_cb(ctx,cb)
211555714Skrisint callback(SSL *s, SSL_SESSION *sess);
211655714SkrisWhen a new connection is established, if the SSL_SESSION is going to be added
211755714Skristo the cache, this callback is called.  Return 1 if a 'copy' is required,
211855714Skrisotherwise, return 0.  This return value just causes the reference count
211955714Skristo be incremented (on return of a 1), this means the application does
212055714Skrisnot need to worry about incrementing the refernece count (and the
212155714Skrislocking that implies in a multi-threaded application).
212255714Skris
212355714Skrisvoid SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)());
212455714SkrisThis sets the SSL password reading function.
212555714SkrisIt is mostly used for windowing applications
212655714Skrisand used by PEM_read_bio_X509() and PEM_read_bio_RSAPrivateKey()
212755714Skriscalls inside the SSL library.   The only reason this is present is because the
212855714Skriscalls to PEM_* functions is hidden in the SSLeay library so you have to
212955714Skrispass in the callback some how.
213055714Skris
213155714Skris#define SSL_CTX_set_client_cert_cb(ctx,cb)
213255714Skrisint callback(SSL *s,X509 **x509, EVP_PKEY **pkey);
213355714SkrisCalled when a client certificate is requested but there is not one set
213455714Skrisagainst the SSL_CTX or the SSL.  If the callback returns 1, x509 and
213555714Skrispkey need to point to valid data.  The library will free these when
213655714Skrisrequired so if the application wants to keep these around, increment
213755714Skristheir reference counts.  If 0 is returned, no client cert is
213855714Skrisavailable.  If -1 is returned, it is assumed that the callback needs
213955714Skristo be called again at a later point in time.  SSL_connect will return
214055714Skris-1 and SSL_want_x509_lookup(ssl) returns true.  Remember that
214155714Skrisapplication data can be attached to an SSL structure via the
214255714SkrisSSL_set_app_data(SSL *ssl,char *data) call.
214355714Skris
214455714Skris--------------------------
214555714SkrisThe X509 library.
214655714Skris
214755714Skrisint X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)(),
214855714Skris	int *error,char *arg,STACK *cert_chain);
214955714Skrisint verify_callback(int ok,X509 *xs,X509 *xi,int depth,int error,char *arg,
215055714Skris	STACK *cert_chain);
215155714Skris
215255714SkrisX509_cert_verify() is used to authenticate X509 certificates.  The 'ctx' holds
215355714Skristhe details of the various caches and files used to locate certificates.
215455714Skris'xs' is the certificate to verify and 'cb' is the application callback (more
215555714Skrisdetail later).  'error' will be set to the error code and 'arg' is passed
215655714Skristo the 'cb' callback.  Look at the VERIFY_* defines in crypto/x509/x509.h
215755714Skris
215855714SkrisWhen ever X509_cert_verify() makes a 'negative' decision about a
215955714Skriscertitificate, the callback is called.  If everything checks out, the
216055714Skriscallback is called with 'VERIFY_OK' or 'VERIFY_ROOT_OK' (for a self
216155714Skrissigned cert that is not the passed certificate).
216255714Skris
216355714SkrisThe callback is passed the X509_cert_verify opinion of the certificate 
216455714Skrisin 'ok', the certificate in 'xs', the issuer certificate in 'xi',
216555714Skristhe 'depth' of the certificate in the verification 'chain', the
216655714SkrisVERIFY_* code in 'error' and the argument passed to X509_cert_verify()
216755714Skrisin 'arg'. cert_chain is a list of extra certs to use if they are not
216855714Skrisin the cache.
216955714Skris
217055714SkrisThe callback can be used to look at the error reason, and then return 0
217155714Skrisfor an 'error' or '1' for ok.  This will override the X509_cert_verify()
217255714Skrisopinion of the certificates validity.  Processing will continue depending on
217355714Skristhe return value.  If one just wishes to use the callback for informational
217455714Skrisreason, just return the 'ok' parameter.
217555714Skris
217655714Skris--------------------------
217755714SkrisThe BN and DH library.
217855714Skris
217955714SkrisBIGNUM *BN_generate_prime(int bits,int strong,BIGNUM *add,
218055714Skris	BIGNUM *rem,void (*callback)(int,int));
218155714Skrisint BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(int,int),
218255714Skris
218355714SkrisRead doc/bn.doc for the description of these 2.
218455714Skris
218555714SkrisDH *DH_generate_parameters(int prime_len,int generator,
218655714Skris	void (*callback)(int,int));
218755714SkrisRead doc/bn.doc for the description of the callback, since it is just passed
218855714Skristo BN_generate_prime(), except that it is also called as
218955714Skriscallback(3,0) by this function.
219055714Skris
219155714Skris--------------------------
219255714SkrisThe CRYPTO library.
219355714Skris
219455714Skrisvoid CRYPTO_set_locking_callback(void (*func)(int mode,int type,char *file,
219555714Skris	int line));
219655714Skrisvoid CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,
219755714Skris	int type,char *file, int line));
219855714Skrisvoid CRYPTO_set_id_callback(unsigned long (*func)(void));
219955714Skris
220055714SkrisRead threads.doc for info on these ones.
220155714Skris
220255714Skris
220355714Skris==== cipher.doc ========================================================
220455714Skris
220555714SkrisThe Cipher subroutines.
220655714Skris
220755714SkrisThese routines require "evp.h" to be included.
220855714Skris
220955714SkrisThese functions are a higher level interface to the various cipher
221055714Skrisroutines found in this library.  As such, they allow the same code to be
221155714Skrisused to encrypt and decrypt via different ciphers with only a change
221255714Skrisin an initial parameter.  These routines also provide buffering for block
221355714Skrisciphers.
221455714Skris
221555714SkrisThese routines all take a pointer to the following structure to specify
221655714Skriswhich cipher to use.  If you wish to use a new cipher with these routines,
221755714Skrisyou would probably be best off looking an how an existing cipher is
221855714Skrisimplemented and copying it.  At this point in time, I'm not going to go
221955714Skrisinto many details.  This structure should be considered opaque
222055714Skris
222155714Skristypedef struct pem_cipher_st
222255714Skris	{
222355714Skris	int type;
222455714Skris	int block_size;
222555714Skris	int key_len;
222655714Skris	int iv_len;
222755714Skris	void (*enc_init)();	/* init for encryption */
222855714Skris	void (*dec_init)();	/* init for decryption */
222955714Skris	void (*do_cipher)();	/* encrypt data */
223055714Skris	} EVP_CIPHER;
223155714Skris	
223255714SkrisThe type field is the object NID of the cipher type
223355714Skris(read the section on Objects for an explanation of what a NID is).
223455714SkrisThe cipher block_size is how many bytes need to be passed
223555714Skristo the cipher at a time.  Key_len is the
223655714Skrislength of the key the cipher requires and iv_len is the length of the
223755714Skrisinitialisation vector required.  enc_init is the function
223855714Skriscalled to initialise the ciphers context for encryption and dec_init is the
223955714Skrisfunction to initialise for decryption (they need to be different, especially
224055714Skrisfor the IDEA cipher).
224155714Skris
224255714SkrisOne reason for specifying the Cipher via a pointer to a structure
224355714Skrisis that if you only use des-cbc, only the des-cbc routines will
224455714Skrisbe included when you link the program.  If you passed an integer
224555714Skristhat specified which cipher to use, the routine that mapped that
224655714Skrisinteger to a set of cipher functions would cause all the ciphers
224755714Skristo be link into the code.  This setup also allows new ciphers
224855714Skristo be added by the application (with some restrictions).
224955714Skris
225055714SkrisThe thirteen ciphers currently defined in this library are
225155714Skris
225255714SkrisEVP_CIPHER *EVP_des_ecb();     /* DES in ecb mode,     iv=0, block=8, key= 8 */
225355714SkrisEVP_CIPHER *EVP_des_ede();     /* DES in ecb ede mode, iv=0, block=8, key=16 */
225455714SkrisEVP_CIPHER *EVP_des_ede3();    /* DES in ecb ede mode, iv=0, block=8, key=24 */
225555714SkrisEVP_CIPHER *EVP_des_cfb();     /* DES in cfb mode,     iv=8, block=1, key= 8 */
225655714SkrisEVP_CIPHER *EVP_des_ede_cfb(); /* DES in ede cfb mode, iv=8, block=1, key=16 */
225755714SkrisEVP_CIPHER *EVP_des_ede3_cfb();/* DES in ede cfb mode, iv=8, block=1, key=24 */
225855714SkrisEVP_CIPHER *EVP_des_ofb();     /* DES in ofb mode,     iv=8, block=1, key= 8 */
225955714SkrisEVP_CIPHER *EVP_des_ede_ofb(); /* DES in ede ofb mode, iv=8, block=1, key=16 */
226055714SkrisEVP_CIPHER *EVP_des_ede3_ofb();/* DES in ede ofb mode, iv=8, block=1, key=24 */
226155714SkrisEVP_CIPHER *EVP_des_cbc();     /* DES in cbc mode,     iv=8, block=8, key= 8 */
226255714SkrisEVP_CIPHER *EVP_des_ede_cbc(); /* DES in cbc ede mode, iv=8, block=8, key=16 */
226355714SkrisEVP_CIPHER *EVP_des_ede3_cbc();/* DES in cbc ede mode, iv=8, block=8, key=24 */
226455714SkrisEVP_CIPHER *EVP_desx_cbc();    /* DES in desx cbc mode,iv=8, block=8, key=24 */
226555714SkrisEVP_CIPHER *EVP_rc4();         /* RC4,                 iv=0, block=1, key=16 */
226655714SkrisEVP_CIPHER *EVP_idea_ecb();    /* IDEA in ecb mode,    iv=0, block=8, key=16 */
226755714SkrisEVP_CIPHER *EVP_idea_cfb();    /* IDEA in cfb mode,    iv=8, block=1, key=16 */
226855714SkrisEVP_CIPHER *EVP_idea_ofb();    /* IDEA in ofb mode,    iv=8, block=1, key=16 */
226955714SkrisEVP_CIPHER *EVP_idea_cbc();    /* IDEA in cbc mode,    iv=8, block=8, key=16 */
227055714SkrisEVP_CIPHER *EVP_rc2_ecb();     /* RC2 in ecb mode,     iv=0, block=8, key=16 */
227155714SkrisEVP_CIPHER *EVP_rc2_cfb();     /* RC2 in cfb mode,     iv=8, block=1, key=16 */
227255714SkrisEVP_CIPHER *EVP_rc2_ofb();     /* RC2 in ofb mode,     iv=8, block=1, key=16 */
227355714SkrisEVP_CIPHER *EVP_rc2_cbc();     /* RC2 in cbc mode,     iv=8, block=8, key=16 */
227455714SkrisEVP_CIPHER *EVP_bf_ecb();      /* Blowfish in ecb mode,iv=0, block=8, key=16 */
227555714SkrisEVP_CIPHER *EVP_bf_cfb();      /* Blowfish in cfb mode,iv=8, block=1, key=16 */
227655714SkrisEVP_CIPHER *EVP_bf_ofb();      /* Blowfish in ofb mode,iv=8, block=1, key=16 */
227755714SkrisEVP_CIPHER *EVP_bf_cbc();      /* Blowfish in cbc mode,iv=8, block=8, key=16 */
227855714Skris
227955714SkrisThe meaning of the compound names is as follows.
228055714Skrisdes	The base cipher is DES.
228155714Skrisidea	The base cipher is IDEA
228255714Skrisrc4	The base cipher is RC4-128
228355714Skrisrc2	The base cipher is RC2-128
228455714Skrisecb	Electronic Code Book form of the cipher.
228555714Skriscbc	Cipher Block Chaining form of the cipher.
228655714Skriscfb	64 bit Cipher Feedback form of the cipher.
228755714Skrisofb	64 bit Output Feedback form of the cipher.
228855714Skrisede	The cipher is used in Encrypt, Decrypt, Encrypt mode.  The first
228955714Skris	and last keys are the same.
229055714Skrisede3	The cipher is used in Encrypt, Decrypt, Encrypt mode.
229155714Skris
229255714SkrisAll the Cipher routines take a EVP_CIPHER_CTX pointer as an argument.
229355714SkrisThe state of the cipher is kept in this structure.
229455714Skris
229555714Skristypedef struct EVP_CIPHER_Ctx_st
229655714Skris	{
229755714Skris	EVP_CIPHER *cipher;
229855714Skris	int encrypt;		/* encrypt or decrypt */
229955714Skris	int buf_len;		/* number we have left */
230055714Skris	unsigned char buf[8];
230155714Skris	union	{
230255714Skris		.... /* cipher specific stuff */
230355714Skris		} c;
230455714Skris	} EVP_CIPHER_CTX;
230555714Skris
230655714SkrisCipher is a pointer the the EVP_CIPHER for the current context.  The encrypt
230755714Skrisflag indicates encryption or decryption.  buf_len is the number of bytes
230855714Skriscurrently being held in buf.
230955714SkrisThe 'c' union holds the cipher specify context.
231055714Skris
231155714SkrisThe following functions are to be used.
231255714Skris
231355714Skrisint EVP_read_pw_string(
231455714Skrischar *buf,
231555714Skrisint len,
231655714Skrischar *prompt,
231755714Skrisint verify,
231855714Skris	This function is the same as des_read_pw_string() (des.doc).
231955714Skris
232055714Skrisvoid EVP_set_pw_prompt(char *prompt);
232155714Skris	This function sets the 'default' prompt to use to use in
232255714Skris	EVP_read_pw_string when the prompt parameter is NULL.  If the
232355714Skris	prompt parameter is NULL, this 'default prompt' feature is turned
232455714Skris	off.  Be warned, this is a global variable so weird things
232555714Skris	will happen if it is used under Win16 and care must be taken
232655714Skris	with a multi-threaded version of the library.
232755714Skris
232855714Skrischar *EVP_get_pw_prompt();
232955714Skris	This returns a pointer to the default prompt string.  NULL
233055714Skris	if it is not set.
233155714Skris
233255714Skrisint EVP_BytesToKey(
233355714SkrisEVP_CIPHER *type,
233455714SkrisEVP_MD *md,
233555714Skrisunsigned char *salt,
233655714Skrisunsigned char *data,
233755714Skrisint datal,
233855714Skrisint count,
233955714Skrisunsigned char *key,
234055714Skrisunsigned char *iv);
234155714Skris	This function is used to generate a key and an initialisation vector
234255714Skris	for a specified cipher from a key string and a salt.  Type
234355714Skris	specifies the cipher the 'key' is being generated for.  Md is the
234455714Skris	message digest algorithm to use to generate the key and iv.  The salt
234555714Skris	is an optional 8 byte object that is used to help seed the key
234655714Skris	generator.
234755714Skris	If the salt value is NULL, it is just not used.  Datal is the
234855714Skris	number of bytes to use from 'data' in the key generation.  
234955714Skris	This function returns the key size for the specified cipher, if
235055714Skris	data is NULL, this value is returns and no other
235155714Skris	computation is performed.  Count is
235255714Skris	the number of times to loop around the key generator.  I would
235355714Skris	suggest leaving it's value as 1.  Key and iv are the structures to
235455714Skris	place the returning iv and key in.  If they are NULL, no value is
235555714Skris	generated for that particular value.
235655714Skris	The algorithm used is as follows
235755714Skris	
235855714Skris	/* M[] is an array of message digests
235955714Skris	 * MD() is the message digest function */
236055714Skris	M[0]=MD(data . salt);
236155714Skris	for (i=1; i<count; i++) M[0]=MD(M[0]);
236255714Skris
236355714Skris	i=1
236455714Skris	while (data still needed for key and iv)
236555714Skris		{
236655714Skris		M[i]=MD(M[i-1] . data . salt);
236755714Skris		for (i=1; i<count; i++) M[i]=MD(M[i]);
236855714Skris		i++;
236955714Skris		}
237055714Skris
237155714Skris	If the salt is NULL, it is not used.
237255714Skris	The digests are concatenated together.
237355714Skris	M = M[0] . M[1] . M[2] .......
237455714Skris
237555714Skris	For key= 8, iv=8 => key=M[0.. 8], iv=M[ 9 .. 16].
237655714Skris	For key=16, iv=0 => key=M[0..16].
237755714Skris	For key=16, iv=8 => key=M[0..16], iv=M[17 .. 24].
237855714Skris	For key=24, iv=8 => key=M[0..24], iv=M[25 .. 32].
237955714Skris
238055714Skris	This routine will produce DES-CBC keys and iv that are compatible
238155714Skris	with the PKCS-5 standard when md2 or md5 are used.  If md5 is
238255714Skris	used, the salt is NULL and count is 1, this routine will produce
238355714Skris	the password to key mapping normally used with RC4.
238455714Skris	I have attempted to logically extend the PKCS-5 standard to
238555714Skris	generate keys and iv for ciphers that require more than 16 bytes,
238655714Skris	if anyone knows what the correct standard is, please inform me.
238755714Skris	When using sha or sha1, things are a bit different under this scheme,
238855714Skris	since sha produces a 20 byte digest.  So for ciphers requiring
238955714Skris	24 bits of data, 20 will come from the first MD and 4 will
239055714Skris	come from the second.
239155714Skris
239255714Skris	I have considered having a separate function so this 'routine'
239355714Skris	can be used without the requirement of passing a EVP_CIPHER *,
239455714Skris	but I have decided to not bother.  If you wish to use the
239555714Skris	function without official EVP_CIPHER structures, just declare
239655714Skris	a local one and set the key_len and iv_len fields to the
239755714Skris	length you desire.
239855714Skris
239955714SkrisThe following routines perform encryption and decryption 'by parts'.  By
240055714Skristhis I mean that there are groups of 3 routines.  An Init function that is
240155714Skrisused to specify a cipher and initialise data structures.  An Update routine
240255714Skristhat does encryption/decryption, one 'chunk' at a time.  And finally a
240355714Skris'Final' function that finishes the encryption/decryption process.
240455714SkrisAll these functions take a EVP_CIPHER pointer to specify which cipher to
240555714Skrisencrypt/decrypt with.  They also take a EVP_CIPHER_CTX object as an
240655714Skrisargument.  This structure is used to hold the state information associated
240755714Skriswith the operation in progress.
240855714Skris
240955714Skrisvoid EVP_EncryptInit(
241055714SkrisEVP_CIPHER_CTX *ctx,
241155714SkrisEVP_CIPHER *type,
241255714Skrisunsigned char *key,
241355714Skrisunsigned char *iv);
241455714Skris	This function initialise a EVP_CIPHER_CTX for encryption using the
241555714Skris	cipher passed in the 'type' field.  The cipher is initialised to use
241655714Skris	'key' as the key and 'iv' for the initialisation vector (if one is
241755714Skris	required).  If the type, key or iv is NULL, the value currently in the
241855714Skris	EVP_CIPHER_CTX is reused.  So to perform several decrypt
241955714Skris	using the same cipher, key and iv, initialise with the cipher,
242055714Skris	key and iv the first time and then for subsequent calls,
242155714Skris	reuse 'ctx' but pass NULL for type, key and iv.  You must make sure
242255714Skris	to pass a key that is large enough for a particular cipher.  I
242355714Skris	would suggest using the EVP_BytesToKey() function.
242455714Skris
242555714Skrisvoid EVP_EncryptUpdate(
242655714SkrisEVP_CIPHER_CTX *ctx,
242755714Skrisunsigned char *out,
242855714Skrisint *outl,
242955714Skrisunsigned char *in,
243055714Skrisint inl);
243155714Skris	This function takes 'inl' bytes from 'in' and outputs bytes
243255714Skris	encrypted by the cipher 'ctx' was initialised with into 'out'.  The
243355714Skris	number of bytes written to 'out' is put into outl.  If a particular
243455714Skris	cipher encrypts in blocks, less or more bytes than input may be
243555714Skris	output.  Currently the largest block size used by supported ciphers
243655714Skris	is 8 bytes, so 'out' should have room for 'inl+7' bytes.  Normally
243755714Skris	EVP_EncryptInit() is called once, followed by lots and lots of
243855714Skris	calls to EVP_EncryptUpdate, followed by a single EVP_EncryptFinal
243955714Skris	call.
244055714Skris
244155714Skrisvoid EVP_EncryptFinal(
244255714SkrisEVP_CIPHER_CTX *ctx,
244355714Skrisunsigned char *out,
244455714Skrisint *outl);
244555714Skris	Because quite a large number of ciphers are block ciphers, there is
244655714Skris	often an incomplete block to write out at the end of the
244755714Skris	encryption.  EVP_EncryptFinal() performs processing on this last
244855714Skris	block.  The last block in encoded in such a way that it is possible
244955714Skris	to determine how many bytes in the last block are valid.  For 8 byte
245055714Skris	block size ciphers, if only 5 bytes in the last block are valid, the
245155714Skris	last three bytes will be filled with the value 3.  If only 2 were
245255714Skris	valid, the other 6 would be filled with sixes.  If all 8 bytes are
245355714Skris	valid, a extra 8 bytes are appended to the cipher stream containing
245455714Skris	nothing but 8 eights.  These last bytes are output into 'out' and
245555714Skris	the number of bytes written is put into 'outl'  These last bytes
245655714Skris	are output into 'out' and the number of bytes written is put into
245755714Skris	'outl'.  This form of block cipher finalisation is compatible with
245855714Skris	PKCS-5.  Please remember that even if you are using ciphers like
245955714Skris	RC4 that has no blocking and so the function will not write
246055714Skris	anything into 'out', it would still be a good idea to pass a
246155714Skris	variable for 'out' that can hold 8 bytes just in case the cipher is
246255714Skris	changed some time in the future.  It should also be remembered
246355714Skris	that the EVP_CIPHER_CTX contains the password and so when one has
246455714Skris	finished encryption with a particular EVP_CIPHER_CTX, it is good
246555714Skris	practice to zero the structure 
246655714Skris	(ie. memset(ctx,0,sizeof(EVP_CIPHER_CTX)).
246755714Skris	
246855714Skrisvoid EVP_DecryptInit(
246955714SkrisEVP_CIPHER_CTX *ctx,
247055714SkrisEVP_CIPHER *type,
247155714Skrisunsigned char *key,
247255714Skrisunsigned char *iv);
247355714Skris	This function is basically the same as EVP_EncryptInit() accept that
247455714Skris	is prepares the EVP_CIPHER_CTX for decryption.
247555714Skris
247655714Skrisvoid EVP_DecryptUpdate(
247755714SkrisEVP_CIPHER_CTX *ctx,
247855714Skrisunsigned char *out,
247955714Skrisint *outl,
248055714Skrisunsigned char *in,
248155714Skrisint inl);
248255714Skris	This function is basically the same as EVP_EncryptUpdate()
248355714Skris	except that it performs decryption.  There is one
248455714Skris	fundamental difference though.  'out' can not be the same as
248555714Skris	'in' for any ciphers with a block size greater than 1 if more
248655714Skris	than one call to EVP_DecryptUpdate() will be made.  This
248755714Skris	is because this routine can hold a 'partial' block between
248855714Skris	calls.  When a partial block is decrypted (due to more bytes
248955714Skris	being passed via this function, they will be written to 'out'
249055714Skris	overwriting the input bytes in 'in' that have not been read
249155714Skris	yet.  From this it should also be noted that 'out' should
249255714Skris	be at least one 'block size' larger than 'inl'.  This problem
249355714Skris	only occurs on the second and subsequent call to
249455714Skris	EVP_DecryptUpdate() when using a block cipher.
249555714Skris
249655714Skrisint EVP_DecryptFinal(
249755714SkrisEVP_CIPHER_CTX *ctx,
249855714Skrisunsigned char *out,
249955714Skrisint *outl);
250055714Skris	This function is different to EVP_EncryptFinal in that it 'removes'
250155714Skris	any padding bytes appended when the data was encrypted.  Due to the
250255714Skris	way in which 1 to 8 bytes may have been appended when encryption
250355714Skris	using a block cipher, 'out' can end up with 0 to 7 bytes being put
250455714Skris	into it.  When decoding the padding bytes, it is possible to detect
250555714Skris	an incorrect decryption.  If the decryption appears to be wrong, 0
250655714Skris	is returned.  If everything seems ok, 1 is returned.  For ciphers
250755714Skris	with a block size of 1 (RC4), this function would normally not
250855714Skris	return any bytes and would always return 1.  Just because this
250955714Skris	function returns 1 does not mean the decryption was correct. It
251055714Skris	would normally be wrong due to either the wrong key/iv or
251155714Skris	corruption of the cipher data fed to EVP_DecryptUpdate().
251255714Skris	As for EVP_EncryptFinal, it is a good idea to zero the
251355714Skris	EVP_CIPHER_CTX after use since the structure contains the key used
251455714Skris	to decrypt the data.
251555714Skris	
251655714SkrisThe following Cipher routines are convenience routines that call either
251755714SkrisEVP_EncryptXxx or EVP_DecryptXxx depending on weather the EVP_CIPHER_CTX
251855714Skriswas setup to encrypt or decrypt.  
251955714Skris
252055714Skrisvoid EVP_CipherInit(
252155714SkrisEVP_CIPHER_CTX *ctx,
252255714SkrisEVP_CIPHER *type,
252355714Skrisunsigned char *key,
252455714Skrisunsigned char *iv,
252555714Skrisint enc);
252655714Skris	This function take arguments that are the same as EVP_EncryptInit()
252755714Skris	and EVP_DecryptInit() except for the extra 'enc' flag.  If 1, the
252855714Skris	EVP_CIPHER_CTX is setup for encryption, if 0, decryption.
252955714Skris
253055714Skrisvoid EVP_CipherUpdate(
253155714SkrisEVP_CIPHER_CTX *ctx,
253255714Skrisunsigned char *out,
253355714Skrisint *outl,
253455714Skrisunsigned char *in,
253555714Skrisint inl);
253655714Skris	Again this function calls either EVP_EncryptUpdate() or
253755714Skris	EVP_DecryptUpdate() depending on state in the 'ctx' structure.
253855714Skris	As noted for EVP_DecryptUpdate(), when this routine is used
253955714Skris	for decryption with block ciphers, 'out' should not be the
254055714Skris	same as 'in'.
254155714Skris
254255714Skrisint EVP_CipherFinal(
254355714SkrisEVP_CIPHER_CTX *ctx,
254455714Skrisunsigned char *outm,
254555714Skrisint *outl);
254655714Skris	This routine call EVP_EncryptFinal() or EVP_DecryptFinal()
254755714Skris	depending on the state information in 'ctx'.  1 is always returned
254855714Skris	if the mode is encryption, otherwise the return value is the return
254955714Skris	value of EVP_DecryptFinal().
255055714Skris
255155714Skris==== cipher.m ========================================================
255255714Skris
255355714SkrisDate: Tue, 15 Oct 1996 08:16:14 +1000 (EST)
255455714SkrisFrom: Eric Young <eay@mincom.com>
255555714SkrisX-Sender: eay@orb
255655714SkrisTo: Roland Haring <rharing@tandem.cl>
255755714SkrisCc: ssl-users@mincom.com
255855714SkrisSubject: Re: Symmetric encryption with ssleay
255955714SkrisIn-Reply-To: <m0vBpyq-00001aC@tandemnet.tandem.cl>
256055714SkrisMessage-Id: <Pine.SOL.3.91.961015075623.11394A-100000@orb>
256155714SkrisMime-Version: 1.0
256255714SkrisContent-Type: TEXT/PLAIN; charset=US-ASCII
256355714SkrisSender: ssl-lists-owner@mincom.com
256455714SkrisPrecedence: bulk
256555714SkrisStatus: RO
256655714SkrisX-Status: 
256755714Skris
256855714SkrisOn Fri, 11 Oct 1996, Roland Haring wrote:
256955714Skris> THE_POINT:
257055714Skris> 	Would somebody be so kind to give me the minimum basic 
257155714Skris> 	calls I need to do to libcrypto.a to get some text encrypted
257255714Skris> 	and decrypted again? ...hopefully with code included to do
257355714Skris> 	base64 encryption and decryption ... e.g. that sign-it.c code
257455714Skris> 	posted some while ago was a big help :-) (please, do not point
257555714Skris> 	me to apps/enc.c where I suspect my Heissenbug to be hidden :-)
257655714Skris
257755714SkrisOk, the base64 encoding stuff in 'enc.c' does the wrong thing sometimes 
257855714Skriswhen the data is less than a line long (this is for decoding).  I'll dig 
257955714Skrisup the exact fix today and post it.  I am taking longer on 0.6.5 than I 
258055714Skrisintended so I'll just post this patch.
258155714Skris
258255714SkrisThe documentation to read is in
258355714Skrisdoc/cipher.doc,
258455714Skrisdoc/encode.doc (very sparse :-).
258555714Skrisand perhaps
258655714Skrisdoc/digest.doc,
258755714Skris
258855714SkrisThe basic calls to encrypt with say triple DES are
258955714Skris
259055714SkrisGiven
259155714Skrischar key[EVP_MAX_KEY_LENGTH];
259255714Skrischar iv[EVP_MAX_IV_LENGTH];
259355714SkrisEVP_CIPHER_CTX ctx;
259455714Skrisunsigned char out[512+8];
259555714Skrisint outl;
259655714Skris
259755714Skris/* optional generation of key/iv data from text password using md5
259855714Skris * via an upward compatable verson of PKCS#5. */
259955714SkrisEVP_BytesToKey(EVP_des_ede3_cbc,EVP_md5,NULL,passwd,strlen(passwd),
260055714Skris	key,iv);
260155714Skris
260255714Skris/* Initalise the EVP_CIPHER_CTX */
260355714SkrisEVP_EncryptInit(ctx,EVP_des_ede3_cbc,key,iv);
260455714Skris
260555714Skriswhile (....)
260655714Skris	{
260755714Skris	/* This is processing 512 bytes at a time, the bytes are being
260855714Skris	 * copied into 'out', outl bytes are output.  'out' should not be the
260955714Skris	 * same as 'in' for reasons mentioned in the documentation. */
261055714Skris	EVP_EncryptUpdate(ctx,out,&outl,in,512);
261155714Skris	}
261255714Skris
261355714Skris/* Output the last 'block'.  If the cipher is a block cipher, the last
261455714Skris * block is encoded in such a way so that a wrong decryption will normally be
261555714Skris * detected - again, one of the PKCS standards. */
261655714Skris
261755714SkrisEVP_EncryptFinal(ctx,out,&outl);
261855714Skris
261955714SkrisTo decrypt, use the EVP_DecryptXXXXX functions except that EVP_DecryptFinal()
262055714Skriswill return 0 if the decryption fails (only detectable on block ciphers).
262155714Skris
262255714SkrisYou can also use
262355714SkrisEVP_CipherInit()
262455714SkrisEVP_CipherUpdate()
262555714SkrisEVP_CipherFinal()
262655714Skriswhich does either encryption or decryption depending on an extra 
262755714Skrisparameter to EVP_CipherInit().
262855714Skris
262955714Skris
263055714SkrisTo do the base64 encoding,
263155714SkrisEVP_EncodeInit()
263255714SkrisEVP_EncodeUpdate()
263355714SkrisEVP_EncodeFinal()
263455714Skris
263555714SkrisEVP_DecodeInit()
263655714SkrisEVP_DecodeUpdate()
263755714SkrisEVP_DecodeFinal()
263855714Skris
263955714Skriswhere the encoding is quite simple, but the decoding can be a bit more 
264055714Skrisfun (due to dud input).
264155714Skris
264255714SkrisEVP_DecodeUpdate() returns -1 for an error on an input line, 0 if the 
264355714Skris'last line' was just processed, and 1 if more lines should be submitted.
264455714Skris
264555714SkrisEVP_DecodeFinal() returns -1 for an error or 1 if things are ok.
264655714Skris
264755714SkrisSo the loop becomes
264855714SkrisEVP_DecodeInit(....)
264955714Skrisfor (;;)
265055714Skris	{
265155714Skris	i=EVP_DecodeUpdate(....);
265255714Skris	if (i < 0) goto err;
265355714Skris
265455714Skris	/* process the data */
265555714Skris
265655714Skris	if (i == 0) break;
265755714Skris	}
265855714SkrisEVP_DecodeFinal(....);
265955714Skris/* process the data */
266055714Skris
266155714SkrisThe problem in 'enc.c' is that I was stuff the processing up after the 
266255714SkrisEVP_DecodeFinal(...) when the for(..) loop was not being run (one line of 
266355714Skrisbase64 data) and this was because 'enc.c' tries to scan over a file until
266455714Skrisit hits the first valid base64 encoded line.
266555714Skris
266655714Skrishope this helps a bit.
266755714Skriseric
266855714Skris--
266955714SkrisEric Young                  | BOOL is tri-state according to Bill Gates.
267055714SkrisAARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
267155714Skris
267255714Skris==== conf.doc ========================================================
267355714Skris
267455714SkrisThe CONF library.
267555714Skris
267655714SkrisThe CONF library is a simple set of routines that can be used to configure
267755714Skrisprograms.  It is a superset of the genenv() function with some extra
267855714Skrisstructure.
267955714Skris
268055714SkrisThe library consists of 5 functions.
268155714Skris
268255714SkrisLHASH *CONF_load(LHASH *config,char *file);
268355714SkrisThis function is called to load in a configuration file.  Multiple
268455714Skrisconfiguration files can be loaded, with each subsequent 'load' overwriting
268555714Skrisany already defined 'variables'.  If there is an error, NULL is returned.
268655714SkrisIf config is NULL, a new LHASH structure is created and returned, otherwise
268755714Skristhe new data in the 'file' is loaded into the 'config' structure.
268855714Skris
268955714Skrisvoid CONF_free(LHASH *config);
269055714SkrisThis function free()s the data in config.
269155714Skris
269255714Skrischar *CONF_get_string(LHASH *config,char *section,char *name);
269355714SkrisThis function returns the string found in 'config' that corresponds to the
269455714Skris'section' and 'name' specified.  Classes and the naming system used will be
269555714Skrisdiscussed later in this document.  If the variable is not defined, an NULL
269655714Skrisis returned.
269755714Skris
269855714Skrislong CONF_get_long(LHASH *config,char *section, char *name);
269955714SkrisThis function is the same as CONF_get_string() except that it converts the
270055714Skrisstring to an long and returns it.  If variable is not a number or the
270155714Skrisvariable does not exist, 0 is returned.  This is a little problematic but I
270255714Skrisdon't know of a simple way around it.
270355714Skris
270455714SkrisSTACK *CONF_get_section(LHASH *config, char *section);
270555714SkrisThis function returns a 'stack' of CONF_VALUE items that are all the
270655714Skrisitems defined in a particular section.  DO NOT free() any of the
270755714Skrisvariable returned.  They will disappear when CONF_free() is called.
270855714Skris
270955714SkrisThe 'lookup' model.
271055714SkrisThe configuration file is divided into 'sections'.  Each section is started by
271155714Skrisa line of the form '[ section ]'.  All subsequent variable definitions are
271255714Skrisof this section.  A variable definition is a simple alpha-numeric name
271355714Skrisfollowed by an '=' and then the data.  A section or variable name can be
271455714Skrisdescribed by a regular expression of the following form '[A-Za-z0-9_]+'.
271555714SkrisThe value of the variable is the text after the '=' until the end of the
271655714Skrisline, stripped of leading and trailing white space.
271755714SkrisAt this point I should mention that a '#' is a comment character, \ is the
271855714Skrisescape character, and all three types of quote can be used to stop any
271955714Skrisspecial interpretation of the data.
272055714SkrisNow when the data is being loaded, variable expansion can occur.  This is
272155714Skrisdone by expanding any $NAME sequences into the value represented by the
272255714Skrisvariable NAME.  If the variable is not in the current section, the different
272355714Skrissection can be specified by using the $SECTION::NAME form.  The ${NAME} form
272455714Skrisalso works and is very useful for expanding variables inside strings.
272555714Skris
272655714SkrisWhen a variable is looked up, there are 2 special section. 'default', which
272755714Skrisis the initial section, and 'ENV' which is the processes environment
272855714Skrisvariables (accessed via getenv()).  When a variable is looked up, it is
272955714Skrisfirst 'matched' with it's section (if one was specified), if this fails, the
273055714Skris'default' section is matched.
273155714SkrisIf the 'lhash' variable passed was NULL, the environment is searched.
273255714Skris
273355714SkrisNow why do we bother with sections?  So we can have multiple programs using
273455714Skristhe same configuration file, or multiple instances of the same program
273555714Skrisusing different variables.  It also provides a nice mechanism to override
273655714Skristhe processes environment variables (eg ENV::HOME=/tmp).  If there is a
273755714Skrisprogram specific variable missing, we can have default values.
273855714SkrisMultiple configuration files can be loaded, with each new value clearing
273955714Skrisany predefined values.  A system config file can provide 'default' values,
274055714Skrisand application/usr specific files can provide overriding values.
274155714Skris
274255714SkrisExamples
274355714Skris
274455714Skris# This is a simple example
274555714SkrisSSLEAY_HOME	= /usr/local/ssl
274655714SkrisENV::PATH	= $SSLEAY_HOME/bin:$PATH	# override my path
274755714Skris
274855714Skris[X509]
274955714Skriscert_dir	= $SSLEAY_HOME/certs	# /usr/local/ssl/certs
275055714Skris
275155714Skris[SSL]
275255714SkrisCIPHER		= DES-EDE-MD5:RC4-MD5
275355714SkrisUSER_CERT	= $HOME/${USER}di'r 5'	# /home/eay/eaydir 5
275455714SkrisUSER_CERT	= $HOME/\${USER}di\'r	# /home/eay/${USER}di'r
275555714SkrisUSER_CERT	= "$HOME/${US"ER}di\'r	# $HOME/${USER}di'r
275655714Skris
275755714SkrisTEST		= 1234\
275855714Skris5678\
275955714Skris9ab					# TEST=123456789ab
276055714SkrisTTT		= 1234\n\n		# TTT=1234<nl><nl>
276155714Skris
276255714Skris
276355714Skris
276455714Skris==== des.doc ========================================================
276555714Skris
276655714SkrisThe DES library.
276755714Skris
276855714SkrisPlease note that this library was originally written to operate with
276955714SkriseBones, a version of Kerberos that had had encryption removed when it left
277055714Skristhe USA and then put back in.  As such there are some routines that I will
277155714Skrisadvise not using but they are still in the library for historical reasons.
277255714SkrisFor all calls that have an 'input' and 'output' variables, they can be the
277355714Skrissame.
277455714Skris
277555714SkrisThis library requires the inclusion of 'des.h'.
277655714Skris
277755714SkrisAll of the encryption functions take what is called a des_key_schedule as an 
277855714Skrisargument.  A des_key_schedule is an expanded form of the des key.
277955714SkrisA des_key is 8 bytes of odd parity, the type used to hold the key is a
278055714Skrisdes_cblock.  A des_cblock is an array of 8 bytes, often in this library
278155714Skrisdescription I will refer to input bytes when the function specifies
278255714Skrisdes_cblock's as input or output, this just means that the variable should
278355714Skrisbe a multiple of 8 bytes.
278455714Skris
278555714SkrisThe define DES_ENCRYPT is passed to specify encryption, DES_DECRYPT to
278655714Skrisspecify decryption.  The functions and global variable are as follows:
278755714Skris
278855714Skrisint des_check_key;
278955714Skris	DES keys are supposed to be odd parity.  If this variable is set to
279055714Skris	a non-zero value, des_set_key() will check that the key has odd
279155714Skris	parity and is not one of the known weak DES keys.  By default this
279255714Skris	variable is turned off;
279355714Skris	
279455714Skrisvoid des_set_odd_parity(
279555714Skrisdes_cblock *key );
279655714Skris	This function takes a DES key (8 bytes) and sets the parity to odd.
279755714Skris	
279855714Skrisint des_is_weak_key(
279955714Skrisdes_cblock *key );
280055714Skris	This function returns a non-zero value if the DES key passed is a
280155714Skris	weak, DES key.  If it is a weak key, don't use it, try a different
280255714Skris	one.  If you are using 'random' keys, the chances of hitting a weak
280355714Skris	key are 1/2^52 so it is probably not worth checking for them.
280455714Skris	
280555714Skrisint des_set_key(
280655714Skrisdes_cblock *key,
280755714Skrisdes_key_schedule schedule);
280855714Skris	Des_set_key converts an 8 byte DES key into a des_key_schedule.
280955714Skris	A des_key_schedule is an expanded form of the key which is used to
281055714Skris	perform actual encryption.  It can be regenerated from the DES key
281155714Skris	so it only needs to be kept when encryption or decryption is about
281255714Skris	to occur.  Don't save or pass around des_key_schedule's since they
281355714Skris	are CPU architecture dependent, DES keys are not.  If des_check_key
281455714Skris	is non zero, zero is returned if the key has the wrong parity or
281555714Skris	the key is a weak key, else 1 is returned.
281655714Skris	
281755714Skrisint des_key_sched(
281855714Skrisdes_cblock *key,
281955714Skrisdes_key_schedule schedule);
282055714Skris	An alternative name for des_set_key().
282155714Skris
282255714Skrisint des_rw_mode;		/* defaults to DES_PCBC_MODE */
282355714Skris	This flag holds either DES_CBC_MODE or DES_PCBC_MODE (default).
282455714Skris	This specifies the function to use in the enc_read() and enc_write()
282555714Skris	functions.
282655714Skris
282755714Skrisvoid des_encrypt(
282855714Skrisunsigned long *data,
282955714Skrisdes_key_schedule ks,
283055714Skrisint enc);
283155714Skris	This is the DES encryption function that gets called by just about
283255714Skris	every other DES routine in the library.  You should not use this
283355714Skris	function except to implement 'modes' of DES.  I say this because the
283455714Skris	functions that call this routine do the conversion from 'char *' to
283555714Skris	long, and this needs to be done to make sure 'non-aligned' memory
283655714Skris	access do not occur.  The characters are loaded 'little endian',
283755714Skris	have a look at my source code for more details on how I use this
283855714Skris	function.
283955714Skris	Data is a pointer to 2 unsigned long's and ks is the
284055714Skris	des_key_schedule to use.  enc, is non zero specifies encryption,
284155714Skris	zero if decryption.
284255714Skris
284355714Skrisvoid des_encrypt2(
284455714Skrisunsigned long *data,
284555714Skrisdes_key_schedule ks,
284655714Skrisint enc);
284755714Skris	This functions is the same as des_encrypt() except that the DES
284855714Skris	initial permutation (IP) and final permutation (FP) have been left
284955714Skris	out.  As for des_encrypt(), you should not use this function.
285055714Skris	It is used by the routines in my library that implement triple DES.
285155714Skris	IP() des_encrypt2() des_encrypt2() des_encrypt2() FP() is the same
285255714Skris	as des_encrypt() des_encrypt() des_encrypt() except faster :-).
285355714Skris
285455714Skrisvoid des_ecb_encrypt(
285555714Skrisdes_cblock *input,
285655714Skrisdes_cblock *output,
285755714Skrisdes_key_schedule ks,
285855714Skrisint enc);
285955714Skris	This is the basic Electronic Code Book form of DES, the most basic
286055714Skris	form.  Input is encrypted into output using the key represented by
286155714Skris	ks.  If enc is non zero (DES_ENCRYPT), encryption occurs, otherwise
286255714Skris	decryption occurs.  Input is 8 bytes long and output is 8 bytes.
286355714Skris	(the des_cblock structure is 8 chars).
286455714Skris	
286555714Skrisvoid des_ecb3_encrypt(
286655714Skrisdes_cblock *input,
286755714Skrisdes_cblock *output,
286855714Skrisdes_key_schedule ks1,
286955714Skrisdes_key_schedule ks2,
287055714Skrisdes_key_schedule ks3,
287155714Skrisint enc);
287255714Skris	This is the 3 key EDE mode of ECB DES.  What this means is that 
287355714Skris	the 8 bytes of input is encrypted with ks1, decrypted with ks2 and
287455714Skris	then encrypted again with ks3, before being put into output;
287555714Skris	C=E(ks3,D(ks2,E(ks1,M))).  There is a macro, des_ecb2_encrypt()
287655714Skris	that only takes 2 des_key_schedules that implements,
287755714Skris	C=E(ks1,D(ks2,E(ks1,M))) in that the final encrypt is done with ks1.
287855714Skris	
287955714Skrisvoid des_cbc_encrypt(
288055714Skrisdes_cblock *input,
288155714Skrisdes_cblock *output,
288255714Skrislong length,
288355714Skrisdes_key_schedule ks,
288455714Skrisdes_cblock *ivec,
288555714Skrisint enc);
288655714Skris	This routine implements DES in Cipher Block Chaining mode.
288755714Skris	Input, which should be a multiple of 8 bytes is encrypted
288855714Skris	(or decrypted) to output which will also be a multiple of 8 bytes.
288955714Skris	The number of bytes is in length (and from what I've said above,
289055714Skris	should be a multiple of 8).  If length is not a multiple of 8, I'm
289155714Skris	not being held responsible :-).  ivec is the initialisation vector.
289255714Skris	This function does not modify this variable.  To correctly implement
289355714Skris	cbc mode, you need to do one of 2 things; copy the last 8 bytes of
289455714Skris	cipher text for use as the next ivec in your application,
289555714Skris	or use des_ncbc_encrypt(). 
289655714Skris	Only this routine has this problem with updating the ivec, all
289755714Skris	other routines that are implementing cbc mode update ivec.
289855714Skris	
289955714Skrisvoid des_ncbc_encrypt(
290055714Skrisdes_cblock *input,
290155714Skrisdes_cblock *output,
290255714Skrislong length,
290355714Skrisdes_key_schedule sk,
290455714Skrisdes_cblock *ivec,
290555714Skrisint enc);
290655714Skris	For historical reasons, des_cbc_encrypt() did not update the
290755714Skris	ivec with the value requires so that subsequent calls to
290855714Skris	des_cbc_encrypt() would 'chain'.  This was needed so that the same
290955714Skris	'length' values would not need to be used when decrypting.
291055714Skris	des_ncbc_encrypt() does the right thing.  It is the same as
291155714Skris	des_cbc_encrypt accept that ivec is updates with the correct value
291255714Skris	to pass in subsequent calls to des_ncbc_encrypt().  I advise using
291355714Skris	des_ncbc_encrypt() instead of des_cbc_encrypt();
291455714Skris
291555714Skrisvoid des_xcbc_encrypt(
291655714Skrisdes_cblock *input,
291755714Skrisdes_cblock *output,
291855714Skrislong length,
291955714Skrisdes_key_schedule sk,
292055714Skrisdes_cblock *ivec,
292155714Skrisdes_cblock *inw,
292255714Skrisdes_cblock *outw,
292355714Skrisint enc);
292455714Skris	This is RSA's DESX mode of DES.  It uses inw and outw to
292555714Skris	'whiten' the encryption.  inw and outw are secret (unlike the iv)
292655714Skris	and are as such, part of the key.  So the key is sort of 24 bytes.
292755714Skris	This is much better than cbc des.
292855714Skris	
292955714Skrisvoid des_3cbc_encrypt(
293055714Skrisdes_cblock *input,
293155714Skrisdes_cblock *output,
293255714Skrislong length,
293355714Skrisdes_key_schedule sk1,
293455714Skrisdes_key_schedule sk2,
293555714Skrisdes_cblock *ivec1,
293655714Skrisdes_cblock *ivec2,
293755714Skrisint enc);
293855714Skris	This function is flawed, do not use it.  I have left it in the
293955714Skris	library because it is used in my des(1) program and will function
294055714Skris	correctly when used by des(1).  If I removed the function, people
294155714Skris	could end up unable to decrypt files.
294255714Skris	This routine implements outer triple cbc encryption using 2 ks and
294355714Skris	2 ivec's.  Use des_ede2_cbc_encrypt() instead.
294455714Skris	
294555714Skrisvoid des_ede3_cbc_encrypt(
294655714Skrisdes_cblock *input,
294755714Skrisdes_cblock *output, 
294855714Skrislong length,
294955714Skrisdes_key_schedule ks1,
295055714Skrisdes_key_schedule ks2, 
295155714Skrisdes_key_schedule ks3, 
295255714Skrisdes_cblock *ivec,
295355714Skrisint enc);
295455714Skris	This function implements outer triple CBC DES encryption with 3
295555714Skris	keys.  What this means is that each 'DES' operation
295655714Skris	inside the cbc mode is really an C=E(ks3,D(ks2,E(ks1,M))).
295755714Skris	Again, this is cbc mode so an ivec is requires.
295855714Skris	This mode is used by SSL.
295955714Skris	There is also a des_ede2_cbc_encrypt() that only uses 2
296055714Skris	des_key_schedule's, the first being reused for the final
296155714Skris	encryption.  C=E(ks1,D(ks2,E(ks1,M))).  This form of triple DES
296255714Skris	is used by the RSAref library.
296355714Skris	
296455714Skrisvoid des_pcbc_encrypt(
296555714Skrisdes_cblock *input,
296655714Skrisdes_cblock *output,
296755714Skrislong length,
296855714Skrisdes_key_schedule ks,
296955714Skrisdes_cblock *ivec,
297055714Skrisint enc);
297155714Skris	This is Propagating Cipher Block Chaining mode of DES.  It is used
297255714Skris	by Kerberos v4.  It's parameters are the same as des_ncbc_encrypt().
297355714Skris	
297455714Skrisvoid des_cfb_encrypt(
297555714Skrisunsigned char *in,
297655714Skrisunsigned char *out,
297755714Skrisint numbits,
297855714Skrislong length,
297955714Skrisdes_key_schedule ks,
298055714Skrisdes_cblock *ivec,
298155714Skrisint enc);
298255714Skris	Cipher Feedback Back mode of DES.  This implementation 'feeds back'
298355714Skris	in numbit blocks.  The input (and output) is in multiples of numbits
298455714Skris	bits.  numbits should to be a multiple of 8 bits.  Length is the
298555714Skris	number of bytes input.  If numbits is not a multiple of 8 bits,
298655714Skris	the extra bits in the bytes will be considered padding.  So if
298755714Skris	numbits is 12, for each 2 input bytes, the 4 high bits of the
298855714Skris	second byte will be ignored.  So to encode 72 bits when using
298955714Skris	a numbits of 12 take 12 bytes.  To encode 72 bits when using
299055714Skris	numbits of 9 will take 16 bytes.  To encode 80 bits when using
299155714Skris	numbits of 16 will take 10 bytes. etc, etc.  This padding will
299255714Skris	apply to both input and output.
299355714Skris
299455714Skris	
299555714Skrisvoid des_cfb64_encrypt(
299655714Skrisunsigned char *in,
299755714Skrisunsigned char *out,
299855714Skrislong length,
299955714Skrisdes_key_schedule ks,
300055714Skrisdes_cblock *ivec,
300155714Skrisint *num,
300255714Skrisint enc);
300355714Skris	This is one of the more useful functions in this DES library, it
300455714Skris	implements CFB mode of DES with 64bit feedback.  Why is this
300555714Skris	useful you ask?  Because this routine will allow you to encrypt an
300655714Skris	arbitrary number of bytes, no 8 byte padding.  Each call to this
300755714Skris	routine will encrypt the input bytes to output and then update ivec
300855714Skris	and num.  num contains 'how far' we are though ivec.  If this does
300955714Skris	not make much sense, read more about cfb mode of DES :-).
301055714Skris	
301155714Skrisvoid des_ede3_cfb64_encrypt(
301255714Skrisunsigned char *in,
301355714Skrisunsigned char *out,
301455714Skrislong length,
301555714Skrisdes_key_schedule ks1,
301655714Skrisdes_key_schedule ks2,
301755714Skrisdes_key_schedule ks3,
301855714Skrisdes_cblock *ivec,
301955714Skrisint *num,
302055714Skrisint enc);
302155714Skris	Same as des_cfb64_encrypt() accept that the DES operation is
302255714Skris	triple DES.  As usual, there is a macro for
302355714Skris	des_ede2_cfb64_encrypt() which reuses ks1.
302455714Skris
302555714Skrisvoid des_ofb_encrypt(
302655714Skrisunsigned char *in,
302755714Skrisunsigned char *out,
302855714Skrisint numbits,
302955714Skrislong length,
303055714Skrisdes_key_schedule ks,
303155714Skrisdes_cblock *ivec);
303255714Skris	This is a implementation of Output Feed Back mode of DES.  It is
303355714Skris	the same as des_cfb_encrypt() in that numbits is the size of the
303455714Skris	units dealt with during input and output (in bits).
303555714Skris	
303655714Skrisvoid des_ofb64_encrypt(
303755714Skrisunsigned char *in,
303855714Skrisunsigned char *out,
303955714Skrislong length,
304055714Skrisdes_key_schedule ks,
304155714Skrisdes_cblock *ivec,
304255714Skrisint *num);
304355714Skris	The same as des_cfb64_encrypt() except that it is Output Feed Back
304455714Skris	mode.
304555714Skris
304655714Skrisvoid des_ede3_ofb64_encrypt(
304755714Skrisunsigned char *in,
304855714Skrisunsigned char *out,
304955714Skrislong length,
305055714Skrisdes_key_schedule ks1,
305155714Skrisdes_key_schedule ks2,
305255714Skrisdes_key_schedule ks3,
305355714Skrisdes_cblock *ivec,
305455714Skrisint *num);
305555714Skris	Same as des_ofb64_encrypt() accept that the DES operation is
305655714Skris	triple DES.  As usual, there is a macro for
305755714Skris	des_ede2_ofb64_encrypt() which reuses ks1.
305855714Skris
305955714Skrisint des_read_pw_string(
306055714Skrischar *buf,
306155714Skrisint length,
306255714Skrischar *prompt,
306355714Skrisint verify);
306455714Skris	This routine is used to get a password from the terminal with echo
306555714Skris	turned off.  Buf is where the string will end up and length is the
306655714Skris	size of buf.  Prompt is a string presented to the 'user' and if
306755714Skris	verify is set, the key is asked for twice and unless the 2 copies
306855714Skris	match, an error is returned.  A return code of -1 indicates a
306955714Skris	system error, 1 failure due to use interaction, and 0 is success.
307055714Skris
307155714Skrisunsigned long des_cbc_cksum(
307255714Skrisdes_cblock *input,
307355714Skrisdes_cblock *output,
307455714Skrislong length,
307555714Skrisdes_key_schedule ks,
307655714Skrisdes_cblock *ivec);
307755714Skris	This function produces an 8 byte checksum from input that it puts in
307855714Skris	output and returns the last 4 bytes as a long.  The checksum is
307955714Skris	generated via cbc mode of DES in which only the last 8 byes are
308055714Skris	kept.  I would recommend not using this function but instead using
308155714Skris	the EVP_Digest routines, or at least using MD5 or SHA.  This
308255714Skris	function is used by Kerberos v4 so that is why it stays in the
308355714Skris	library.
308455714Skris	
308555714Skrischar *des_fcrypt(
308655714Skrisconst char *buf,
308755714Skrisconst char *salt
308855714Skrischar *ret);
308955714Skris	This is my fast version of the unix crypt(3) function.  This version
309055714Skris	takes only a small amount of space relative to other fast
309155714Skris	crypt() implementations.  This is different to the normal crypt
309255714Skris	in that the third parameter is the buffer that the return value
309355714Skris	is written into.  It needs to be at least 14 bytes long.  This
309455714Skris	function is thread safe, unlike the normal crypt.
309555714Skris
309655714Skrischar *crypt(
309755714Skrisconst char *buf,
309855714Skrisconst char *salt);
309955714Skris	This function calls des_fcrypt() with a static array passed as the
310055714Skris	third parameter.  This emulates the normal non-thread safe semantics
310155714Skris	of crypt(3).
310255714Skris
310355714Skrisvoid des_string_to_key(
310455714Skrischar *str,
310555714Skrisdes_cblock *key);
310655714Skris	This function takes str and converts it into a DES key.  I would
310755714Skris	recommend using MD5 instead and use the first 8 bytes of output.
310855714Skris	When I wrote the first version of these routines back in 1990, MD5
310955714Skris	did not exist but I feel these routines are still sound.  This
311055714Skris	routines is compatible with the one in MIT's libdes.
311155714Skris	
311255714Skrisvoid des_string_to_2keys(
311355714Skrischar *str,
311455714Skrisdes_cblock *key1,
311555714Skrisdes_cblock *key2);
311655714Skris	This function takes str and converts it into 2 DES keys.
311755714Skris	I would recommend using MD5 and using the 16 bytes as the 2 keys.
311855714Skris	I have nothing against these 2 'string_to_key' routines, it's just
311955714Skris	that if you say that your encryption key is generated by using the
312055714Skris	16 bytes of an MD5 hash, every-one knows how you generated your
312155714Skris	keys.
312255714Skris
312355714Skrisint des_read_password(
312455714Skrisdes_cblock *key,
312555714Skrischar *prompt,
312655714Skrisint verify);
312755714Skris	This routine combines des_read_pw_string() with des_string_to_key().
312855714Skris
312955714Skrisint des_read_2passwords(
313055714Skrisdes_cblock *key1,
313155714Skrisdes_cblock *key2,
313255714Skrischar *prompt,
313355714Skrisint verify);
313455714Skris	This routine combines des_read_pw_string() with des_string_to_2key().
313555714Skris
313655714Skrisvoid des_random_seed(
313755714Skrisdes_cblock key);
313855714Skris	This routine sets a starting point for des_random_key().
313955714Skris	
314055714Skrisvoid des_random_key(
314155714Skrisdes_cblock ret);
314255714Skris	This function return a random key.  Make sure to 'seed' the random
314355714Skris	number generator (with des_random_seed()) before using this function.
314455714Skris	I personally now use a MD5 based random number system.
314555714Skris
314655714Skrisint des_enc_read(
314755714Skrisint fd,
314855714Skrischar *buf,
314955714Skrisint len,
315055714Skrisdes_key_schedule ks,
315155714Skrisdes_cblock *iv);
315255714Skris	This function will write to a file descriptor the encrypted data
315355714Skris	from buf.  This data will be preceded by a 4 byte 'byte count' and
315455714Skris	will be padded out to 8 bytes.  The encryption is either CBC of
315555714Skris	PCBC depending on the value of des_rw_mode.  If it is DES_PCBC_MODE,
315655714Skris	pcbc is used, if DES_CBC_MODE, cbc is used.  The default is to use
315755714Skris	DES_PCBC_MODE.
315855714Skris
315955714Skrisint des_enc_write(
316055714Skrisint fd,
316155714Skrischar *buf,
316255714Skrisint len,
316355714Skrisdes_key_schedule ks,
316455714Skrisdes_cblock *iv);
316555714Skris	This routines read stuff written by des_enc_read() and decrypts it.
316655714Skris	I have used these routines quite a lot but I don't believe they are
316755714Skris	suitable for non-blocking io.  If you are after a full
316855714Skris	authentication/encryption over networks, have a look at SSL instead.
316955714Skris
317055714Skrisunsigned long des_quad_cksum(
317155714Skrisdes_cblock *input,
317255714Skrisdes_cblock *output,
317355714Skrislong length,
317455714Skrisint out_count,
317555714Skrisdes_cblock *seed);
317655714Skris	This is a function from Kerberos v4 that is not anything to do with
317755714Skris	DES but was needed.  It is a cksum that is quicker to generate than
317855714Skris	des_cbc_cksum();  I personally would use MD5 routines now.
317955714Skris=====
318055714SkrisModes of DES
318155714SkrisQuite a bit of the following information has been taken from
318255714Skris	AS 2805.5.2
318355714Skris	Australian Standard
318455714Skris	Electronic funds transfer - Requirements for interfaces,
318555714Skris	Part 5.2: Modes of operation for an n-bit block cipher algorithm
318655714Skris	Appendix A
318755714Skris
318855714SkrisThere are several different modes in which DES can be used, they are
318955714Skrisas follows.
319055714Skris
319155714SkrisElectronic Codebook Mode (ECB) (des_ecb_encrypt())
319255714Skris- 64 bits are enciphered at a time.
319355714Skris- The order of the blocks can be rearranged without detection.
319455714Skris- The same plaintext block always produces the same ciphertext block
319555714Skris  (for the same key) making it vulnerable to a 'dictionary attack'.
319655714Skris- An error will only affect one ciphertext block.
319755714Skris
319855714SkrisCipher Block Chaining Mode (CBC) (des_cbc_encrypt())
319955714Skris- a multiple of 64 bits are enciphered at a time.
320055714Skris- The CBC mode produces the same ciphertext whenever the same
320155714Skris  plaintext is encrypted using the same key and starting variable.
320255714Skris- The chaining operation makes the ciphertext blocks dependent on the
320355714Skris  current and all preceding plaintext blocks and therefore blocks can not
320455714Skris  be rearranged.
320555714Skris- The use of different starting variables prevents the same plaintext
320655714Skris  enciphering to the same ciphertext.
320755714Skris- An error will affect the current and the following ciphertext blocks.
320855714Skris
320955714SkrisCipher Feedback Mode (CFB) (des_cfb_encrypt())
321055714Skris- a number of bits (j) <= 64 are enciphered at a time.
321155714Skris- The CFB mode produces the same ciphertext whenever the same
321255714Skris  plaintext is encrypted using the same key and starting variable.
321355714Skris- The chaining operation makes the ciphertext variables dependent on the
321455714Skris  current and all preceding variables and therefore j-bit variables are
321555714Skris  chained together and can not be rearranged.
321655714Skris- The use of different starting variables prevents the same plaintext
321755714Skris  enciphering to the same ciphertext.
321855714Skris- The strength of the CFB mode depends on the size of k (maximal if
321955714Skris  j == k).  In my implementation this is always the case.
322055714Skris- Selection of a small value for j will require more cycles through
322155714Skris  the encipherment algorithm per unit of plaintext and thus cause
322255714Skris  greater processing overheads.
322355714Skris- Only multiples of j bits can be enciphered.
322455714Skris- An error will affect the current and the following ciphertext variables.
322555714Skris
322655714SkrisOutput Feedback Mode (OFB) (des_ofb_encrypt())
322755714Skris- a number of bits (j) <= 64 are enciphered at a time.
322855714Skris- The OFB mode produces the same ciphertext whenever the same
322955714Skris  plaintext enciphered using the same key and starting variable.  More
323055714Skris  over, in the OFB mode the same key stream is produced when the same
323155714Skris  key and start variable are used.  Consequently, for security reasons
323255714Skris  a specific start variable should be used only once for a given key.
323355714Skris- The absence of chaining makes the OFB more vulnerable to specific attacks.
323455714Skris- The use of different start variables values prevents the same
323555714Skris  plaintext enciphering to the same ciphertext, by producing different
323655714Skris  key streams.
323755714Skris- Selection of a small value for j will require more cycles through
323855714Skris  the encipherment algorithm per unit of plaintext and thus cause
323955714Skris  greater processing overheads.
324055714Skris- Only multiples of j bits can be enciphered.
324155714Skris- OFB mode of operation does not extend ciphertext errors in the
324255714Skris  resultant plaintext output.  Every bit error in the ciphertext causes
324355714Skris  only one bit to be in error in the deciphered plaintext.
324455714Skris- OFB mode is not self-synchronising.  If the two operation of
324555714Skris  encipherment and decipherment get out of synchronism, the system needs
324655714Skris  to be re-initialised.
324755714Skris- Each re-initialisation should use a value of the start variable
324855714Skris different from the start variable values used before with the same
324955714Skris key.  The reason for this is that an identical bit stream would be
325055714Skris produced each time from the same parameters.  This would be
325155714Skris susceptible to a ' known plaintext' attack.
325255714Skris
325355714SkrisTriple ECB Mode (des_ecb3_encrypt())
325455714Skris- Encrypt with key1, decrypt with key2 and encrypt with key3 again.
325555714Skris- As for ECB encryption but increases the key length to 168 bits.
325655714Skris  There are theoretic attacks that can be used that make the effective
325755714Skris  key length 112 bits, but this attack also requires 2^56 blocks of
325855714Skris  memory, not very likely, even for the NSA.
325955714Skris- If both keys are the same it is equivalent to encrypting once with
326055714Skris  just one key.
326155714Skris- If the first and last key are the same, the key length is 112 bits.
326255714Skris  There are attacks that could reduce the key space to 55 bit's but it
326355714Skris  requires 2^56 blocks of memory.
326455714Skris- If all 3 keys are the same, this is effectively the same as normal
326555714Skris  ecb mode.
326655714Skris
326755714SkrisTriple CBC Mode (des_ede3_cbc_encrypt())
326855714Skris- Encrypt with key1, decrypt with key2 and then encrypt with key3.
326955714Skris- As for CBC encryption but increases the key length to 168 bits with
327055714Skris  the same restrictions as for triple ecb mode.
327155714Skris
327255714Skris==== digest.doc ========================================================
327355714Skris
327455714Skris
327555714SkrisThe Message Digest subroutines.
327655714Skris
327755714SkrisThese routines require "evp.h" to be included.
327855714Skris
327955714SkrisThese functions are a higher level interface to the various message digest
328055714Skrisroutines found in this library.  As such, they allow the same code to be
328155714Skrisused to digest via different algorithms with only a change in an initial
328255714Skrisparameter.  They are basically just a front-end to the MD2, MD5, SHA
328355714Skrisand SHA1
328455714Skrisroutines.
328555714Skris
328655714SkrisThese routines all take a pointer to the following structure to specify
328755714Skriswhich message digest algorithm to use.
328855714Skristypedef struct evp_md_st
328955714Skris	{
329055714Skris	int type;
329155714Skris	int pkey_type;
329255714Skris	int md_size;
329355714Skris	void (*init)();
329455714Skris	void (*update)();
329555714Skris	void (*final)();
329655714Skris
329755714Skris	int required_pkey_type; /*EVP_PKEY_xxx */
329855714Skris	int (*sign)();
329955714Skris	int (*verify)();
330055714Skris	} EVP_MD;
330155714Skris
330255714SkrisIf additional message digest algorithms are to be supported, a structure of
330355714Skristhis type needs to be declared and populated and then the Digest routines
330455714Skriscan be used with that algorithm.  The type field is the object NID of the
330555714Skrisdigest type (read the section on Objects for an explanation).  The pkey_type
330655714Skrisis the Object type to use when the a message digest is generated by there
330755714Skrisroutines and then is to be signed with the pkey algorithm.  Md_size is
330855714Skristhe size of the message digest returned.  Init, update
330955714Skrisand final are the relevant functions to perform the message digest function
331055714Skrisby parts.  One reason for specifying the message digest to use via this
331155714Skrismechanism is that if you only use md5, only the md5 routines will
331255714Skrisbe included in you linked program.  If you passed an integer
331355714Skristhat specified which message digest to use, the routine that mapped that
331455714Skrisinteger to a set of message digest functions would cause all the message
331555714Skrisdigests functions to be link into the code.  This setup also allows new
331655714Skrismessage digest functions to be added by the application.
331755714Skris
331855714SkrisThe six message digests defined in this library are
331955714Skris
332055714SkrisEVP_MD *EVP_md2(void);	/* RSA sign/verify */
332155714SkrisEVP_MD *EVP_md5(void);	/* RSA sign/verify */
332255714SkrisEVP_MD *EVP_sha(void);	/* RSA sign/verify */
332355714SkrisEVP_MD *EVP_sha1(void);	/* RSA sign/verify */
332455714SkrisEVP_MD *EVP_dss(void);	/* DSA sign/verify */
332555714SkrisEVP_MD *EVP_dss1(void);	/* DSA sign/verify */
332655714Skris
332755714SkrisAll the message digest routines take a EVP_MD_CTX pointer as an argument.
332855714SkrisThe state of the message digest is kept in this structure.
332955714Skris
333055714Skristypedef struct pem_md_ctx_st
333155714Skris	{
333255714Skris	EVP_MD *digest;
333355714Skris	union	{
333455714Skris		unsigned char base[4]; /* this is used in my library as a
333555714Skris					* 'pointer' to all union elements
333655714Skris					* structures. */
333755714Skris		MD2_CTX md2;
333855714Skris		MD5_CTX md5;
333955714Skris		SHA_CTX sha;
334055714Skris		} md;
334155714Skris	} EVP_MD_CTX;
334255714Skris
334355714SkrisThe Digest functions are as follows.
334455714Skris
334555714Skrisvoid EVP_DigestInit(
334655714SkrisEVP_MD_CTX *ctx,
334755714SkrisEVP_MD *type);
334855714Skris	This function is used to initialise the EVP_MD_CTX.  The message
334955714Skris	digest that will associated with 'ctx' is specified by 'type'.
335055714Skris
335155714Skrisvoid EVP_DigestUpdate(
335255714SkrisEVP_MD_CTX *ctx,
335355714Skrisunsigned char *data,
335455714Skrisunsigned int cnt);
335555714Skris	This function is used to pass more data to the message digest
335655714Skris	function.  'cnt' bytes are digested from 'data'.
335755714Skris
335855714Skrisvoid EVP_DigestFinal(
335955714SkrisEVP_MD_CTX *ctx,
336055714Skrisunsigned char *md,
336155714Skrisunsigned int *len);
336255714Skris	This function finishes the digestion and puts the message digest
336355714Skris	into 'md'.  The length of the message digest is put into len;
336455714Skris	EVP_MAX_MD_SIZE is the size of the largest message digest that
336555714Skris	can be returned from this function.  Len can be NULL if the
336655714Skris	size of the digest is not required.
336755714Skris	
336855714Skris
336955714Skris==== encode.doc ========================================================
337055714Skris
337155714Skris
337255714Skrisvoid    EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
337355714Skrisvoid    EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,
337455714Skris		int *outl,unsigned char *in,int inl);
337555714Skrisvoid    EVP_EncodeFinal(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl);
337655714Skrisint     EVP_EncodeBlock(unsigned char *t, unsigned char *f, int n);
337755714Skris
337855714Skrisvoid    EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
337955714Skrisint     EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
338055714Skris		unsigned char *in, int inl);
338155714Skrisint     EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
338255714Skris		char *out, int *outl);
338355714Skrisint     EVP_DecodeBlock(unsigned char *t, unsigned
338455714Skris		char *f, int n);
338555714Skris
338655714Skris
338755714Skris==== envelope.doc ========================================================
338855714Skris
338955714SkrisThe following routines are use to create 'digital' envelopes.
339055714SkrisBy this I mean that they perform various 'higher' level cryptographic
339155714Skrisfunctions.  Have a read of 'cipher.doc' and 'digest.doc' since those
339255714Skrisroutines are used by these functions.
339355714Skriscipher.doc contains documentation about the cipher part of the
339455714Skrisenvelope library and digest.doc contatins the description of the
339555714Skrismessage digests supported.
339655714Skris
339755714SkrisTo 'sign' a document involves generating a message digest and then encrypting
339855714Skristhe digest with an private key.
339955714Skris
340055714Skris#define EVP_SignInit(a,b)		EVP_DigestInit(a,b)
340155714Skris#define EVP_SignUpdate(a,b,c)		EVP_DigestUpdate(a,b,c)
340255714SkrisDue to the fact this operation is basically just an extended message
340355714Skrisdigest, the first 2 functions are macro calls to Digest generating
340455714Skrisfunctions.
340555714Skris
340655714Skrisint     EVP_SignFinal(
340755714SkrisEVP_MD_CTX *ctx,
340855714Skrisunsigned char *md,
340955714Skrisunsigned int *s,
341055714SkrisEVP_PKEY *pkey);
341155714Skris	This finalisation function finishes the generation of the message
341255714Skrisdigest and then encrypts the digest (with the correct message digest 
341355714Skrisobject identifier) with the EVP_PKEY private key.  'ctx' is the message digest
341455714Skriscontext.  'md' will end up containing the encrypted message digest.  This
341555714Skrisarray needs to be EVP_PKEY_size(pkey) bytes long.  's' will actually
341655714Skriscontain the exact length.  'pkey' of course is the private key.  It is
341755714Skrisone of EVP_PKEY_RSA or EVP_PKEY_DSA type.
341855714SkrisIf there is an error, 0 is returned, otherwise 1.
341955714Skris		
342055714SkrisVerify is used to check an signed message digest.
342155714Skris
342255714Skris#define EVP_VerifyInit(a,b)		EVP_DigestInit(a,b)
342355714Skris#define EVP_VerifyUpdate(a,b,c)		EVP_DigestUpdate(a,b,c)
342455714SkrisSince the first step is to generate a message digest, the first 2 functions
342555714Skrisare macros.
342655714Skris
342755714Skrisint EVP_VerifyFinal(
342855714SkrisEVP_MD_CTX *ctx,
342955714Skrisunsigned char *md,
343055714Skrisunsigned int s,
343155714SkrisEVP_PKEY *pkey);
343255714Skris	This function finishes the generation of the message digest and then
343355714Skriscompares it with the supplied encrypted message digest.  'md' contains the
343455714Skris's' bytes of encrypted message digest.  'pkey' is used to public key decrypt
343555714Skristhe digest.  It is then compared with the message digest just generated.
343655714SkrisIf they match, 1 is returned else 0.
343755714Skris
343855714Skrisint	EVP_SealInit(EVP_CIPHER_CTX *ctx, EVP_CIPHER *type, unsigned char **ek,
343955714Skris		int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk);
344055714SkrisMust have at least one public key, error is 0.  I should also mention that
344155714Skristhe buffers pointed to by 'ek' need to be EVP_PKEY_size(pubk[n]) is size.
344255714Skris
344355714Skris#define EVP_SealUpdate(a,b,c,d,e)	EVP_EncryptUpdate(a,b,c,d,e)	
344455714Skrisvoid	EVP_SealFinal(EVP_CIPHER_CTX *ctx,unsigned char *out,int *outl);
344555714Skris
344655714Skris
344755714Skrisint	EVP_OpenInit(EVP_CIPHER_CTX *ctx,EVP_CIPHER *type,unsigned char *ek,
344855714Skris		int ekl,unsigned char *iv,EVP_PKEY *priv);
344955714Skris0 on failure
345055714Skris
345155714Skris#define EVP_OpenUpdate(a,b,c,d,e)	EVP_DecryptUpdate(a,b,c,d,e)
345255714Skris
345355714Skrisint	EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
345455714SkrisDecrypt final return code
345555714Skris
345655714Skris
345755714Skris==== error.doc ========================================================
345855714Skris
345955714SkrisThe error routines.
346055714Skris
346155714SkrisThe 'error' system I've implemented is intended to server 2 purpose, to
346255714Skrisrecord the reason why a command failed and to record where in the libraries
346355714Skristhe failure occurred.  It is more or less setup to record a 'trace' of which
346455714Skrislibrary components were being traversed when the error occurred.
346555714Skris
346655714SkrisWhen an error is recorded, it is done so a as single unsigned long which is
346755714Skriscomposed of three parts.  The top byte is the 'library' number, the middle
346855714Skris12 bytes is the function code, and the bottom 12 bits is the 'reason' code.
346955714Skris
347055714SkrisEach 'library', or should a say, 'section' of the SSLeay library has a
347155714Skrisdifferent unique 'library' error number.  Each function in the library has
347255714Skrisa number that is unique for that library.  Each 'library' also has a number
347355714Skrisfor each 'error reason' that is only unique for that 'library'.
347455714Skris
347555714SkrisDue to the way these error routines record a 'error trace', there is an
347655714Skrisarray per thread that is used to store the error codes.
347755714SkrisThe various functions in this library are used to access
347855714Skrisand manipulate this array.
347955714Skris
348055714Skrisvoid ERR_put_error(int lib, int func,int reason);
348155714Skris	This routine records an error in library 'lib', function 'func'
348255714Skrisand reason 'reason'.  As errors get 'put' into the buffer, they wrap
348355714Skrisaround and overwrite old errors if too many are written.  It is assumed
348455714Skristhat the last errors are the most important.
348555714Skris
348655714Skrisunsigned long ERR_get_error(void );
348755714Skris	This function returns the last error added to the error buffer.
348855714SkrisIn effect it is popping the value off the buffer so repeated calls will
348955714Skriscontinue to return values until there are no more errors to return in which
349055714Skriscase 0 is returned.
349155714Skris
349255714Skrisunsigned long ERR_peek_error(void );
349355714Skris	This function returns the value of the last error added to the
349455714Skriserror buffer but does not 'pop' it from the buffer.
349555714Skris
349655714Skrisvoid ERR_clear_error(void );
349755714Skris	This function clears the error buffer, discarding all unread
349855714Skriserrors.
349955714Skris
350055714SkrisWhile the above described error system obviously produces lots of different
350155714Skriserror number, a method for 'reporting' these errors in a human readable
350255714Skrisform is required.  To achieve this, each library has the option of
350355714Skris'registering' error strings.
350455714Skris
350555714Skristypedef struct ERR_string_data_st
350655714Skris	{
350755714Skris	unsigned long error;
350855714Skris	char *string;
350955714Skris	} ERR_STRING_DATA;
351055714Skris
351155714SkrisThe 'ERR_STRING_DATA' contains an error code and the corresponding text
351255714Skrisstring.  To add new function error strings for a library, the
351355714SkrisERR_STRING_DATA needs to be 'registered' with the library.
351455714Skris
351555714Skrisvoid ERR_load_strings(unsigned long lib,ERR_STRING_DATA *err);
351655714Skris	This function 'registers' the array of ERR_STRING_DATA pointed to by
351755714Skris'err' as error text strings for the error library 'lib'.
351855714Skris
351955714Skrisvoid ERR_free_strings(void);
352055714Skris	This function free()s all the loaded error strings.
352155714Skris
352255714Skrischar *ERR_error_string(unsigned long error,char *buf);
352355714Skris	This function returns a text string that is a human readable
352455714Skrisversion of the error represented by 'error'.  Buff should be at least 120
352555714Skrisbytes long and if it is NULL, the return value is a pointer to a static
352655714Skrisvariable that will contain the error string, otherwise 'buf' is returned.
352755714SkrisIf there is not a text string registered for a particular error, a text
352855714Skrisstring containing the error number is returned instead.
352955714Skris
353055714Skrisvoid ERR_print_errors(BIO *bp);
353155714Skrisvoid ERR_print_errors_fp(FILE *fp);
353255714Skris	This function is a convenience routine that prints the error string
353355714Skrisfor each error until all errors have been accounted for.
353455714Skris
353555714Skrischar *ERR_lib_error_string(unsigned long e);
353655714Skrischar *ERR_func_error_string(unsigned long e);
353755714Skrischar *ERR_reason_error_string(unsigned long e);
353855714SkrisThe above three functions return the 3 different components strings for the
353955714Skriserror 'e'.  ERR_error_string() uses these functions.
354055714Skris
354155714Skrisvoid ERR_load_ERR_strings(void );
354255714Skris	This function 'registers' the error strings for the 'ERR' module.
354355714Skris
354455714Skrisvoid ERR_load_crypto_strings(void );
354555714Skris	This function 'register' the error strings for just about every
354655714Skrislibrary in the SSLeay package except for the SSL routines.  There is no
354755714Skrisneed to ever register any error text strings and you will probably save in
354855714Skrisprogram size.  If on the other hand you do 'register' all errors, it is
354955714Skrisquite easy to determine why a particular routine failed.
355055714Skris
355155714SkrisAs a final footnote as to why the error system is designed as it is.
355255714Skris1) I did not want a single 'global' error code.
355355714Skris2) I wanted to know which subroutine a failure occurred in.
355455714Skris3) For Windows NT etc, it should be simple to replace the 'key' routines
355555714Skris   with code to pass error codes back to the application.
355655714Skris4) I wanted the option of meaningful error text strings.
355755714Skris
355855714SkrisLate breaking news - the changes to support threads.
355955714Skris
356055714SkrisEach 'thread' has an 'ERR_STATE' state associated with it.
356155714SkrisERR_STATE *ERR_get_state(void ) will return the 'state' for the calling
356255714Skristhread/process.
356355714Skris
356455714SkrisERR_remove_state(unsigned long pid); will 'free()' this state.  If pid == 0
356555714Skristhe current 'thread/process' will have it's error state removed.
356655714SkrisIf you do not remove the error state of a thread, this could be considered a
356755714Skrisform of memory leak, so just after 'reaping' a thread that has died,
356855714Skriscall ERR_remove_state(pid).
356955714Skris
357055714SkrisHave a read of thread.doc for more details for what is required for
357155714Skrismulti-threading support.  All the other error routines will
357255714Skriswork correctly when using threads.
357355714Skris
357455714Skris
357555714Skris==== idea.doc ========================================================
357655714Skris
357755714SkrisThe IDEA library.
357855714SkrisIDEA is a block cipher that operates on 64bit (8 byte) quantities.  It
357955714Skrisuses a 128bit (16 byte) key.  It can be used in all the modes that DES can
358055714Skrisbe used.  This library implements the ecb, cbc, cfb64 and ofb64 modes.
358155714Skris
358255714SkrisFor all calls that have an 'input' and 'output' variables, they can be the
358355714Skrissame.
358455714Skris
358555714SkrisThis library requires the inclusion of 'idea.h'.
358655714Skris
358755714SkrisAll of the encryption functions take what is called an IDEA_KEY_SCHEDULE as an 
358855714Skrisargument.  An IDEA_KEY_SCHEDULE is an expanded form of the idea key.
358955714SkrisFor all modes of the IDEA algorithm, the IDEA_KEY_SCHEDULE used for
359055714Skrisdecryption is different to the one used for encryption.
359155714Skris
359255714SkrisThe define IDEA_ENCRYPT is passed to specify encryption for the functions
359355714Skristhat require an encryption/decryption flag. IDEA_DECRYPT is passed to
359455714Skrisspecify decryption.  For some mode there is no encryption/decryption
359555714Skrisflag since this is determined by the IDEA_KEY_SCHEDULE.
359655714Skris
359755714SkrisSo to encrypt you would do the following
359855714Skrisidea_set_encrypt_key(key,encrypt_ks);
359955714Skrisidea_ecb_encrypt(...,encrypt_ks);
360055714Skrisidea_cbc_encrypt(....,encrypt_ks,...,IDEA_ENCRYPT);
360155714Skris
360255714SkrisTo Decrypt
360355714Skrisidea_set_encrypt_key(key,encrypt_ks);
360455714Skrisidea_set_decrypt_key(encrypt_ks,decrypt_ks);
360555714Skrisidea_ecb_encrypt(...,decrypt_ks);
360655714Skrisidea_cbc_encrypt(....,decrypt_ks,...,IDEA_DECRYPT);
360755714Skris
360855714SkrisPlease note that any of the encryption modes specified in my DES library
360955714Skriscould be used with IDEA.  I have only implemented ecb, cbc, cfb64 and
361055714Skrisofb64 for the following reasons.
361155714Skris- ecb is the basic IDEA encryption.
361255714Skris- cbc is the normal 'chaining' form for block ciphers.
361355714Skris- cfb64 can be used to encrypt single characters, therefore input and output
361455714Skris  do not need to be a multiple of 8.
361555714Skris- ofb64 is similar to cfb64 but is more like a stream cipher, not as
361655714Skris  secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
361755714Skris- If you want triple IDEA, thats 384 bits of key and you must be totally
361855714Skris  obsessed with security.  Still, if you want it, it is simple enough to
361955714Skris  copy the function from the DES library and change the des_encrypt to
362055714Skris  idea_encrypt; an exercise left for the paranoid reader :-).
362155714Skris
362255714SkrisThe functions are as follows:
362355714Skris
362455714Skrisvoid idea_set_encrypt_key(
362555714Skrisunsigned char *key;
362655714SkrisIDEA_KEY_SCHEDULE *ks);
362755714Skris	idea_set_encrypt_key converts a 16 byte IDEA key into an
362855714Skris	IDEA_KEY_SCHEDULE.  The IDEA_KEY_SCHEDULE is an expanded form of
362955714Skris	the key which can be used to perform IDEA encryption.
363055714Skris	An IDEA_KEY_SCHEDULE is an expanded form of the key which is used to
363155714Skris	perform actual encryption.  It can be regenerated from the IDEA key
363255714Skris	so it only needs to be kept when encryption is about
363355714Skris	to occur.  Don't save or pass around IDEA_KEY_SCHEDULE's since they
363455714Skris	are CPU architecture dependent, IDEA keys are not.
363555714Skris	
363655714Skrisvoid idea_set_decrypt_key(
363755714SkrisIDEA_KEY_SCHEDULE *encrypt_ks,
363855714SkrisIDEA_KEY_SCHEDULE *decrypt_ks);
363955714Skris	This functions converts an encryption IDEA_KEY_SCHEDULE into a
364055714Skris	decryption IDEA_KEY_SCHEDULE.  For all decryption, this conversion
364155714Skris	of the key must be done.  In some modes of IDEA, an
364255714Skris	encryption/decryption flag is also required, this is because these
364355714Skris	functions involve block chaining and the way this is done changes
364455714Skris	depending on which of encryption of decryption is being done.
364555714Skris	Please note that there is no quick way to generate the decryption
364655714Skris	key schedule other than generating the encryption key schedule and
364755714Skris	then converting it.
364855714Skris
364955714Skrisvoid idea_encrypt(
365055714Skrisunsigned long *data,
365155714SkrisIDEA_KEY_SCHEDULE *ks);
365255714Skris	This is the IDEA encryption function that gets called by just about
365355714Skris	every other IDEA routine in the library.  You should not use this
365455714Skris	function except to implement 'modes' of IDEA.  I say this because the
365555714Skris	functions that call this routine do the conversion from 'char *' to
365655714Skris	long, and this needs to be done to make sure 'non-aligned' memory
365755714Skris	access do not occur.
365855714Skris	Data is a pointer to 2 unsigned long's and ks is the
365955714Skris	IDEA_KEY_SCHEDULE to use.  Encryption or decryption depends on the
366055714Skris	IDEA_KEY_SCHEDULE.
366155714Skris
366255714Skrisvoid idea_ecb_encrypt(
366355714Skrisunsigned char *input,
366455714Skrisunsigned char *output,
366555714SkrisIDEA_KEY_SCHEDULE *ks);
366655714Skris	This is the basic Electronic Code Book form of IDEA (in DES this
366755714Skris	mode is called Electronic Code Book so I'm going to use the term
366855714Skris	for idea as well :-).
366955714Skris	Input is encrypted into output using the key represented by
367055714Skris	ks.  Depending on the IDEA_KEY_SCHEDULE, encryption or
367155714Skris	decryption occurs.  Input is 8 bytes long and output is 8 bytes.
367255714Skris	
367355714Skrisvoid idea_cbc_encrypt(
367455714Skrisunsigned char *input,
367555714Skrisunsigned char *output,
367655714Skrislong length,
367755714SkrisIDEA_KEY_SCHEDULE *ks,
367855714Skrisunsigned char *ivec,
367955714Skrisint enc);
368055714Skris	This routine implements IDEA in Cipher Block Chaining mode.
368155714Skris	Input, which should be a multiple of 8 bytes is encrypted
368255714Skris	(or decrypted) to output which will also be a multiple of 8 bytes.
368355714Skris	The number of bytes is in length (and from what I've said above,
368455714Skris	should be a multiple of 8).  If length is not a multiple of 8, bad 
368555714Skris	things will probably happen.  ivec is the initialisation vector.
368655714Skris	This function updates iv after each call so that it can be passed to
368755714Skris	the next call to idea_cbc_encrypt().
368855714Skris	
368955714Skrisvoid idea_cfb64_encrypt(
369055714Skrisunsigned char *in,
369155714Skrisunsigned char *out,
369255714Skrislong length,
369355714Skrisdes_key_schedule ks,
369455714Skrisdes_cblock *ivec,
369555714Skrisint *num,
369655714Skrisint enc);
369755714Skris	This is one of the more useful functions in this IDEA library, it
369855714Skris	implements CFB mode of IDEA with 64bit feedback.
369955714Skris	This allows you to encrypt an arbitrary number of bytes,
370055714Skris	you do not require 8 byte padding.  Each call to this
370155714Skris	routine will encrypt the input bytes to output and then update ivec
370255714Skris	and num.  Num contains 'how far' we are though ivec.
370355714Skris	Enc is used to indicate encryption or decryption.
370455714Skris	One very important thing to remember is that when decrypting, use
370555714Skris	the encryption form of the key.
370655714Skris	CFB64 mode operates by using the cipher to
370755714Skris	generate a stream of bytes which is used to encrypt the plain text.
370855714Skris	The cipher text is then encrypted to generate the next 64 bits to
370955714Skris	be xored (incrementally) with the next 64 bits of plain
371055714Skris	text.  As can be seen from this, to encrypt or decrypt,
371155714Skris	the same 'cipher stream' needs to be generated but the way the next
371255714Skris	block of data is gathered for encryption is different for
371355714Skris	encryption and decryption.  What this means is that to encrypt
371455714Skris	idea_set_encrypt_key(key,ks);
371555714Skris	idea_cfb64_encrypt(...,ks,..,IDEA_ENCRYPT)
371655714Skris	do decrypt
371755714Skris	idea_set_encrypt_key(key,ks)
371855714Skris	idea_cfb64_encrypt(...,ks,...,IDEA_DECRYPT)
371955714Skris	Note: The same IDEA_KEY_SCHEDULE but different encryption flags.
372055714Skris	For idea_cbc or idea_ecb, idea_set_decrypt_key() would need to be
372155714Skris	used to generate the IDEA_KEY_SCHEDULE for decryption.
372255714Skris	The reason I'm stressing this point is that I just wasted 3 hours
372355714Skris	today trying to decrypt using this mode and the decryption form of
372455714Skris	the key :-(.
372555714Skris	
372655714Skrisvoid idea_ofb64_encrypt(
372755714Skrisunsigned char *in,
372855714Skrisunsigned char *out,
372955714Skrislong length,
373055714Skrisdes_key_schedule ks,
373155714Skrisdes_cblock *ivec,
373255714Skrisint *num);
373355714Skris	This functions implements OFB mode of IDEA with 64bit feedback.
373455714Skris	This allows you to encrypt an arbitrary number of bytes,
373555714Skris	you do not require 8 byte padding.  Each call to this
373655714Skris	routine will encrypt the input bytes to output and then update ivec
373755714Skris	and num.  Num contains 'how far' we are though ivec.
373855714Skris	This is in effect a stream cipher, there is no encryption or
373955714Skris	decryption mode.  The same key and iv should be used to
374055714Skris	encrypt and decrypt.
374155714Skris	
374255714SkrisFor reading passwords, I suggest using des_read_pw_string() from my DES library.
374355714SkrisTo generate a password from a text string, I suggest using MD5 (or MD2) to
374455714Skrisproduce a 16 byte message digest that can then be passed directly to
374555714Skrisidea_set_encrypt_key().
374655714Skris
374755714Skris=====
374855714SkrisFor more information about the specific IDEA modes in this library
374955714Skris(ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
375055714Skrisdocumentation on my DES library.  What is said about DES is directly
375155714Skrisapplicable for IDEA.
375255714Skris
375355714Skris
375455714Skris==== legal.doc ========================================================
375555714Skris
375655714SkrisFrom eay@mincom.com Thu Jun 27 00:25:45 1996
375755714SkrisReceived: by orb.mincom.oz.au id AA15821
375855714Skris  (5.65c/IDA-1.4.4 for eay); Wed, 26 Jun 1996 14:25:45 +1000
375955714SkrisDate: Wed, 26 Jun 1996 14:25:45 +1000 (EST)
376055714SkrisFrom: Eric Young <eay@mincom.oz.au>
376155714SkrisX-Sender: eay@orb
376255714SkrisTo: Ken Toll <ktoll@ren.digitalage.com>
376355714SkrisCc: Eric Young <eay@mincom.oz.au>, ssl-talk@netscape.com
376455714SkrisSubject: Re: Unidentified subject!
376555714SkrisIn-Reply-To: <9606261950.ZM28943@ren.digitalage.com>
376655714SkrisMessage-Id: <Pine.SOL.3.91.960626131156.28573K-100000@orb>
376755714SkrisMime-Version: 1.0
376855714SkrisContent-Type: TEXT/PLAIN; charset=US-ASCII
376955714SkrisStatus: O
377055714SkrisX-Status: 
377155714Skris
377255714Skris
377355714SkrisThis is a little off topic but since SSLeay is a free implementation of
377455714Skristhe SSLv2 protocol, I feel it is worth responding on the topic of if it 
377555714Skrisis actually legal for Americans to use free cryptographic software.
377655714Skris
377755714SkrisOn Wed, 26 Jun 1996, Ken Toll wrote:
377855714Skris> Is the U.S the only country that SSLeay cannot be used commercially 
377955714Skris> (because of RSAref) or is that going to be an issue with every country 
378055714Skris> that a client/server application (non-web browser/server) is deployed 
378155714Skris> and sold?
378255714Skris
378355714Skris>From what I understand, the software patents that apply to algorithms 
378455714Skrislike RSA and DH only apply in the USA.  The IDEA algorithm I believe is 
378555714Skrispatened in europe (USA?), but considing how little it is used by other SSL 
378655714Skrisimplementations, it quite easily be left out of the SSLeay build
378755714Skris(this can be done with a compile flag).
378855714Skris
378955714SkrisActually if the RSA patent did apply outside the USA, it could be rather
379055714Skrisinteresting since RSA is not alowed to let RSA toolkits outside of the USA
379155714Skris[1], and since these are the only forms that they will alow the algorithm
379255714Skristo be used in, it would mean that non-one outside of the USA could produce
379355714Skrispublic key software which would be a very strong statment for
379455714Skrisinternational patent law to make :-).  This logic is a little flawed but
379555714Skrisit still points out some of the more interesting permutations of USA
379655714Skrispatent law and ITAR restrictions. 
379755714Skris
379855714SkrisInside the USA there is also the unresolved issue of RC4/RC2 which were
379955714Skrismade public on sci.crypt in Sep 1994 (RC4) and Feb 1996 (RC2).  I have
380055714Skriscopies of the origional postings if people are interested.  RSA I believe 
380155714Skrisclaim that they were 'trade-secrets' and that some-one broke an NDA in 
380255714Skrisrevealing them.  Other claim they reverse engineered the algorithms from 
3803194206Ssimoncompiled binaries.  If the algorithms were reverse engineered, I believe 
380455714SkrisRSA had no legal leg to stand on.  If an NDA was broken, I don't know.
3805194206SsimonRegardless, RSA, I believe, is willing to go to court over the issue so 
380655714Skrislicencing is probably the best idea, or at least talk to them.
380755714SkrisIf there are people who actually know more about this, pease let me know, I 
380855714Skrisdon't want to vilify or spread miss-information if I can help it.
380955714Skris
381055714SkrisIf you are not producing a web browser, it is easy to build SSLeay with
381155714SkrisRC2/RC4 removed. Since RC4 is the defacto standard cipher in 
381255714Skrisall web software (and it is damn fast) it is more or less required for 
381355714Skriswww use. For non www use of SSL, especially for an application where 
381455714Skrisinteroperability with other vendors is not critical just leave it out.
381555714Skris
381655714SkrisRemoving IDEA, RC2 and RC4 would only leave DES and Triple DES but 
381755714Skristhey should be ok.  Considing that Triple DES can encrypt at rates of
381855714Skris410k/sec on a pentium 100, and 940k/sec on a P6/200, this is quite 
381955714Skrisreasonable performance.  Single DES clocks in at 1160k/s and 2467k/s
382055714Skrisrespectivly is actually quite fast for those not so paranoid (56 bit key).[1]
382155714Skris
382255714Skris> Is it possible to get a certificate for commercial use outside of the U.S.?
382355714Skrisyes.
382455714Skris
382555714SkrisThawte Consulting issues certificates (they are the people who sell the
382655714Skris	Sioux httpd server and are based in South Africa)
382755714SkrisVerisign will issue certificates for Sioux (sold from South Africa), so this
382855714Skris	proves that they will issue certificate for OS use if they are
382955714Skris	happy with the quality of the software.
383055714Skris
383155714Skris(The above mentioned companies just the ones that I know for sure are issuing
383255714Skris certificates outside the USA).
383355714Skris
383455714SkrisThere is always the point that if you are using SSL for an intra net, 
383555714SkrisSSLeay provides programs that can be used so you can issue your own 
383655714Skriscertificates.  They need polishing but at least it is a good starting point.
383755714Skris
383855714SkrisI am not doing anything outside Australian law by implementing these
383955714Skrisalgorithms (to the best of my knowedge).  It is another example of how 
384055714Skristhe world legal system does not cope with the internet very well.
384155714Skris
384255714SkrisI may start making shared libraries available (I have now got DLL's for 
384355714SkrisWindows).  This will mean that distributions into the usa could be 
384455714Skrisshipped with a version with a reduced cipher set and the versions outside 
384555714Skriscould use the DLL/shared library with all the ciphers (and without RSAref).
384655714Skris
384755714SkrisThis could be completly hidden from the application, so this would not 
384855714Skriseven require a re-linking.
384955714Skris
385055714SkrisThis is the reverse of what people were talking about doing to get around 
385155714SkrisUSA export regulations :-)
385255714Skris
385355714Skriseric
385455714Skris
385555714Skris[1]:	The RSAref2.0 tookit is available on at least 3 ftp sites in Europe
385655714Skris	and one in South Africa.
385755714Skris
385855714Skris[2]:	Since I always get questions when I post benchmark numbers :-),
385955714Skris	DES performace figures are in 1000's of bytes per second in cbc 
386055714Skris	mode using an 8192 byte buffer.  The pentium 100 was running Windows NT 
386155714Skris	3.51 DLLs and the 686/200 was running NextStep.
386255714Skris	I quote pentium 100 benchmarks because it is basically the
386355714Skris	'entry level' computer that most people buy for personal use.
386455714Skris	Windows 95 is the OS shipping on those boxes, so I'll give
386555714Skris	NT numbers (the same Win32 runtime environment).  The 686
386655714Skris	numbers are present as an indication of where we will be in a
386755714Skris	few years.
386855714Skris--
386955714SkrisEric Young                  | BOOL is tri-state according to Bill Gates.
387055714SkrisAARNet: eay@mincom.oz.au    | RTFM Win32 GetMessage().
387155714Skris
387255714Skris
387355714Skris
387455714Skris==== lhash.doc ========================================================
387555714Skris
387655714SkrisThe LHASH library.
387755714Skris
387855714SkrisI wrote this library in 1991 and have since forgotten why I called it lhash.
387955714SkrisIt implements a hash table from an article I read at the
388055714Skristime from 'Communications of the ACM'.  What makes this hash
388155714Skristable different is that as the table fills, the hash table is
388255714Skrisincreased (or decreased) in size via realloc().
388355714SkrisWhen a 'resize' is done, instead of all hashes being redistributed over
388455714Skristwice as many 'buckets', one bucket is split.  So when an 'expand' is done,
388555714Skristhere is only a minimal cost to redistribute some values.  Subsequent
388655714Skrisinserts will cause more single 'bucket' redistributions but there will
388755714Skrisnever be a sudden large cost due to redistributing all the 'buckets'.
388855714Skris
388955714SkrisThe state for a particular hash table is kept in the LHASH structure.
389055714SkrisThe LHASH structure also records statistics about most aspects of accessing
389155714Skristhe hash table.  This is mostly a legacy of my writing this library for
389255714Skristhe reasons of implementing what looked like a nice algorithm rather than
389355714Skrisfor a particular software product.
389455714Skris
389555714SkrisInternal stuff you probably don't want to know about.
389655714SkrisThe decision to increase or decrease the hash table size is made depending
389755714Skrison the 'load' of the hash table.  The load is the number of items in the
389855714Skrishash table divided by the size of the hash table.  The default values are
389955714Skrisas follows.  If (hash->up_load < load) => expand.
390055714Skrisif (hash->down_load > load) =>  contract.  The 'up_load' has a default value of
390155714Skris1 and 'down_load' has a default value of 2.  These numbers can be modified
390255714Skrisby the application by just playing with the 'up_load' and 'down_load'
390355714Skrisvariables.  The 'load' is kept in a form which is multiplied by 256.  So
390455714Skrishash->up_load=8*256; will cause a load of 8 to be set.
390555714Skris
390655714SkrisIf you are interested in performance the field to watch is
390755714Skrisnum_comp_calls.  The hash library keeps track of the 'hash' value for
390855714Skriseach item so when a lookup is done, the 'hashes' are compared, if
390955714Skristhere is a match, then a full compare is done, and
391055714Skrishash->num_comp_calls is incremented.  If num_comp_calls is not equal
391155714Skristo num_delete plus num_retrieve it means that your hash function is
391255714Skrisgenerating hashes that are the same for different values.  It is
391355714Skrisprobably worth changing your hash function if this is the case because
391455714Skriseven if your hash table has 10 items in a 'bucked', it can be searched
391555714Skriswith 10 'unsigned long' compares and 10 linked list traverses.  This
391655714Skriswill be much less expensive that 10 calls to you compare function.
391755714Skris
391855714SkrisLHASH *lh_new(
391955714Skrisunsigned long (*hash)(),
392055714Skrisint (*cmp)());
392155714Skris	This function is used to create a new LHASH structure.  It is passed
392255714Skris	function pointers that are used to store and retrieve values passed
392355714Skris	into the hash table.  The 'hash'
392455714Skris	function is a hashing function that will return a hashed value of
392555714Skris	it's passed structure.  'cmp' is passed 2 parameters, it returns 0
392655714Skris	is they are equal, otherwise, non zero.
392755714Skris	If there are any problems (usually malloc failures), NULL is
392855714Skris	returned, otherwise a new LHASH structure is returned.  The
392955714Skris	hash value is normally truncated to a power of 2, so make sure
393055714Skris	that your hash function returns well mixed low order bits.
393155714Skris	
393255714Skrisvoid lh_free(
393355714SkrisLHASH *lh);
393455714Skris	This function free()s a LHASH structure.  If there is malloced
393555714Skris	data in the hash table, it will not be freed.  Consider using the
393655714Skris	lh_doall function to deallocate any remaining entries in the hash
393755714Skris	table.
393855714Skris	
393955714Skrischar *lh_insert(
394055714SkrisLHASH *lh,
394155714Skrischar *data);
394255714Skris	This function inserts the data pointed to by data into the lh hash
394355714Skris	table.  If there is already and entry in the hash table entry, the
394455714Skris	value being replaced is returned.  A NULL is returned if the new
394555714Skris	entry does not clash with an entry already in the table (the normal
394655714Skris	case) or on a malloc() failure (perhaps I should change this....).
394755714Skris	The 'char *data' is exactly what is passed to the hash and
394855714Skris	comparison functions specified in lh_new().
394955714Skris	
395055714Skrischar *lh_delete(
395155714SkrisLHASH *lh,
395255714Skrischar *data);
395355714Skris	This routine deletes an entry from the hash table.  The value being
395455714Skris	deleted is returned.  NULL is returned if there is no such value in
395555714Skris	the hash table.
395655714Skris
395755714Skrischar *lh_retrieve(
395855714SkrisLHASH *lh,
395955714Skrischar *data);
396055714Skris	If 'data' is in the hash table it is returned, else NULL is
396155714Skris	returned.  The way these routines would normally be uses is that a
396255714Skris	dummy structure would have key fields populated and then
396355714Skris	ret=lh_retrieve(hash,&dummy);.  Ret would now be a pointer to a fully
396455714Skris	populated structure.
396555714Skris
396655714Skrisvoid lh_doall(
396755714SkrisLHASH *lh,
396855714Skrisvoid (*func)(char *a));
396955714Skris	This function will, for every entry in the hash table, call function
397055714Skris	'func' with the data item as parameters.
397155714Skris	This function can be quite useful when used as follows.
397255714Skris	void cleanup(STUFF *a)
397355714Skris		{ STUFF_free(a); }
397455714Skris	lh_doall(hash,cleanup);
397555714Skris	lh_free(hash);
397655714Skris	This can be used to free all the entries, lh_free() then
397755714Skris	cleans up the 'buckets' that point to nothing.  Be careful
397855714Skris	when doing this.  If you delete entries from the hash table,
397955714Skris	in the call back function, the table may decrease in size,
398055714Skris	moving item that you are
398155714Skris	currently on down lower in the hash table.  This could cause
398255714Skris	some entries to be skipped.  The best solution to this problem
398355714Skris	is to set lh->down_load=0 before you start.  This will stop
398455714Skris	the hash table ever being decreased in size.
398555714Skris
398655714Skrisvoid lh_doall_arg(
398755714SkrisLHASH *lh;
398855714Skrisvoid(*func)(char *a,char *arg));
398955714Skrischar *arg;
399055714Skris	This function is the same as lh_doall except that the function
399155714Skris	called will be passed 'arg' as the second argument.
399255714Skris	
399355714Skrisunsigned long lh_strhash(
399455714Skrischar *c);
399555714Skris	This function is a demo string hashing function.  Since the LHASH
399655714Skris	routines would normally be passed structures, this routine would
399755714Skris	not normally be passed to lh_new(), rather it would be used in the
399855714Skris	function passed to lh_new().
399955714Skris
400055714SkrisThe next three routines print out various statistics about the state of the
400155714Skrispassed hash table.  These numbers are all kept in the lhash structure.
400255714Skris
400355714Skrisvoid lh_stats(
400455714SkrisLHASH *lh,
400555714SkrisFILE *out);
400655714Skris	This function prints out statistics on the size of the hash table,
400755714Skris	how many entries are in it, and the number and result of calls to
400855714Skris	the routines in this library.
400955714Skris
401055714Skrisvoid lh_node_stats(
401155714SkrisLHASH *lh,
401255714SkrisFILE *out);
401355714Skris	For each 'bucket' in the hash table, the number of entries is
401455714Skris	printed.
401555714Skris	
401655714Skrisvoid lh_node_usage_stats(
401755714SkrisLHASH *lh,
401855714SkrisFILE *out);
401955714Skris	This function prints out a short summary of the state of the hash
402055714Skris	table.  It prints what I call the 'load' and the 'actual load'.
402155714Skris	The load is the average number of data items per 'bucket' in the
402255714Skris	hash table.  The 'actual load' is the average number of items per
402355714Skris	'bucket', but only for buckets which contain entries.  So the
402455714Skris	'actual load' is the average number of searches that will need to
402555714Skris	find an item in the hash table, while the 'load' is the average number
402655714Skris	that will be done to record a miss.
402755714Skris
402855714Skris==== md2.doc ========================================================
402955714Skris
403055714SkrisThe MD2 library.
403155714SkrisMD2 is a message digest algorithm that can be used to condense an arbitrary
403255714Skrislength message down to a 16 byte hash.  The functions all need to be passed
403355714Skrisa MD2_CTX which is used to hold the MD2 context during multiple MD2_Update()
403455714Skrisfunction calls.  The normal method of use for this library is as follows
403555714Skris
403655714SkrisMD2_Init(...);
403755714SkrisMD2_Update(...);
403855714Skris...
403955714SkrisMD2_Update(...);
404055714SkrisMD2_Final(...);
404155714Skris
404255714SkrisThis library requires the inclusion of 'md2.h'.
404355714Skris
404455714SkrisThe main negative about MD2 is that it is slow, especially when compared
404555714Skristo MD5.
404655714Skris
404755714SkrisThe functions are as follows:
404855714Skris
404955714Skrisvoid MD2_Init(
405055714SkrisMD2_CTX *c);
405155714Skris	This function needs to be called to initiate a MD2_CTX structure for
405255714Skris	use.
405355714Skris	
405455714Skrisvoid MD2_Update(
405555714SkrisMD2_CTX *c;
405655714Skrisunsigned char *data;
405755714Skrisunsigned long len);
405855714Skris	This updates the message digest context being generated with 'len'
405955714Skris	bytes from the 'data' pointer.  The number of bytes can be any
406055714Skris	length.
406155714Skris
406255714Skrisvoid MD2_Final(
406355714Skrisunsigned char *md;
406455714SkrisMD2_CTX *c;
406555714Skris	This function is called when a message digest of the data digested
406655714Skris	with MD2_Update() is wanted.  The message digest is put in the 'md'
406755714Skris	array and is MD2_DIGEST_LENGTH (16) bytes long.
406855714Skris
406955714Skrisunsigned char *MD2(
407055714Skrisunsigned long n;
407155714Skrisunsigned char *d;
407255714Skrisunsigned char *md;
407355714Skris	This function performs a MD2_Init(), followed by a MD2_Update()
407455714Skris	followed by a MD2_Final() (using a local MD2_CTX).
407555714Skris	The resulting digest is put into 'md' if it is not NULL.
407655714Skris	Regardless of the value of 'md', the message
407755714Skris	digest is returned from the function.  If 'md' was NULL, the message
407855714Skris	digest returned is being stored in a static structure.
407955714Skris
408055714Skris==== md5.doc ========================================================
408155714Skris
408255714SkrisThe MD5 library.
408355714SkrisMD5 is a message digest algorithm that can be used to condense an arbitrary
408455714Skrislength message down to a 16 byte hash.  The functions all need to be passed
408555714Skrisa MD5_CTX which is used to hold the MD5 context during multiple MD5_Update()
408655714Skrisfunction calls.  This library also contains random number routines that are
408755714Skrisbased on MD5
408855714Skris
408955714SkrisThe normal method of use for this library is as follows
409055714Skris
409155714SkrisMD5_Init(...);
409255714SkrisMD5_Update(...);
409355714Skris...
409455714SkrisMD5_Update(...);
409555714SkrisMD5_Final(...);
409655714Skris
409755714SkrisThis library requires the inclusion of 'md5.h'.
409855714Skris
409955714SkrisThe functions are as follows:
410055714Skris
410155714Skrisvoid MD5_Init(
410255714SkrisMD5_CTX *c);
410355714Skris	This function needs to be called to initiate a MD5_CTX structure for
410455714Skris	use.
410555714Skris	
410655714Skrisvoid MD5_Update(
410755714SkrisMD5_CTX *c;
410855714Skrisunsigned char *data;
410955714Skrisunsigned long len);
411055714Skris	This updates the message digest context being generated with 'len'
411155714Skris	bytes from the 'data' pointer.  The number of bytes can be any
411255714Skris	length.
411355714Skris
411455714Skrisvoid MD5_Final(
411555714Skrisunsigned char *md;
411655714SkrisMD5_CTX *c;
411755714Skris	This function is called when a message digest of the data digested
411855714Skris	with MD5_Update() is wanted.  The message digest is put in the 'md'
411955714Skris	array and is MD5_DIGEST_LENGTH (16) bytes long.
412055714Skris
412155714Skrisunsigned char *MD5(
412255714Skrisunsigned char *d;
412355714Skrisunsigned long n;
412455714Skrisunsigned char *md;
412555714Skris	This function performs a MD5_Init(), followed by a MD5_Update()
412655714Skris	followed by a MD5_Final() (using a local MD5_CTX).
412755714Skris	The resulting digest is put into 'md' if it is not NULL.
412855714Skris	Regardless of the value of 'md', the message
412955714Skris	digest is returned from the function.  If 'md' was NULL, the message
413055714Skris	digest returned is being stored in a static structure.
413155714Skris
413255714Skris
413355714Skris==== memory.doc ========================================================
413455714Skris
413555714SkrisIn the interests of debugging SSLeay, there is an option to compile
413655714Skrisusing some simple memory leak checking.
413755714Skris
413855714SkrisAll malloc(), free() and realloc() calls in SSLeay now go via
413955714SkrisMalloc(), Free() and Realloc() (except those in crypto/lhash).
414055714Skris
414155714SkrisIf CRYPTO_MDEBUG is defined, these calls are #defined to
414255714SkrisCRYPTO_malloc(), CRYPTO_free() and CRYPTO_realloc().
414355714SkrisIf it is not defined, they are #defined to malloc(), free() and realloc().
414455714Skris
414555714Skristhe CRYPTO_malloc() routines by default just call the underlying library
414655714Skrisfunctons.
414755714Skris
414855714SkrisIf CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON) is called, memory leak detection is
414955714Skristurned on.  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF) turns it off.
415055714Skris
415155714SkrisWhen turned on, each Malloc() or Realloc() call is recored along with the file
415255714Skrisand line number from where the call was made.   (This is done using the
415355714Skrislhash library which always uses normal system malloc(3) routines).
415455714Skris
415555714Skrisvoid CRYPTO_mem_leaks(BIO *b);
415655714Skrisvoid CRYPTO_mem_leaks_fp(FILE *fp);
415755714SkrisThese both print out the list of memory that has not been free()ed.
415855714SkrisThis will probably be rather hard to read, but if you look for the 'top level'
415955714Skrisstructure allocation, this will often give an idea as to what is not being
416055714Skrisfree()ed.  I don't expect people to use this stuff normally.
416155714Skris
416255714Skris==== ca.1 ========================================================
416355714Skris
416455714SkrisFrom eay@orb.mincom.oz.au Thu Dec 28 23:56:45 1995
416555714SkrisReceived: by orb.mincom.oz.au id AA07374
416655714Skris  (5.65c/IDA-1.4.4 for eay); Thu, 28 Dec 1995 13:56:45 +1000
416755714SkrisDate: Thu, 28 Dec 1995 13:56:45 +1000 (EST)
416855714SkrisFrom: Eric Young <eay@mincom.oz.au>
416955714SkrisX-Sender: eay@orb
417055714SkrisTo: sameer <sameer@c2.org>
417155714SkrisCc: ssleay@mincom.oz.au
417255714SkrisSubject: Re: 'ca'
417355714SkrisIn-Reply-To: <199512230440.UAA23410@infinity.c2.org>
417455714SkrisMessage-Id: <Pine.SOL.3.91.951228133525.7269A-100000@orb>
417555714SkrisMime-Version: 1.0
417655714SkrisContent-Type: TEXT/PLAIN; charset=US-ASCII
417755714SkrisStatus: RO
417855714SkrisX-Status: 
417955714Skris
418055714SkrisOn Fri, 22 Dec 1995, sameer wrote:
418155714Skris> 	I could use documentation on 'ca'. Thanks.
418255714Skris
418355714SkrisVery quickly.
418455714SkrisThe ca program uses the ssleay.conf file for most of its configuration
418555714Skris
418655714Skris./ca -help
418755714Skris
418855714Skris -verbose        - Talk alot while doing things
418955714Skris -config file    - A config file. If you don't want to use the
419055714Skris		   default config file
419155714Skris -name arg       - The particular CA definition to use
419255714Skris	In the config file, the section to use for parameters.  This lets 
419355714Skris	multiple setups to be contained in the one file.  By default, the 
419455714Skris	default_ca variable is looked up in the [ ca ] section.  So in the 
419555714Skris	shipped ssleay.conf, the CA definition used is CA_default.  It could be 
419655714Skris	any other name.
419755714Skris -gencrl days    - Generate a new CRL, days is when the next CRL is due
419855714Skris	This will generate a new certificate revocion list.
419955714Skris -days arg       - number of days to certify the certificate for
420055714Skris	When certifiying certificates, this is the number of days to use.
420155714Skris -md arg         - md to use, one of md2, md5, sha or sha1
420255714Skris -policy arg     - The CA 'policy' to support
420355714Skris	I'll describe this later, but there are 2 policies definied in the 
420455714Skris	shipped ssleay.conf
420555714Skris -keyfile arg    - PEM RSA private key file
420655714Skris -key arg        - key to decode the RSA private key if it is encrypted
420755714Skris	since we need to keep the CA's RSA key encrypted
420855714Skris -cert           - The CA certificate
420955714Skris -in file        - The input PEM encoded certificate request(s)
421055714Skris -out file       - Where to put the output file(s)
421155714Skris -outdir dir     - Where to put output certificates
421255714Skris	The -out options concatinates all the output certificied
421355714Skris	certificates to one file, -outdir puts them in a directory,
421455714Skris	named by serial number.
421555714Skris -infiles ....   - The last argument, requests to process
421655714Skris	The certificate requests to process, -in is the same.
421755714Skris
421855714SkrisJust about all the above have default values defined in ssleay.conf.
421955714Skris
422055714SkrisThe key variables in ssleay.conf are (for the pariticular '-name' being 
422155714Skrisused, in the default, it is CA_default).
422255714Skris
422355714Skrisdir is where all the CA database stuff is kept.
422455714Skriscerts is where all the previously issued certificates are kept.
422555714SkrisThe database is a simple text database containing the following tab separated 
422655714Skrisfields.
422755714Skrisstatus: a value of 'R' - revoked, 'E' -expired or 'V' valid.
422855714Skrisissued date:  When the certificate was certified.
422955714Skrisrevoked date:  When it was revoked, blank if not revoked.
423055714Skrisserial number:  The certificate serial number.
423155714Skriscertificate:	Where the certificate is located.
423255714SkrisCN:	The name of the certificate.
423355714Skris
423455714SkrisThe demo file has quite a few made up values it it.  The last 2 were 
423555714Skrisadded by the ca program and are acurate.
423655714SkrisThe CA program does not update the 'certificate' file correctly right now.
423755714SkrisThe serial field should be unique as should the CN/status combination.
423855714SkrisThe ca program checks these at startup.  What still needs to be 
423955714Skriswrtten is a program to 'regenerate' the data base file from the issued 
424055714Skriscertificate list (and a CRL list).
424155714Skris
424255714SkrisBack to the CA_default variables.
424355714Skris
424455714SkrisMost of the variables are commented.
424555714Skris
424655714Skrispolicy is the default policy.
424755714Skris
424855714SkrisOk for policies, they define the order and which fields must be present 
424955714Skrisin the certificate request and what gets filled in.
425055714Skris
425155714SkrisSo a value of
425255714SkriscountryName             = match
425355714Skrismeans that the country name must match the CA certificate.
425455714SkrisorganizationalUnitName  = optional
425555714SkrisThe org.Unit,Name does not have to be present and
425655714SkriscommonName              = supplied
425755714SkriscommonName must be supplied in the certificate request.
425855714Skris
425955714SkrisFor the 'policy_match' polocy, the order of the attributes in the 
426055714Skrisgenerated certiticate would be
426155714SkriscountryName
426255714SkrisstateOrProvinceName
426355714SkrisorganizationName
426455714SkrisorganizationalUnitName
426555714SkriscommonName
426655714SkrisemailAddress
426755714Skris
426855714SkrisHave a play, it sort of makes sense.  If you think about how the persona 
426955714Skrisrequests operate, it is similar to the 'policy_match' policy and the
427055714Skris'policy_anything' is similar to what versign is doing.
427155714Skris
427255714SkrisI hope this helps a bit.  Some backend scripts are definitly needed to 
427355714Skrisupdate the database and to make certificate revocion easy.  All 
427455714Skriscertificates issued should also be kept forever (or until they expire?)
427555714Skris
427655714Skrishope this helps
427755714Skriseric (who has to run off an buy some cheap knee pads for the caving in 4 
427855714Skrisdays time :-)
427955714Skris
428055714Skris--
428155714SkrisEric Young                  | Signature removed since it was generating
428255714SkrisAARNet: eay@mincom.oz.au    | more followups than the message contents :-)
428355714Skris
428455714Skris
428555714Skris==== ms3-ca.doc ========================================================
428655714Skris
428755714SkrisDate: Mon, 9 Jun 97 08:00:33 +0200
428855714SkrisFrom: Holger.Reif@PrakInf.TU-Ilmenau.DE (Holger Reif)
428955714SkrisSubject: ms3-ca.doc
429055714SkrisOrganization: TU Ilmenau, Fak. IA, FG Telematik
429155714SkrisContent-Length: 14575
429255714SkrisStatus: RO
429355714SkrisX-Status: 
429455714Skris
429555714SkrisLoading client certs into MSIE 3.01
429655714Skris===================================
429755714Skris
4298160814SsimonThis document contains all the information necessary to successfully set up 
429955714Skrissome scripts to issue client certs to Microsoft Internet Explorer. It 
430055714Skrisincludes the required knowledge about the model MSIE uses for client 
430155714Skriscertification and includes complete sample scripts ready to play with. The 
430255714Skrisscripts were tested against a modified ca program of SSLeay 0.6.6 and should 
430355714Skriswork with the regular ca program that comes with version 0.8.0. I haven't 
430455714Skristested against MSIE 4.0
430555714Skris
430655714SkrisYou can use the information contained in this document in either way you 
430755714Skriswant. However if you feel it saved you a lot of time I ask you to be as fair 
430855714Skrisas to mention my name: Holger Reif <reif@prakinf.tu-ilmenau.de>.
430955714Skris
431055714Skris1.) The model used by MSIE
431155714Skris--------------------------
431255714Skris
431355714SkrisThe Internet Explorer doesn't come with a embedded engine for installing 
431455714Skrisclient certs like Netscape's Navigator. It rather uses the CryptoAPI (CAPI) 
431555714Skrisdefined by Microsoft. CAPI comes with WindowsNT 4.0 or is installed together 
431655714Skriswith Internet Explorer since 3.01. The advantage of this approach is a higher 
431755714Skrisflexibility because the certificates in the (per user) system open 
431855714Skriscertificate store may be used by other applications as well. The drawback 
431955714Skrishowever is that you need to do a bit more work to get a client cert issued.
432055714Skris
432155714SkrisCAPI defines functions which will handle basic cryptographic work, eg. 
432255714Skrisgenerating keys, encrypting some data, signing text or building a certificate 
432355714Skrisrequest. The procedure is as follows: A CAPI function generates you a key 
432455714Skrispair and saves it into the certificate store. After that one builds a 
432555714SkrisDistinguished Name. Together with that key pair another CAPI function forms a 
432655714SkrisPKCS#10 request which you somehow need to submit to a CA. Finally the issued 
432755714Skriscert is given to a yet another CAPI function which saves it into the 
432855714Skriscertificate store.
432955714Skris
433055714SkrisThe certificate store with the user's keys and certs is in the registry. You 
433155714Skriswill find it under HKEY_CURRENT_USER/Software/Microsoft/Cryptography/ (I 
433255714Skrisleave it to you as a little exercise to figure out what all the entries mean 
433355714Skris;-). Note that the keys are protected only with the user's usual Windows 
433455714Skrislogin password.
433555714Skris
433655714Skris2.) The practical usage
433755714Skris-----------------------
433855714Skris
433955714SkrisUnfortunatly since CAPI is a system API you can't access its functions from 
434055714SkrisHTML code directly. For this purpose Microsoft provides a wrapper called 
434155714Skriscertenr3.dll. This DLL accesses the CAPI functions and provides an interface 
434255714Skrisusable from Visual Basic Script. One needs to install that library on the 
434355714Skriscomputer which wants to have client cert. The easiest way is to load it as an 
434455714SkrisActiveX control (certenr3.dll is properly authenticode signed by MS ;-). If 
434555714Skrisyou have ever enrolled e cert request at a CA you will have installed it.
434655714Skris
434755714SkrisAt time of writing certenr3.dll is contained in 
434855714Skrishttp://www.microsoft.com/workshop/prog/security/csa/certenr3.exe. It comes 
434955714Skriswith an README file which explains the available functions. It is labeled 
435055714Skrisbeta but every CA seems to use it anyway. The license.txt allows you the 
435155714Skrisusage for your own purposes (as far as I understood) and a somehow limited 
435255714Skrisdistribution. 
435355714Skris
435455714SkrisThe two functions of main interest are GenerateKeyPair and AcceptCredentials. 
435555714SkrisFor complete explanation of all possible parameters see the README file. Here 
435655714Skrisare only minimal required parameters and their values.
435755714Skris
435855714SkrisGenerateKeyPair(sessionID, FASLE, szName, 0, "ClientAuth", TRUE, FALSE, 1)
435955714Skris- sessionID is a (locally to that computer) unique string to correlate the 
436055714Skrisgenerated key pair with a cert installed later.
436155714Skris- szName is the DN of the form "C=DE; S=Thueringen; L=Ilmenau; CN=Holger 
436255714SkrisReif; 1.2.840.113549.1.9.1=reif@prakinf.tu-ilmenau.de". Note that S is the 
436355714Skrisabreviation for StateOrProvince. The recognized abreviation include CN, O, C, 
436455714SkrisOU, G, I, L, S, T. If the abreviation is unknown (eg. for PKCS#9 email addr) 
436555714Skrisyou need to use the full object identifier. The starting point for searching 
436655714Skristhem could be crypto/objects.h since all OIDs know to SSLeay are listed 
436755714Skristhere.
436855714Skris- note: the possible ninth parameter which should give a default name to the 
436955714Skriscertificate storage location doesn't seem to work. Changes to the constant 
437055714Skrisvalues in the call above doesn't seem to make sense. You can't generate 
437155714SkrisPKCS#10 extensions with that function.
437255714Skris
437355714SkrisThe result of GenerateKeyPair is the base64 encoded PKCS#10 request. However 
437455714Skrisit has a little strange format that SSLeay doesn't accept. (BTW I feel the 
437555714Skrisdecision of rejecting that format as standard conforming.) It looks like 
437655714Skrisfollows:
437755714Skris	1st line with 76 chars
437855714Skris	2nd line with 76 chars
437955714Skris	...
438055714Skris	(n-2)th line with 76 chars
438155714Skris	(n-1)th line contains a multiple of 4 chars less then 76 (possible 
438255714Skrisempty)
438355714Skris	(n)th line has zero or 4 chars (then with 1 or 2 equal signs - the 
438455714Skris		original text's lenght wasn'T a multiple of 3) 
438555714Skris	The line separator has two chars: 0x0d 0x0a
438655714Skris
438755714SkrisAcceptCredentials(sessionID, credentials, 0, FALSE)
438855714Skris- sessionID needs to be the same as while generating the key pair
438955714Skris- credentials is the base64 encoded PKCS#7 object containing the cert. 
439055714Skris
439155714SkrisCRL's and CA certs are not required simply just the client cert. (It seems to 
439255714Skrisme that both are not even checked somehow.) The only format of the base64 
439355714Skrisencoded object I succesfully used was all characters in a very long string 
439455714Skriswithout line feeds or carriage returns. (Hey, it doesn't matter, only a 
439555714Skriscomputer reads it!)
439655714Skris
439755714SkrisThe result should be S_OK. For error handling see the example that comes with 
439855714Skriscertenr3.dll.
439955714Skris
440055714SkrisA note about ASN.1 character encodings. certenr3.dll seems to know only about 
440155714Skris2 of them: UniversalString and PrintableString. First it is definitely wrong 
440255714Skrisfor an email address which is IA5STRING (checked by ssleay's ca). Second 
440355714Skrisunfortunately MSIE (at least until version 3.02) can't handle UniversalString 
440455714Skriscorrectly - they just blow up you cert store! Therefore ssleay's ca (starting 
440555714Skrisfrom version 0.8.0) tries to convert the encodings automatically to IA5STRING 
440655714Skrisor TeletexString. The beef is it will work only for the latin-1 (western) 
440755714Skrischarset. Microsoft still has to do abit of homework...
440855714Skris
440955714Skris3.) An example
441055714Skris--------------
441155714Skris
441255714SkrisAt least you need two steps: generating the key & request and then installing 
441355714Skristhe certificate. A real world CA would have some more steps involved, eg. 
441455714Skrisaccepting some license. Note that both scripts shown below are just 
441555714Skrisexperimental state without any warrenty!
441655714Skris
441755714SkrisFirst how to generate a request. Note that we can't use a static page because 
441855714Skrisof the sessionID. I generate it from system time plus pid and hope it is 
441955714Skrisunique enough. Your are free to feed it through md5 to get more impressive 
442055714SkrisID's ;-) Then the intended text is read in with sed which inserts the 
442155714SkrissessionID. 
442255714Skris
442355714Skris-----BEGIN ms-enroll.cgi-----
442455714Skris#!/bin/sh
442555714SkrisSESSION_ID=`date '+%y%m%d%H%M%S'`$$
442655714Skrisecho Content-type: text/html
442755714Skrisecho
442855714Skrissed s/template_for_sessId/$SESSION_ID/ <<EOF
442955714Skris<HTML><HEAD>
443055714Skris<TITLE>Certificate Enrollment Test Page</TITLE>
443155714Skris</HEAD><BODY>
443255714Skris
443355714Skris<OBJECT
443455714Skris    classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
443555714Skris    codebase=certenr3.dll
443655714Skris    id=certHelper
443755714Skris    >
443855714Skris</OBJECT>
443955714Skris
444055714Skris<CENTER>
444155714Skris<H2>enrollment for a personal cert</H2>
444255714Skris<BR><HR WIDTH=50%><BR><P>
444355714Skris<FORM NAME="MSIE_Enrollment" ACTION="ms-gencert.cgi" ENCTYPE=x-www-form-
444455714Skrisencoded METHOD=POST>
444555714Skris<TABLE>
444655714Skris    <TR><TD>Country</TD><TD><INPUT NAME="Country" VALUE=""></TD></TR>
444755714Skris    <TR><TD>State</TD><TD><INPUT NAME="StateOrProvince" VALUE=""></TD></TR>
444855714Skris    <TR><TD>Location</TD><TD><INPUT NAME="Location" VALUE=""></TD></TR>
444955714Skris    <TR><TD>Organization</TD><TD><INPUT NAME="Organization" 
445055714SkrisVALUE=""></TD></TR>
445155714Skris    <TR><TD>Organizational Unit</TD>
445255714Skris        <TD><INPUT NAME="OrganizationalUnit" VALUE=""></TD></TR>
445355714Skris    <TR><TD>Name</TD><TD><INPUT NAME="CommonName" VALUE=""></TD></TR>
445455714Skris    <TR><TD>eMail Address</TD>
445555714Skris        <TD><INPUT NAME="EmailAddress" VALUE=""></TD></TR>
445655714Skris    <TR><TD></TD>
445755714Skris        <TD><INPUT TYPE="BUTTON" NAME="submit" VALUE="Beantragen"></TD></TR>
445855714Skris</TABLE>
445955714Skris	<INPUT TYPE="hidden" NAME="SessionId" VALUE="template_for_sessId">
446055714Skris	<INPUT TYPE="hidden" NAME="Request" VALUE="">
446155714Skris</FORM>
446255714Skris<BR><HR WIDTH=50%><BR><P>
446355714Skris</CENTER>
446455714Skris
446555714Skris<SCRIPT LANGUAGE=VBS>
446655714Skris    Dim DN
446755714Skris
446855714Skris    Sub Submit_OnClick
446955714Skris	Dim TheForm
447055714Skris	Set TheForm = Document.MSIE_Enrollment
447155714Skris	sessionId	= TheForm.SessionId.value
447255714Skris	reqHardware     = FALSE
447355714Skris	C		= TheForm.Country.value
447455714Skris	SP		= TheForm.StateOrProvince.value
447555714Skris	L		= TheForm.Location.value
447655714Skris	O		= TheForm.Organization.value
447755714Skris	OU		= TheForm.OrganizationalUnit.value
447855714Skris	CN              = TheForm.CommonName.value
447955714Skris	Email		= TheForm.EmailAddress.value
448055714Skris        szPurpose       = "ClientAuth"
448155714Skris        doAcceptanceUINow   = FALSE
448255714Skris        doOnline        = TRUE
448355714Skris
448455714Skris	DN = ""
448555714Skris
448655714Skris	Call Add_RDN("C", C)
448755714Skris	Call Add_RDN("S", SP)
448855714Skris	Call Add_RDN("L", L)
448955714Skris	Call Add_RDN("O", O)
449055714Skris	Call Add_RDN("OU", OU)
449155714Skris	Call Add_RDN("CN", CN)
449255714Skris	Call Add_RDN("1.2.840.113549.1.9.1", Email)
449355714Skris		      ' rsadsi
449455714Skris				     ' pkcs
449555714Skris				       ' pkcs9
449655714Skris					 ' eMailAddress
449755714Skris        On Error Resume Next
449855714Skris        sz10 = certHelper.GenerateKeyPair(sessionId, _
449955714Skris                FALSE, DN, 0, ClientAuth, FASLE, TRUE, 1)_
450055714Skris        theError = Err.Number
450155714Skris        On Error Goto 0
450255714Skris        if (sz10 = Empty OR theError <> 0) Then
450355714Skris            sz = "The error '" & Hex(theError) & "' occurred." & chr(13) & _
450455714Skris                chr(10) & "Your credentials could not be generated."
450555714Skris            result = MsgBox(sz, 0, "Credentials Enrollment")
450655714Skris            Exit Sub
450755714Skris	else 
450855714Skris	    TheForm.Request.value = sz10
450955714Skris	    TheForm.Submit
451055714Skris        end if
451155714Skris    End Sub
451255714Skris
451355714Skris    Sub Add_RDN(sn, value)
451455714Skris	if (value <> "") then
451555714Skris	    if (DN <> "") then
451655714Skris		DN = DN & "; "
451755714Skris	    end if
451855714Skris	    DN = DN & sn & "=" & value
451955714Skris	end if
452055714Skris    End Sub
452155714Skris</SCRIPT>
452255714Skris</BODY>
452355714Skris</HTML>
452455714SkrisEOF
452555714Skris-----END ms-enroll.cgi-----
452655714Skris
452755714SkrisSecond, how to extract the request and feed the certificate back? We need to 
452855714Skris"normalize" the base64 encoding of the PKCS#10 format which means 
452955714Skrisregenerating the lines and wrapping with BEGIN and END line. This is done by 
453055714Skrisgawk. The request is taken by ca the normal way. Then the cert needs to be 
453155714Skrispacked into a PKCS#7 structure (note: the use of a CRL is necessary for 
453255714Skriscrl2pkcs7 as of version 0.6.6. Starting with 0.8.0 it it might probably be 
453355714Skrisommited). Finally we need to format the PKCS#7 object and generate the HTML 
453455714Skristext. I use two templates to have a clearer script.
453555714Skris
453655714Skris1st note: postit2 is slightly modified from a program I found at ncsa's ftp 
453755714Skrissite. Grab it from http://www.easterngraphics.com/certs/IX9704/postit2.c. You 
453855714Skrisneed utils.c from there too.
453955714Skris
454055714Skris2nd note: I'm note quite sure wether the gawk script really handles all 
454155714Skrispossible inputs for the request right! Today I don't use this construction 
454255714Skrisanymore myself.
454355714Skris
454455714Skris3d note: the cert must be of version 3! This could be done with the nsComment 
454555714Skrisline in ssleay.cnf...
454655714Skris
454755714Skris------BEGIN ms-gencert.cgi-----
454855714Skris#!/bin/sh
454955714SkrisFILE="/tmp/"`date '+%y%m%d%H%M%S'-`$$
455055714Skrisrm -f "$FILE".*
455155714Skris
455255714SkrisHOME=`pwd`; export HOME  # as ssleay.cnf insists on having such an env var
455355714Skriscd /usr/local/ssl #where demoCA (as named in ssleay.conf) is located
455455714Skris
455555714Skrispostit2 -s " " -i 0x0d > "$FILE".inp  # process the FORM vars
455655714Skris
455755714SkrisSESSION_ID=`gawk '$1 == "SessionId" { print $2; exit }' "$FILE".inp`
455855714Skris
455955714Skrisgawk \
456055714Skris	'BEGIN { \
456155714Skris		OFS = ""; \
456255714Skris		print "-----BEGIN CERTIFICATE REQUEST-----"; \
456355714Skris		req_seen=0 \
456455714Skris	} \
456555714Skris	$1 == "Request" { \
456655714Skris		req_seen=1; \
456755714Skris		if (length($2) == 72) print($2); \
456855714Skris		lastline=$2; \
456955714Skris		next; \
457055714Skris	} \
457155714Skris	{ \
457255714Skris		if (req_seen == 1) { \
457355714Skris			if (length($1) >= 72) print($1); \
457455714Skris			else if (length(lastline) < 72) { \
457555714Skris				req_seen=0; \
457655714Skris				print (lastline,$1); \
457755714Skris			} \
457855714Skris		lastline=$1; \
457955714Skris		} \
458055714Skris	} \
458155714Skris	END { \
458255714Skris		print "-----END CERTIFICATE REQUEST-----"; \
458355714Skris	}' > "$FILE".pem < "$FILE".inp 
458455714Skris
458555714Skrisssleay ca -batch -in "$FILE".pem -key passwd -out "$FILE".out
458655714Skrisssleay crl2pkcs7 -certfile "$FILE".out -out "$FILE".pkcs7 -in demoCA/crl.pem
458755714Skris
458855714Skrissed s/template_for_sessId/$SESSION_ID/ <ms-enroll2a.html >"$FILE".cert
458955714Skris/usr/local/bin/gawk \
459055714Skris	'BEGIN	{ \
459155714Skris		OFS = ""; \
459255714Skris		dq = sprintf("%c",34); \
459355714Skris	} \
459455714Skris	$0 ~ "PKCS7" { next; } \
459555714Skris	{ \
459655714Skris		print dq$0dq" & _"; \
459755714Skris	}' <"$FILE".pkcs7 >> "$FILE".cert
459855714Skriscat  ms-enroll2b.html >>"$FILE".cert
459955714Skris
460055714Skrisecho Content-type: text/html
460155714Skrisecho Content-length: `wc -c "$FILE".cert`
460255714Skrisecho
460355714Skriscat "$FILE".cert
460455714Skrisrm -f "$FILE".*
460555714Skris-----END ms-gencert.cgi-----
460655714Skris
460755714Skris----BEGIN ms-enroll2a.html----
460855714Skris<HTML><HEAD><TITLE>Certificate Acceptance Test Page</TITLE></HEAD><BODY>
460955714Skris
461055714Skris<OBJECT
461155714Skris    classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
461255714Skris    codebase=certenr3.dll
461355714Skris    id=certHelper
461455714Skris    >
461555714Skris</OBJECT>
461655714Skris
461755714Skris<CENTER>
461855714Skris<H2>Your personal certificate</H2>
461955714Skris<BR><HR WIDTH=50%><BR><P>
462055714SkrisPress the button!
462155714Skris<P><INPUT TYPE=BUTTON VALUE="Nimm mich!" NAME="InstallCert">
462255714Skris</CENTER>
462355714Skris<BR><HR WIDTH=50%><BR>
462455714Skris
462555714Skris<SCRIPT LANGUAGE=VBS>
462655714Skris    Sub InstallCert_OnClick
462755714Skris
462855714Skris	sessionId	= "template_for_sessId"
462955714Skriscredentials = "" & _
463055714Skris----END ms-enroll2a.html----
463155714Skris
463255714Skris----BEGIN ms-enroll2b.html----
463355714Skris""
463455714Skris        On Error Resume Next
463555714Skris        result = certHelper.AcceptCredentials(sessionId, credentials, 0, 
463655714SkrisFALSE)
463755714Skris        if (IsEmpty(result)) Then
463855714Skris           sz = "The error '" & Err.Number & "' occurred." & chr(13) & 
463955714Skrischr(10) & "This Digital ID could not be registered."
464055714Skris           msgOut = MsgBox(sz, 0, "Credentials Registration Error")
464155714Skris           navigate "error.html"
464255714Skris        else
464355714Skris           sz = "Digital ID successfully registered."
464455714Skris           msgOut = MsgBox(sz, 0, "Credentials Registration")
464555714Skris           navigate "success.html"
464655714Skris        end if
464755714Skris	Exit Sub
464855714Skris    End Sub
464955714Skris</SCRIPT>
465055714Skris</BODY>
465155714Skris</HTML>
465255714Skris----END ms-enroll2b.html----
465355714Skris
465455714Skris4.) What do do with the cert?
465555714Skris-----------------------------
465655714Skris
465755714SkrisThe cert is visible (without restarting MSIE) under the following menu:
465855714SkrisView->Options->Security->Personal certs. You can examine it's contents at 
465955714Skrisleast partially.
466055714Skris
466155714SkrisTo use it for client authentication you need to use SSL3.0 (fortunately 
466255714SkrisSSLeay supports it with 0.8.0). Furthermore MSIE is told to only supports a 
466355714Skriskind of automatic selection of certs (I personally wasn't able to test it 
466455714Skrismyself). But there is a requirement that the issuer of the server cert and 
466555714Skristhe issuer of the client cert needs to be the same (according to a developer 
466655714Skrisfrom MS). Which means: you need may more then one cert to talk to all 
466755714Skrisservers...
466855714Skris
466955714SkrisI'm sure we will get a bit more experience after ApacheSSL is available for 
467055714SkrisSSLeay 0.8.8.
467155714Skris
467255714Skris
467355714SkrisI hope you enjoyed reading and that in future questions on this topic will 
467455714Skrisrarely appear on ssl-users@moncom.com ;-)
467555714Skris
467655714SkrisIlmenau, 9th of June 1997
467755714SkrisHolger Reif <reif@prakinf.tu-ilmenau.de>
467855714Skris-- 
467955714Skrisread you later  -  Holger Reif
468055714Skris----------------------------------------  Signaturprojekt Deutsche Einheit
468155714SkrisTU Ilmenau - Informatik - Telematik                      (Verdamp lang her)
468255714SkrisHolger.Reif@PrakInf.TU-Ilmenau.DE         Alt wie ein Baum werden, um ueber
468355714Skrishttp://Remus.PrakInf.TU-Ilmenau.DE/Reif/  alle 7 Bruecken gehen zu koennen
468455714Skris
468555714Skris
468655714Skris==== ns-ca.doc ========================================================
468755714Skris
468855714SkrisThe following documentation was supplied by Jeff Barber, who provided the
468955714Skrispatch to the CA program to add this functionality.
469055714Skris
469155714Skriseric
469255714Skris--
469355714SkrisJeff Barber                                Email: jeffb@issl.atl.hp.com
469455714Skris
469555714SkrisHewlett Packard                            Phone: (404) 648-9503
469655714SkrisInternet and System Security Lab           Fax:   (404) 648-9516
469755714Skris
469855714Skris                         oo
469955714Skris---------------------cut /\ here for ns-ca.doc ------------------------------
470055714Skris
470155714SkrisThis document briefly describes how to use SSLeay to implement a 
470255714Skriscertificate authority capable of dynamically serving up client
470355714Skriscertificates for version 3.0 beta 5 (and presumably later) versions of
470455714Skristhe Netscape Navigator.  Before describing how this is done, it's
470555714Skrisimportant to understand a little about how the browser implements its
470655714Skrisclient certificate support.  This is documented in some detail in the
470755714SkrisURLs based at <URL:http://home.netscape.com/eng/security/certs.html>.
470855714SkrisHere's a brief overview:
470955714Skris
471055714Skris-	The Navigator supports a new HTML tag "KEYGEN" which will cause
471155714Skris	the browser to generate an RSA key pair when you submit a form
471255714Skris	containing the tag.  The public key, along with an optional
471355714Skris	challenge (supposedly provided for use in certificate revocation
471455714Skris	but I don't use it) is signed, DER-encoded, base-64 encoded
471555714Skris	and sent to the web server as the value of the variable
471655714Skris	whose NAME is provided in the KEYGEN tag.  The private key is
471755714Skris	stored by the browser in a local key database.
471855714Skris
471955714Skris	This "Signed Public Key And Challenge" (SPKAC) arrives formatted
472055714Skris	into 64 character lines (which are of course URL-encoded when 
472155714Skris	sent via HTTP -- i.e. spaces, newlines and most punctuatation are
472255714Skris	encoded as "%HH" where HH is the hex equivalent of the ASCII code).
472355714Skris	Note that the SPKAC does not contain the other usual attributes
472455714Skris	of a certificate request, especially the subject name fields.
472555714Skris	These must be otherwise encoded in the form for submission along
472655714Skris	with the SPKAC.
472755714Skris
472855714Skris-	Either immediately (in response to this form submission), or at
472955714Skris	some later date (a real CA will probably verify your identity in
473055714Skris	some way before issuing the certificate), a web server can send a
473155714Skris	certificate based on the public key and other attributes back to
473255714Skris	the browser by encoding it in DER (the binary form) and sending it
473355714Skris	to the browser as MIME type:
473455714Skris	"Content-type: application/x-x509-user-cert"
473555714Skris
473655714Skris	The browser uses the public key encoded in the certificate to
473755714Skris	associate the certificate with the appropriate private key in
473855714Skris	its local key database.  Now, the certificate is "installed".
473955714Skris
474055714Skris-	When a server wants to require authentication based on client
474155714Skris	certificates, it uses the right signals via the SSL protocol to
474255714Skris	trigger the Navigator to ask you which certificate you want to
474355714Skris	send.  Whether the certificate is accepted is dependent on CA
474455714Skris	certificates and so forth installed in the server and is beyond
474555714Skris	the scope of this document.
474655714Skris
474755714Skris
474855714SkrisNow, here's how the SSLeay package can be used to provide client 
474955714Skriscertficates:
475055714Skris
475155714Skris-	You prepare a file for input to the SSLeay ca application.
475255714Skris	The file contains a number of "name = value" pairs that identify
475355714Skris	the subject.  The names here are the same subject name component
475455714Skris	identifiers used in the CA section of the lib/ssleay.conf file,
475555714Skris	such as "emailAddress", "commonName" "organizationName" and so
475655714Skris	forth.  Both the long version and the short version (e.g. "Email",
475755714Skris	"CN", "O") can be used.
475855714Skris
475955714Skris	One more name is supported: this one is "SPKAC".  Its value
476055714Skris	is simply the value of the base-64 encoded SPKAC sent by the
476155714Skris	browser (with all the newlines and other space charaters
476255714Skris	removed -- and newline escapes are NOT supported).
476355714Skris
476455714Skris	[ As of SSLeay 0.6.4, multiple lines are supported.
476555714Skris	  Put a \ at the end of each line and it will be joined with the
476655714Skris	  previous line with the '\n' removed - eay ]
476755714Skris	
476855714Skris	Here's a sample input file:
476955714Skris
477055714SkrisC = US
477155714SkrisSP = Georgia
477255714SkrisO = Some Organization, Inc.
477355714SkrisOU = Netscape Compatibility Group
477455714SkrisCN = John X. Doe
477555714SkrisEmail = jxdoe@someorg.com
477655714SkrisSPKAC = MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAwmk6FMJ4uAVIYbcvIOx5+bDGTfvL8X5gE+R67ccMk6rCSGbVQz2cetyQtnI+VIs0NwdD6wjuSuVtVFbLoHonowIDAQABFgAwDQYJKoZIhvcNAQEEBQADQQBFZDUWFl6BJdomtN1Bi53mwijy1rRgJ4YirF15yBEDM3DjAQkKXHYOIX+qpz4KXKnl6EYxTnGSFL5wWt8X2iyx
477755714Skris
477855714Skris-	You execute the ca command (either from a CGI program run out of
477955714Skris	the web server, or as a later manual task) giving it the above
478055714Skris	file as input.  For example, if the file were named /tmp/cert.req,
478155714Skris	you'd run:
478255714Skris	$SSLDIR/bin/ca -spkac /tmp/cert.req -out /tmp/cert
478355714Skris
478455714Skris	The output is in DER format (binary) if a -out argument is 
478555714Skris	provided, as above; otherwise, it's in the PEM format (base-64
478655714Skris	encoded DER).  Also, the "-batch" switch is implied by the
478755714Skris	"-spkac" so you don't get asked whether to complete the signing
478855714Skris	(probably it shouldn't work this way but I was only interested
478955714Skris	in hacking together an online CA that could be used for issuing
479055714Skris	test certificates).
479155714Skris
479255714Skris	The "-spkac" capability doesn't support multiple files (I think).
479355714Skris
479455714Skris	Any CHALLENGE provided in the SPKAC is simply ignored.
479555714Skris
479655714Skris	The interactions between the identification fields you provide
479755714Skris	and those identified in your lib/ssleay.conf are the same as if
479855714Skris	you did an ordinary "ca -in infile -out outfile" -- that is, if
479955714Skris	something is marked as required in the ssleay.conf file and it
480055714Skris	isn't found in the -spkac file, the certificate won't be issued.
480155714Skris
480255714Skris-	Now, you pick up the output from /tmp/cert and pass it back to
480355714Skris	the Navigator prepending the Content-type string described earlier.
480455714Skris
480555714Skris-	In order to run the ca command out of a CGI program, you must
480655714Skris	provide a password to decrypt the CA's private key.  You can
480755714Skris	do this by using "echo MyKeyPassword | $SSLDIR/bin/ca ..."
480855714Skris	I think there's a way to not encrypt the key file in the first
480955714Skris	place, but I didn't see how to do that, so I made a small change
481055714Skris	to the library that allows the password to be accepted from a pipe.
481155714Skris	Either way is UTTERLY INSECURE and a real CA would never do that.
481255714Skris
481355714Skris	[ You can use the 'ssleay rsa' command to remove the password
481455714Skris	  from the private key, or you can use the '-key' option to the
481555714Skris	  ca command to specify the decryption key on the command line
481655714Skris	  or use the -nodes option when generating the key.
481755714Skris	  ca will try to clear the command line version of the password
481855714Skris	  but for quite a few operating systems, this is not possible.
481955714Skris	  - eric ]
482055714Skris
482155714SkrisSo, what do you have to do to make use of this stuff to create an online 
482255714Skrisdemo CA capability with SSLeay?
482355714Skris
482455714Skris1	Create an HTML form for your users.  The form should contain
482555714Skris	fields for all of the required or optional fields in ssleay.conf.
482655714Skris	The form must contain a KEYGEN tag somewhere with at least a NAME
482755714Skris	attribute.
482855714Skris
482955714Skris2	Create a CGI program to process the form input submitted by the
483055714Skris	browser.  The CGI program must URL-decode the variables and create
483155714Skris	the file described above, containing subject identification info
483255714Skris	as well as the SPKAC block.  It should then run the the ca program
483355714Skris	with the -spkac option.  If it works (check the exit status),
483455714Skris	return the new certificate with the appropriate MIME type.  If not,
483555714Skris	return the output of the ca command with MIME type "text/plain".
483655714Skris
483755714Skris3	Set up your web server to accept connections signed by your demo
483855714Skris	CA.  This probably involves obtaining the PEM-encoded CA certificate
483955714Skris	(ordinarily in $SSLDIR/CA/cacert.pem) and installing it into a
484055714Skris	server database.  See your server manual for instructions.
484155714Skris
484255714Skris
484355714Skris==== obj.doc ========================================================
484455714Skris
484555714SkrisThe Object library.
484655714Skris
484755714SkrisAs part of my Crypto library, I found I required a method of identifying various
484855714Skrisobjects.  These objects normally had 3 different values associated with
484955714Skristhem, a short text name, a long (or lower case) text name, and an
485055714SkrisASN.1 Object Identifier (which is a sequence of numbers).
485155714SkrisThis library contains a static list of objects and functions to lookup
485255714Skrisaccording to one type and to return the other types.
485355714Skris
485455714SkrisTo use these routines, 'Object.h' needs to be included.
485555714Skris
485655714SkrisFor each supported object, #define entries are defined as follows
485755714Skris#define SN_Algorithm			"Algorithm"
485855714Skris#define LN_algorithm			"algorithm"
485955714Skris#define NID_algorithm			38
486055714Skris#define OBJ_algorithm			1L,3L,14L,3L,2L
486155714Skris
486255714SkrisSN_  stands for short name.
486355714SkrisLN_  stands for either long name or lowercase name.
486455714SkrisNID_ stands for Numeric ID.  I each object has a unique NID and this
486555714Skris     should be used internally to identify objects.
486655714SkrisOBJ_ stands for ASN.1 Object Identifier or ASN1_OBJECT as defined in the
486755714Skris     ASN1 routines.  These values are used in ASN1 encoding.
486855714Skris
486955714SkrisThe following functions are to be used to return pointers into a static
487055714Skrisdefinition of these types.  What this means is "don't try to free() any
487155714Skrispointers returned from these functions.
487255714Skris
487355714SkrisASN1_OBJECT *OBJ_nid2obj(
487455714Skrisint n);
487555714Skris	Return the ASN1_OBJECT that corresponds to a NID of n.
487655714Skris	
487755714Skrischar *OBJ_nid2ln(
487855714Skrisint n);
487955714Skris	Return the long/lower case name of the object represented by the
488055714Skris	NID of n.
488155714Skris	
488255714Skrischar *OBJ_nid2sn(
488355714Skrisint n);
488455714Skris	Return the short name for the object represented by the NID of n.
488555714Skris
488655714SkrisASN1_OBJECT *OBJ_dup(
488755714SkrisASN1_OBJECT *o);
488855714Skris	Duplicate and return a new ASN1_OBJECT that is the same as the
488955714Skris	passed parameter.
489055714Skris	
489155714Skrisint OBJ_obj2nid(
489255714SkrisASN1_OBJECT *o);
489355714Skris	Given ASN1_OBJECT o, return the NID that corresponds.
489455714Skris	
489555714Skrisint OBJ_ln2nid(
489655714Skrischar *s);
489755714Skris	Given the long/lower case name 's', return the NID of the object.
489855714Skris	
489955714Skrisint OBJ_sn2nid(
490055714Skrischar *s);
490155714Skris	Given the short name 's', return the NID of the object.
490255714Skris	
490355714Skrischar *OBJ_bsearch(
490455714Skrischar *key,
490555714Skrischar *base,
490655714Skrisint num,
490755714Skrisint size,
490855714Skrisint (*cmp)());
490955714Skris	Since I have come across a few platforms that do not have the
491055714Skris	bsearch() function, OBJ_bsearch is my version of that function.
491155714Skris	Feel free to use this function, but you may as well just use the
491255714Skris	normal system bsearch(3) if it is present.  This version also
491355714Skris	has tolerance of being passed NULL pointers.
491455714Skris
491555714Skris==== keys ===========================================================
491655714Skris
491755714SkrisEVP_PKEY_DSA
491855714SkrisEVP_PKEY_DSA2
491955714SkrisEVP_PKEY_DSA3
492055714SkrisEVP_PKEY_DSA4
492155714Skris
492255714SkrisEVP_PKEY_RSA
492355714SkrisEVP_PKEY_RSA2
492455714Skris
492555714Skrisvalid DSA pkey types
492655714Skris	NID_dsa
492755714Skris	NID_dsaWithSHA
492855714Skris	NID_dsaWithSHA1
492955714Skris	NID_dsaWithSHA1_2
493055714Skris
493155714Skrisvalid RSA pkey types
493255714Skris	NID_rsaEncryption
493355714Skris	NID_rsa
493455714Skris
493555714SkrisNID_dsaWithSHA	NID_dsaWithSHA			DSA		SHA
493655714SkrisNID_dsa		NID_dsaWithSHA1			DSA		SHA1
493755714SkrisNID_md2		NID_md2WithRSAEncryption	RSA-pkcs1	MD2
493855714SkrisNID_md5		NID_md5WithRSAEncryption	RSA-pkcs1	MD5
493955714SkrisNID_mdc2	NID_mdc2WithRSA			RSA-none	MDC2
494055714SkrisNID_ripemd160	NID_ripemd160WithRSA		RSA-pkcs1	RIPEMD160
494155714SkrisNID_sha		NID_shaWithRSAEncryption	RSA-pkcs1	SHA
494255714SkrisNID_sha1	NID_sha1WithRSAEncryption	RSA-pkcs1	SHA1
494355714Skris
494455714Skris==== rand.doc ========================================================
494555714Skris
494655714SkrisMy Random number library.
494755714Skris
494855714SkrisThese routines can be used to generate pseudo random numbers and can be
494955714Skrisused to 'seed' the pseudo random number generator (RNG).  The RNG make no
495055714Skriseffort to reproduce the same random number stream with each execution.
495155714SkrisVarious other routines in the SSLeay library 'seed' the RNG when suitable
495255714Skris'random' input data is available.  Read the section at the end for details
495355714Skrison the design of the RNG.
495455714Skris
495555714Skrisvoid RAND_bytes(
495655714Skrisunsigned char *buf,
495755714Skrisint num);
495855714Skris	This routine puts 'num' random bytes into 'buf'.  One should make
495955714Skris	sure RAND_seed() has been called before using this routine.
496055714Skris	
496155714Skrisvoid RAND_seed(
496255714Skrisunsigned char *buf,
496355714Skrisint num);
496455714Skris	This routine adds more 'seed' data the RNG state.  'num' bytes
496555714Skris	are added to the RNG state, they are taken from 'buf'.  This
496655714Skris	routine can be called with sensitive data such as user entered
496755714Skris	passwords.  This sensitive data is in no way recoverable from
496855714Skris	the RAND library routines or state.  Try to pass as much data
496955714Skris	from 'random' sources as possible into the RNG via this function.
497055714Skris	Also strongly consider using the RAND_load_file() and
497155714Skris	RAND_write_file() routines.
497255714Skris
497355714Skrisvoid RAND_cleanup();
497455714Skris	When a program has finished with the RAND library, if it so
497555714Skris	desires, it can 'zero' all RNG state.
497655714Skris	
497755714SkrisThe following 3 routines are convenience routines that can be used to
497855714Skris'save' and 'restore' data from/to the RNG and it's state.
497955714SkrisSince the more 'random' data that is feed as seed data the better, why not
498055714Skriskeep it around between executions of the program?  Of course the
498155714Skrisapplication should pass more 'random' data in via RAND_seed() and 
498255714Skrismake sure no-one can read the 'random' data file.
498355714Skris	
498455714Skrischar *RAND_file_name(
498555714Skrischar *buf,
498655714Skrisint size);
498755714Skris	This routine returns a 'default' name for the location of a 'rand'
498855714Skris	file.  The 'rand' file should keep a sequence of random bytes used
498955714Skris	to initialise the RNG.  The filename is put in 'buf'.  Buf is 'size'
499055714Skris	bytes long.  Buf is returned if things go well, if they do not,
499155714Skris	NULL is returned.  The 'rand' file name is generated in the
499255714Skris	following way.  First, if there is a 'RANDFILE' environment
499355714Skris	variable, it is returned.  Second, if there is a 'HOME' environment
499455714Skris	variable, $HOME/.rand is returned.  Third, NULL is returned.  NULL
499555714Skris	is also returned if a buf would overflow.
499655714Skris
499755714Skrisint RAND_load_file(
499855714Skrischar *file,
499955714Skrislong number);
500055714Skris	This function 'adds' the 'file' into the RNG state.  It does this by
500155714Skris	doing a RAND_seed() on the value returned from a stat() system call
500255714Skris	on the file and if 'number' is non-zero, upto 'number' bytes read
500355714Skris	from the file.  The number of bytes passed to RAND_seed() is returned.
500455714Skris
500555714Skrisint RAND_write_file(
500655714Skrischar *file),
500755714Skris	RAND_write_file() writes N random bytes to the file 'file', where
500855714Skris	N is the size of the internal RND state (currently 1k).
500955714Skris	This is a suitable method of saving RNG state for reloading via
501055714Skris	RAND_load_file().
501155714Skris
501255714SkrisWhat follows is a description of this RNG and a description of the rational
501355714Skrisbehind it's design.
501455714Skris
501555714SkrisIt should be noted that this RNG is intended to be used to generate
501655714Skris'random' keys for various ciphers including generation of DH and RSA keys.  
501755714Skris
501855714SkrisIt should also be noted that I have just created a system that I am happy with.
501955714SkrisIt may be overkill but that does not worry me.  I have not spent that much
502055714Skristime on this algorithm so if there are glaring errors, please let me know.
502155714SkrisSpeed has not been a consideration in the design of these routines.
502255714Skris
502355714SkrisFirst up I will state the things I believe I need for a good RNG.
502455714Skris1) A good hashing algorithm to mix things up and to convert the RNG 'state'
502555714Skris   to random numbers.
502655714Skris2) An initial source of random 'state'.
502755714Skris3) The state should be very large.  If the RNG is being used to generate
502855714Skris   4096 bit RSA keys, 2 2048 bit random strings are required (at a minimum).
502955714Skris   If your RNG state only has 128 bits, you are obviously limiting the
503055714Skris   search space to 128 bits, not 2048.  I'm probably getting a little
503155714Skris   carried away on this last point but it does indicate that it may not be
503255714Skris   a bad idea to keep quite a lot of RNG state.  It should be easier to
503355714Skris   break a cipher than guess the RNG seed data.
503455714Skris4) Any RNG seed data should influence all subsequent random numbers
503555714Skris   generated.  This implies that any random seed data entered will have
503655714Skris   an influence on all subsequent random numbers generated.
503755714Skris5) When using data to seed the RNG state, the data used should not be
503855714Skris   extractable from the RNG state.  I believe this should be a
503955714Skris   requirement because one possible source of 'secret' semi random
504055714Skris   data would be a private key or a password.  This data must
504155714Skris   not be disclosed by either subsequent random numbers or a
504255714Skris   'core' dump left by a program crash.
504355714Skris6) Given the same initial 'state', 2 systems should deviate in their RNG state
504455714Skris   (and hence the random numbers generated) over time if at all possible.
504555714Skris7) Given the random number output stream, it should not be possible to determine
504655714Skris   the RNG state or the next random number.
504755714Skris
504855714Skris
504955714SkrisThe algorithm is as follows.
505055714Skris
505155714SkrisThere is global state made up of a 1023 byte buffer (the 'state'), a
505255714Skrisworking message digest ('md') and a counter ('count').
505355714Skris
505455714SkrisWhenever seed data is added, it is inserted into the 'state' as
505555714Skrisfollows.
505655714Skris	The input is chopped up into units of 16 bytes (or less for
505755714Skris	the last block).  Each of these blocks is run through the MD5
505855714Skris	message digest.  The data passed to the MD5 digest is the
505955714Skris	current 'md', the same number of bytes from the 'state'
506055714Skris	(the location determined by in incremented looping index) as
506155714Skris	the current 'block' and the new key data 'block'.  The result
506255714Skris	of this is kept in 'md' and also xored into the 'state' at the
506355714Skris	same locations that were used as input into the MD5.
506455714Skris	I believe this system addresses points 1 (MD5), 3 (the 'state'),
506555714Skris	4 (via the 'md'), 5 (by the use of MD5 and xor).
506655714Skris
506755714SkrisWhen bytes are extracted from the RNG, the following process is used.
506855714SkrisFor each group of 8 bytes (or less), we do the following,
506955714Skris	Input into MD5, the top 8 bytes from 'md', the byte that are
507055714Skris	to be overwritten by the random bytes and bytes from the
507155714Skris	'state' (incrementing looping index).  From this digest output
507255714Skris	(which is kept in 'md'), the top (upto) 8 bytes are
507355714Skris	returned to the caller and the bottom (upto) 8 bytes are xored
507455714Skris	into the 'state'.
507555714Skris	Finally, after we have finished 'generation' random bytes for the
507655714Skris	called, 'count' (which is incremented) and 'md' are fed into MD5 and
507755714Skris	the results are kept in 'md'.
507855714Skris	I believe the above addressed points 1 (use of MD5), 6 (by
507955714Skris	hashing into the 'state' the 'old' data from the caller that
508055714Skris	is about to be overwritten) and 7 (by not using the 8 bytes
508155714Skris	given to the caller to update the 'state', but they are used
508255714Skris	to update 'md').
508355714Skris
508455714SkrisSo of the points raised, only 2 is not addressed, but sources of
508555714Skrisrandom data will always be a problem.
508655714Skris	
508755714Skris
508855714Skris==== rc2.doc ========================================================
508955714Skris
509055714SkrisThe RC2 library.
509155714Skris
509255714SkrisRC2 is a block cipher that operates on 64bit (8 byte) quantities.  It
509355714Skrisuses variable size key, but 128bit (16 byte) key would normally be considered
509455714Skrisgood.  It can be used in all the modes that DES can be used.  This
509555714Skrislibrary implements the ecb, cbc, cfb64, ofb64 modes.
509655714Skris
509755714SkrisI have implemented this library from an article posted to sci.crypt on
509855714Skris11-Feb-1996.  I personally don't know how far to trust the RC2 cipher.
509955714SkrisWhile it is capable of having a key of any size, not much reseach has
510055714Skrispublically been done on it at this point in time (Apr-1996)
510155714Skrissince the cipher has only been public for a few months :-)
510255714SkrisIt is of a similar speed to DES and IDEA, so unless it is required for
510355714Skrismeeting some standard (SSLv2, perhaps S/MIME), it would probably be advisable
510455714Skristo stick to IDEA, or for the paranoid, Tripple DES.
510555714Skris
510655714SkrisMind you, having said all that, I should mention that I just read alot and
510755714Skrisimplement ciphers, I'm a 'babe in the woods' when it comes to evaluating
510855714Skrisciphers :-).
510955714Skris
511055714SkrisFor all calls that have an 'input' and 'output' variables, they can be the
511155714Skrissame.
511255714Skris
511355714SkrisThis library requires the inclusion of 'rc2.h'.
511455714Skris
511555714SkrisAll of the encryption functions take what is called an RC2_KEY as an 
511655714Skrisargument.  An RC2_KEY is an expanded form of the RC2 key.
511755714SkrisFor all modes of the RC2 algorithm, the RC2_KEY used for
511855714Skrisdecryption is the same one that was used for encryption.
511955714Skris
512055714SkrisThe define RC2_ENCRYPT is passed to specify encryption for the functions
512155714Skristhat require an encryption/decryption flag. RC2_DECRYPT is passed to
512255714Skrisspecify decryption.
512355714Skris
512455714SkrisPlease note that any of the encryption modes specified in my DES library
512555714Skriscould be used with RC2.  I have only implemented ecb, cbc, cfb64 and
512655714Skrisofb64 for the following reasons.
512755714Skris- ecb is the basic RC2 encryption.
512855714Skris- cbc is the normal 'chaining' form for block ciphers.
512955714Skris- cfb64 can be used to encrypt single characters, therefore input and output
513055714Skris  do not need to be a multiple of 8.
513155714Skris- ofb64 is similar to cfb64 but is more like a stream cipher, not as
513255714Skris  secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
513355714Skris- If you want triple RC2, thats 384 bits of key and you must be totally
513455714Skris  obsessed with security.  Still, if you want it, it is simple enough to
513555714Skris  copy the function from the DES library and change the des_encrypt to
513655714Skris  RC2_encrypt; an exercise left for the paranoid reader :-).
513755714Skris
513855714SkrisThe functions are as follows:
513955714Skris
514055714Skrisvoid RC2_set_key(
514155714SkrisRC2_KEY *ks;
514255714Skrisint len;
514355714Skrisunsigned char *key;
514455714Skrisint bits;
514555714Skris        RC2_set_key converts an 'len' byte key into a RC2_KEY.
514655714Skris        A 'ks' is an expanded form of the 'key' which is used to
514755714Skris        perform actual encryption.  It can be regenerated from the RC2 key
514855714Skris        so it only needs to be kept when encryption or decryption is about
514955714Skris        to occur.  Don't save or pass around RC2_KEY's since they
515055714Skris        are CPU architecture dependent, 'key's are not.  RC2 is an
515155714Skris	interesting cipher in that it can be used with a variable length
515255714Skris	key.  'len' is the length of 'key' to be used as the key.
515355714Skris	A 'len' of 16 is recomended.  The 'bits' argument is an
515455714Skris	interesting addition which I only found out about in Aug 96.
515555714Skris	BSAFE uses this parameter to 'limit' the number of bits used
515655714Skris	for the key.  To use the 'key' unmodified, set bits to 1024.
515755714Skris	This is what old versions of my RC2 library did (SSLeay 0.6.3).
515855714Skris	RSAs BSAFE library sets this parameter to be 128 if 128 bit
515955714Skris	keys are being used.  So to be compatable with BSAFE, set it
516055714Skris	to 128, if you don't want to reduce RC2's key length, leave it
516155714Skris	at 1024.
516255714Skris	
516355714Skrisvoid RC2_encrypt(
516455714Skrisunsigned long *data,
516555714SkrisRC2_KEY *key,
516655714Skrisint encrypt);
516755714Skris	This is the RC2 encryption function that gets called by just about
516855714Skris	every other RC2 routine in the library.  You should not use this
516955714Skris	function except to implement 'modes' of RC2.  I say this because the
517055714Skris	functions that call this routine do the conversion from 'char *' to
517155714Skris	long, and this needs to be done to make sure 'non-aligned' memory
517255714Skris	access do not occur.
517355714Skris	Data is a pointer to 2 unsigned long's and key is the
517455714Skris	RC2_KEY to use.  Encryption or decryption is indicated by 'encrypt'.
517555714Skris	which can have the values RC2_ENCRYPT or RC2_DECRYPT.
517655714Skris
517755714Skrisvoid RC2_ecb_encrypt(
517855714Skrisunsigned char *in,
517955714Skrisunsigned char *out,
518055714SkrisRC2_KEY *key,
518155714Skrisint encrypt);
518255714Skris	This is the basic Electronic Code Book form of RC2 (in DES this
518355714Skris	mode is called Electronic Code Book so I'm going to use the term
518455714Skris	for rc2 as well.
518555714Skris	Input is encrypted into output using the key represented by
518655714Skris	key.  Depending on the encrypt, encryption or
518755714Skris	decryption occurs.  Input is 8 bytes long and output is 8 bytes.
518855714Skris	
518955714Skrisvoid RC2_cbc_encrypt(
519055714Skrisunsigned char *in,
519155714Skrisunsigned char *out,
519255714Skrislong length,
519355714SkrisRC2_KEY *ks,
519455714Skrisunsigned char *ivec,
519555714Skrisint encrypt);
519655714Skris	This routine implements RC2 in Cipher Block Chaining mode.
519755714Skris	Input, which should be a multiple of 8 bytes is encrypted
519855714Skris	(or decrypted) to output which will also be a multiple of 8 bytes.
519955714Skris	The number of bytes is in length (and from what I've said above,
520055714Skris	should be a multiple of 8).  If length is not a multiple of 8, bad 
520155714Skris	things will probably happen.  ivec is the initialisation vector.
520255714Skris	This function updates iv after each call so that it can be passed to
520355714Skris	the next call to RC2_cbc_encrypt().
520455714Skris	
520555714Skrisvoid RC2_cfb64_encrypt(
520655714Skrisunsigned char *in,
520755714Skrisunsigned char *out,
520855714Skrislong length,
520955714SkrisRC2_KEY *schedule,
521055714Skrisunsigned char *ivec,
521155714Skrisint *num,
521255714Skrisint encrypt);
521355714Skris	This is one of the more useful functions in this RC2 library, it
521455714Skris	implements CFB mode of RC2 with 64bit feedback.
521555714Skris	This allows you to encrypt an arbitrary number of bytes,
521655714Skris	you do not require 8 byte padding.  Each call to this
521755714Skris	routine will encrypt the input bytes to output and then update ivec
521855714Skris	and num.  Num contains 'how far' we are though ivec.
521955714Skris	'Encrypt' is used to indicate encryption or decryption.
522055714Skris	CFB64 mode operates by using the cipher to generate a stream
522155714Skris	of bytes which is used to encrypt the plain text.
522255714Skris	The cipher text is then encrypted to generate the next 64 bits to
522355714Skris	be xored (incrementally) with the next 64 bits of plain
522455714Skris	text.  As can be seen from this, to encrypt or decrypt,
522555714Skris	the same 'cipher stream' needs to be generated but the way the next
522655714Skris	block of data is gathered for encryption is different for
522755714Skris	encryption and decryption.
522855714Skris	
522955714Skrisvoid RC2_ofb64_encrypt(
523055714Skrisunsigned char *in,
523155714Skrisunsigned char *out,
523255714Skrislong length,
523355714SkrisRC2_KEY *schedule,
523455714Skrisunsigned char *ivec,
523555714Skrisint *num);
523655714Skris	This functions implements OFB mode of RC2 with 64bit feedback.
523755714Skris	This allows you to encrypt an arbitrary number of bytes,
523855714Skris	you do not require 8 byte padding.  Each call to this
523955714Skris	routine will encrypt the input bytes to output and then update ivec
524055714Skris	and num.  Num contains 'how far' we are though ivec.
524155714Skris	This is in effect a stream cipher, there is no encryption or
524255714Skris	decryption mode.
524355714Skris	
524455714SkrisFor reading passwords, I suggest using des_read_pw_string() from my DES library.
524555714SkrisTo generate a password from a text string, I suggest using MD5 (or MD2) to
524655714Skrisproduce a 16 byte message digest that can then be passed directly to
524755714SkrisRC2_set_key().
524855714Skris
524955714Skris=====
525055714SkrisFor more information about the specific RC2 modes in this library
525155714Skris(ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
525255714Skrisdocumentation on my DES library.  What is said about DES is directly
525355714Skrisapplicable for RC2.
525455714Skris
525555714Skris
525655714Skris==== rc4.doc ========================================================
525755714Skris
525855714SkrisThe RC4 library.
525955714SkrisRC4 is a stream cipher that operates on a byte stream.  It can be used with
526055714Skrisany length key but I would recommend normally using 16 bytes.
526155714Skris
526255714SkrisThis library requires the inclusion of 'rc4.h'.
526355714Skris
526455714SkrisThe RC4 encryption function takes what is called an RC4_KEY as an argument.
526555714SkrisThe RC4_KEY is generated by the RC4_set_key function from the key bytes.
526655714Skris
526755714SkrisRC4, being a stream cipher, does not have an encryption or decryption mode.
526855714SkrisIt produces a stream of bytes that the input stream is xor'ed against and
526955714Skrisso decryption is just a case of 'encrypting' again with the same key.
527055714Skris
527155714SkrisI have only put in one 'mode' for RC4 which is the normal one.  This means
527255714Skristhere is no initialisation vector and there is no feedback of the cipher
527355714Skristext into the cipher.  This implies that you should not ever use the
527455714Skrissame key twice if you can help it.  If you do, you leave yourself open to
527555714Skrisknown plain text attacks; if you know the plain text and
527655714Skriscorresponding cipher text in one message, all messages that used the same
527755714Skriskey can have the cipher text decoded for the corresponding positions in the
527855714Skriscipher stream.
527955714Skris
528055714SkrisThe main positive feature of RC4 is that it is a very fast cipher; about 4
528155714Skristimes faster that DES.  This makes it ideally suited to protocols where the
528255714Skriskey is randomly chosen, like SSL.
528355714Skris
528455714SkrisThe functions are as follows:
528555714Skris
528655714Skrisvoid RC4_set_key(
528755714SkrisRC4_KEY *key;
528855714Skrisint len;
528955714Skrisunsigned char *data);
529055714Skris	This function initialises the RC4_KEY structure with the key passed
529155714Skris	in 'data', which is 'len' bytes long.  The key data can be any
529255714Skris	length but 16 bytes seems to be a good number.
529355714Skris
529455714Skrisvoid RC4(
529555714SkrisRC4_KEY *key;
529655714Skrisunsigned long len;
529755714Skrisunsigned char *in;
529855714Skrisunsigned char *out);
529955714Skris	Do the actual RC4 encryption/decryption.  Using the 'key', 'len'
530055714Skris	bytes are transformed from 'in' to 'out'.  As mentioned above,
530155714Skris	decryption is the operation as encryption.
530255714Skris
530355714Skris==== ref.doc ========================================================
530455714Skris
530555714SkrisI have lots more references etc, and will update this list in the future,
530655714Skris30 Aug 1996 - eay
530755714Skris
530855714Skris
530955714SkrisSSL	The SSL Protocol - from Netscapes.
531055714Skris
531155714SkrisRC4	Newsgroups: sci.crypt
531255714Skris	From: sterndark@netcom.com (David Sterndark)
531355714Skris	Subject: RC4 Algorithm revealed.
531455714Skris	Message-ID: <sternCvKL4B.Hyy@netcom.com>
531555714Skris
531655714SkrisRC2	Newsgroups: sci.crypt
531755714Skris	From: pgut01@cs.auckland.ac.nz (Peter Gutmann)
531855714Skris	Subject: Specification for Ron Rivests Cipher No.2
531955714Skris	Message-ID: <4fk39f$f70@net.auckland.ac.nz>
532055714Skris
532155714SkrisMD2	RFC1319 The MD2 Message-Digest Algorithm
532255714SkrisMD5	RFC1321 The MD5 Message-Digest Algorithm
532355714Skris
532455714SkrisX509 Certificates
532555714Skris	RFC1421 Privacy Enhancement for Internet Electronic Mail: Part I
532655714Skris	RFC1422 Privacy Enhancement for Internet Electronic Mail: Part II
532755714Skris	RFC1423 Privacy Enhancement for Internet Electronic Mail: Part III
532855714Skris	RFC1424 Privacy Enhancement for Internet Electronic Mail: Part IV
532955714Skris
533055714SkrisRSA and various standard encoding
533155714Skris	PKCS#1 RSA Encryption Standard
533255714Skris	PKCS#5 Password-Based Encryption Standard
533355714Skris	PKCS#7 Cryptographic Message Syntax Standard
533455714Skris	A Layman's Guide to a Subset of ASN.1, BER, and DER
533555714Skris	An Overview of the PKCS Standards
533655714Skris	Some Examples of the PKCS Standards
533755714Skris
533855714SkrisIDEA	Chapter 3 The Block Cipher IDEA
533955714Skris
534055714SkrisRSA, prime number generation and bignum algorithms
534155714Skris	Introduction To Algorithms,
534255714Skris	Thomas Cormen, Charles Leiserson, Ronald Rivest,
534355714Skris	Section 29 Arithmetic Circuits
534455714Skris	Section 33 Number-Theoretic Algorithms
534555714Skris
534655714SkrisFast Private Key algorithm
534755714Skris	Fast Decipherment Algorithm for RSA Public-Key Cryptosystem
534855714Skris	J.-J. Quisquater and C. Couvreur, Electronics Letters,
534955714Skris	14th October 1982, Vol. 18 No. 21
535055714Skris
535155714SkrisPrime number generation and bignum algorithms.
535255714Skris	PGP-2.3a
535355714Skris
535455714Skris==== rsa.doc ========================================================
535555714Skris
535655714SkrisThe RSA encryption and utility routines.
535755714Skris
535855714SkrisThe RSA routines are built on top of a big number library (the BN library).
535955714SkrisThere are support routines in the X509 library for loading and manipulating
536055714Skristhe various objects in the RSA library.  When errors are returned, read
536155714Skrisabout the ERR library for how to access the error codes.
536255714Skris
536355714SkrisAll RSA encryption is done according to the PKCS-1 standard which is
536455714Skriscompatible with PEM and RSAref.  This means that any values being encrypted
536555714Skrismust be less than the size of the modulus in bytes, minus 10, bytes long.
536655714Skris
536755714SkrisThis library uses RAND_bytes()() for it's random data, make sure to feed
536855714SkrisRAND_seed() with lots of interesting and varied data before using these
536955714Skrisroutines.
537055714Skris
537155714SkrisThe RSA library has one specific data type, the RSA structure.
537255714SkrisIt is composed of 8 BIGNUM variables (see the BN library for details) and
537355714Skriscan hold either a private RSA key or a public RSA key.
537455714SkrisSome RSA libraries have different structures for public and private keys, I
537555714Skrisdon't.  For my libraries, a public key is determined by the fact that the
537655714SkrisRSA->d value is NULL.  These routines will operate on any size RSA keys.
537755714SkrisWhile I'm sure 4096 bit keys are very very secure, they take a lot longer
537855714Skristo process that 1024 bit keys :-).
537955714Skris
538055714SkrisThe function in the RSA library are as follows.
538155714Skris
538255714SkrisRSA *RSA_new();
538355714Skris	This function creates a new RSA object.  The sub-fields of the RSA
538455714Skris	type are also malloced so you should always use this routine to
538555714Skris	create RSA variables.
538655714Skris	
538755714Skrisvoid RSA_free(
538855714SkrisRSA *rsa);
538955714Skris	This function 'frees' an RSA structure.  This routine should always
539055714Skris	be used to free the RSA structure since it will also 'free' any
539155714Skris	sub-fields of the RSA type that need freeing.
539255714Skris	
539355714Skrisint RSA_size(
539455714SkrisRSA *rsa);	
539555714Skris	This function returns the size of the RSA modulus in bytes.  Why do
539655714Skris	I need this you may ask, well the reason is that when you encrypt
539755714Skris	with RSA, the output string will be the size of the RSA modulus.
539855714Skris	So the output for the RSA_encrypt and the input for the RSA_decrypt
539955714Skris	routines need to be RSA_size() bytes long, because this is how many
540055714Skris	bytes are expected.
540155714Skris	
540255714SkrisFor the following 4 RSA encryption routines, it should be noted that
540355714SkrisRSA_private_decrypt() should be used on the output from 
540455714SkrisRSA_public_encrypt() and RSA_public_decrypt() should be used on
540555714Skristhe output from RSA_private_encrypt().
540655714Skris	
540755714Skrisint RSA_public_encrypt(
540855714Skrisint from_len;
540955714Skrisunsigned char *from	
541055714Skrisunsigned char *to	
541155714SkrisRSA *rsa);
541255714Skris	This function implements RSA public encryption, the rsa variable
541355714Skris	should be a public key (but can be a private key).  'from_len'
541455714Skris	bytes taken from 'from' and encrypted and put into 'to'.  'to' needs
541555714Skris	to be at least RSA_size(rsa) bytes long.  The number of bytes
541655714Skris	written into 'to' is returned.  -1 is returned on an error.  The
541755714Skris	operation performed is
541855714Skris	to = from^rsa->e mod rsa->n.
541955714Skris	
542055714Skrisint RSA_private_encrypt(
542155714Skrisint from_len;
542255714Skrisunsigned char *from	
542355714Skrisunsigned char *to	
542455714SkrisRSA *rsa);
542555714Skris	This function implements RSA private encryption, the rsa variable
542655714Skris	should be a private key.  'from_len' bytes taken from
542755714Skris	'from' and encrypted and put into 'to'.  'to' needs
542855714Skris	to be at least RSA_size(rsa) bytes long.  The number of bytes
542955714Skris	written into 'to' is returned.  -1 is returned on an error.  The
543055714Skris	operation performed is
543155714Skris	to = from^rsa->d mod rsa->n.
543255714Skris
543355714Skrisint RSA_public_decrypt(
543455714Skrisint from_len;
543555714Skrisunsigned char *from	
543655714Skrisunsigned char *to	
543755714SkrisRSA *rsa);
543855714Skris	This function implements RSA public decryption, the rsa variable
543955714Skris	should be a public key (but can be a private key).  'from_len'
544055714Skris	bytes are taken from 'from' and decrypted.  The decrypted data is
544155714Skris	put into 'to'.  The number of bytes encrypted is returned.  -1 is
544255714Skris	returned to indicate an error. The operation performed is
544355714Skris	to = from^rsa->e mod rsa->n.
544455714Skris
544555714Skrisint RSA_private_decrypt(
544655714Skrisint from_len;
544755714Skrisunsigned char *from	
544855714Skrisunsigned char *to	
544955714SkrisRSA *rsa);
545055714Skris	This function implements RSA private decryption, the rsa variable
545155714Skris	should be a private key.  'from_len' bytes are taken
545255714Skris	from 'from' and decrypted.  The decrypted data is
545355714Skris	put into 'to'.  The number of bytes encrypted is returned.  -1 is
545455714Skris	returned to indicate an error. The operation performed is
545555714Skris	to = from^rsa->d mod rsa->n.
545655714Skris
545755714Skrisint RSA_mod_exp(
545855714SkrisBIGNUM *n;
545955714SkrisBIGNUM *p;
546055714SkrisRSA *rsa);
546155714Skris	Normally you will never use this routine.
546255714Skris	This is really an internal function which is called by
546355714Skris	RSA_private_encrypt() and RSA_private_decrypt().  It performs
546455714Skris	n=n^p mod rsa->n except that it uses the 5 extra variables in the
546555714Skris	RSA structure to make this more efficient.
546655714Skris	
546755714SkrisRSA *RSA_generate_key(
546855714Skrisint bits;
546955714Skrisunsigned long e;
547055714Skrisvoid (*callback)();
547155714Skrischar *cb_arg;
547255714Skris	This routine is used to generate RSA private keys.  It takes
547355714Skris	quite a period of time to run and should only be used to
547455714Skris	generate initial private keys that should then be stored
547555714Skris	for later use.  The passed callback function 
547655714Skris	will be called periodically so that feedback can be given
547755714Skris	as to how this function is progressing.
547855714Skris	'bits' is the length desired for the modulus, so it would be 1024
547955714Skris	to generate a 1024 bit private key.
548055714Skris	'e' is the value to use for the public exponent 'e'.  Traditionally
548155714Skris	it is set to either 3 or 0x10001.
548255714Skris	The callback function (if not NULL) is called in the following
548355714Skris	situations.
548455714Skris	when we have generated a suspected prime number to test,
548555714Skris	callback(0,num1++,cb_arg).  When it passes a prime number test,
548655714Skris	callback(1,num2++,cb_arg).  When it is rejected as one of
548755714Skris	the 2 primes required due to gcd(prime,e value) != 0,
548855714Skris	callback(2,num3++,cb_arg).  When finally accepted as one
548955714Skris	of the 2 primes, callback(3,num4++,cb_arg).
549055714Skris
549155714Skris
549255714Skris==== rsaref.doc ========================================================
549355714Skris
549455714SkrisThis package can be compiled to use the RSAref library.
549555714SkrisThis library is not allowed outside of the USA but inside the USA it is
549655714Skrisclaimed by RSA to be the only RSA public key library that can be used
549755714Skrisbesides BSAFE..
549855714Skris
549955714SkrisThere are 2 files, rsaref/rsaref.c and rsaref/rsaref.h that contain the glue
550055714Skriscode to use RSAref.  These files were written by looking at the PGP
550155714Skrissource code and seeing which routines it used to access RSAref.
550255714SkrisI have also been sent by some-one a copy of the RSAref header file that
550355714Skriscontains the library error codes.
550455714Skris
550555714Skris[ Jun 1996 update - I have recently gotten hold of RSAref 2.0 from
550655714Skris  South Africa and have been doing some performace tests. ]
550755714Skris	
550855714SkrisThey have now been tested against the recently announced RSAEURO
550955714Skrislibrary.
551055714Skris
551155714SkrisThere are 2 ways to use SSLeay and RSAref.  First, to build so that
551255714Skristhe programs must be linked with RSAref, add '-DRSAref' to CFLAG in the top
551355714Skrislevel makefile and -lrsaref (or where ever you are keeping RSAref) to
551455714SkrisEX_LIBS.
551555714Skris
551655714SkrisTo build a makefile via util/mk1mf.pl to do this, use the 'rsaref' option.
551755714Skris
551855714SkrisThe second method is to build as per normal and link applications with
551955714Skristhe RSAglue library.  The correct library order would be
552055714Skriscc -o cmd cmd.o -lssl -lRSAglue -lcrypto -lrsaref -ldes
552155714SkrisThe RSAglue library is built in the rsa directory and is NOT
552255714Skrisautomatically installed.
552355714Skris
552455714SkrisBe warned that the RSAEURO library, that is claimed to be compatible
552555714Skriswith RSAref contains a different value for the maximum number of bits
552655714Skrissupported.  This changes structure sizes and so if you are using
552755714SkrisRSAEURO, change the value of RSAref_MAX_BITS in rsa/rsaref.h
552855714Skris
552955714Skris
553055714Skris==== s_mult.doc ========================================================
553155714Skris
553255714Skriss_mult is a test program I hacked up on a Sunday for testing non-blocking
553355714SkrisIO.  It has a select loop at it's centre that handles multiple readers
553455714Skrisand writers.
553555714Skris
553655714SkrisTry the following command
553755714Skrisssleay s_mult -echo -nbio -ssl -v
553855714Skrisecho - sends any sent text back to the sender
553955714Skrisnbio - turns on non-blocking IO
554055714Skrisssl  - accept SSL connections, default is normal text
554155714Skrisv    - print lots
554255714Skris	type Q<cr> to quit
554355714Skris
554455714SkrisIn another window, run the following
554555714Skrisssleay s_client -pause </etc/termcap
554655714Skris
554755714SkrisThe pause option puts in a 1 second pause in each read(2)/write(2) call
554855714Skrisso the other end will have read()s fail.
554955714Skris
555055714Skris==== session.doc ========================================================
555155714Skris
555255714SkrisI have just checked over and re-worked the session stuff.
555355714SkrisThe following brief example will ignore all setup information to do with
555455714Skrisauthentication.
555555714Skris
555655714SkrisThings operate as follows.
555755714Skris
555855714SkrisThe SSL environment has a 'context', a SSL_CTX structure.  This holds the
555955714Skriscached SSL_SESSIONS (which can be reused) and the certificate lookup
556055714Skrisinformation.  Each SSL structure needs to be associated with a SSL_CTX.
556155714SkrisNormally only one SSL_CTX structure is needed per program.
556255714Skris
556355714SkrisSSL_CTX *SSL_CTX_new(void ); 
556455714Skrisvoid    SSL_CTX_free(SSL_CTX *);
556555714SkrisThese 2 functions create and destroy SSL_CTX structures
556655714Skris
556755714SkrisThe SSL_CTX has a session_cache_mode which is by default,
556855714Skrisin SSL_SESS_CACHE_SERVER mode.  What this means is that the library
5569238405Sjkimwill automatically add new session-id's to the cache upon successful
557055714SkrisSSL_accept() calls.
557155714SkrisIf SSL_SESS_CACHE_CLIENT is set, then client certificates are also added
557255714Skristo the cache.
557355714SkrisSSL_set_session_cache_mode(ctx,mode)  will set the 'mode' and
557455714SkrisSSL_get_session_cache_mode(ctx) will get the cache 'mode'.
557555714SkrisThe modes can be
557655714SkrisSSL_SESS_CACHE_OFF	- no caching
557755714SkrisSSL_SESS_CACHE_CLIENT	- only SSL_connect()
557855714SkrisSSL_SESS_CACHE_SERVER	- only SSL_accept()
557955714SkrisSSL_SESS_NO_CACHE_BOTH	- Either SSL_accept() or SSL_connect().
558055714SkrisIf SSL_SESS_CACHE_NO_AUTO_CLEAR is set, old timed out sessions are
558155714Skrisnot automatically removed each 255, SSL_connect()s or SSL_accept()s.
558255714Skris
5583238405SjkimBy default, upon every 255 successful SSL_connect() or SSL_accept()s,
558455714Skristhe cache is flush.  Please note that this could be expensive on
558555714Skrisa heavily loaded SSL server, in which case, turn this off and
558655714Skrisclear the cache of old entries 'manually' (with one of the functions
558755714Skrislisted below) every few hours.  Perhaps I should up this number, it is hard
5588238405Sjkimto say.  Remember, the '255' new calls is just a mechanism to get called
558955714Skrisevery now and then, in theory at most 255 new session-id's will have been
559055714Skrisadded but if 100 are added every minute, you would still have
559155714Skris500 in the cache before any would start being flushed (assuming a 3 minute
559255714Skristimeout)..
559355714Skris
559455714Skrisint SSL_CTX_sess_hits(SSL_CTX *ctx);
559555714Skrisint SSL_CTX_sess_misses(SSL_CTX *ctx);
559655714Skrisint SSL_CTX_sess_timeouts(SSL_CTX *ctx);
559755714SkrisThese 3 functions return statistics about the SSL_CTX.  These 3 are the
559855714Skrisnumber of session id reuses.  hits is the number of reuses, misses are the
559955714Skrisnumber of lookups that failed, and timeouts is the number of cached
560055714Skrisentries ignored because they had timeouted.
560155714Skris
560255714Skrisctx->new_session_cb is a function pointer to a function of type
560355714Skrisint new_session_callback(SSL *ssl,SSL_SESSION *new);
560455714SkrisThis function, if set in the SSL_CTX structure is called whenever a new
560555714SkrisSSL_SESSION is added to the cache.  If the callback returns non-zero, it
560655714Skrismeans that the application will have to do a SSL_SESSION_free()
560755714Skrison the structure (this is
560855714Skristo do with the cache keeping the reference counts correct, without the
560955714Skrisapplication needing to know about it.
561055714SkrisThe 'active' parameter is the current SSL session for which this connection
561155714Skriswas created.
561255714Skris
561355714Skrisvoid SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,int (*cb)());
561455714Skristo set the callback,
561555714Skrisint (*cb)() SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)
561655714Skristo get the callback.
561755714Skris
561855714SkrisIf the 'get session' callback is set, when a session id is looked up and
561955714Skrisit is not in the session-id cache, this callback is called.  The callback is
562055714Skrisof the form
562155714SkrisSSL_SESSION *get_session_callback(unsigned char *sess_id,int sess_id_len,
562255714Skris	int *copy);
562355714Skris
562455714SkrisThe get_session_callback is intended to return null if no session id is found.
562555714SkrisThe reference count on the SSL_SESSION in incremented by the SSL library,
562655714Skrisif copy is 1.  Otherwise, the reference count is not modified.
562755714Skris
562855714Skrisvoid SSL_CTX_sess_set_get_cb(ctx,cb) sets the callback and
562955714Skrisint (*cb)()SSL_CTX_sess_get_get_cb(ctx) returns the callback.
563055714Skris
5631238405SjkimThese callbacks are basically intended to be used by processes to
563255714Skrissend their session-id's to other processes.  I currently have not implemented
5633238405Sjkimnon-blocking semantics for these callbacks, it is upto the application
5634238405Sjkimto make the callbacks efficient if they require blocking (perhaps
563555714Skrisby 'saving' them and then 'posting them' when control returns from
563655714Skristhe SSL_accept().
563755714Skris
563855714SkrisLHASH *SSL_CTX_sessions(SSL_CTX *ctx)
563955714SkrisThis returns the session cache.  The lhash strucutre can be accessed for
564055714Skrisstatistics about the cache.
564155714Skris
564255714Skrisvoid lh_stats(LHASH *lh, FILE *out);
564355714Skrisvoid lh_node_stats(LHASH *lh, FILE *out);
564455714Skrisvoid lh_node_usage_stats(LHASH *lh, FILE *out);
564555714Skris
564655714Skriscan be used to print details about it's activity and current state.
564755714SkrisYou can also delve directly into the lhash structure for 14 different
564855714Skriscounters that are kept against the structure.  When I wrote the lhash library,
564955714SkrisI was interested in gathering statistics :-).
565055714SkrisHave a read of doc/lhash.doc in the SSLeay distribution area for more details
565155714Skrison the lhash library.
565255714Skris
565355714SkrisNow as mentioned ealier, when a SSL is created, it needs a SSL_CTX.
565455714SkrisSSL *   SSL_new(SSL_CTX *);
565555714Skris
565655714SkrisThis stores a session.  A session is secret information shared between 2
565755714SkrisSSL contexts.  It will only be created if both ends of the connection have
565855714Skrisauthenticated their peer to their satisfaction.  It basically contains
565955714Skristhe information required to use a particular secret key cipher.
566055714Skris
566155714SkrisTo retrieve the SSL_CTX being used by a SSL,
566255714SkrisSSL_CTX *SSL_get_SSL_CTX(SSL *s);
566355714Skris
566455714SkrisNow when a SSL session is established between to programs, the 'session'
566555714Skrisinformation that is cached in the SSL_CTX can me manipulated by the
566655714Skrisfollowing functions.
566755714Skrisint SSL_set_session(SSL *s, SSL_SESSION *session);
566855714SkrisThis will set the SSL_SESSION to use for the next SSL_connect().  If you use
566955714Skristhis function on an already 'open' established SSL connection, 'bad things
567055714Skriswill happen'.  This function is meaning-less when used on a ssl strucutre
567155714Skristhat is just about to be used in a SSL_accept() call since the
567255714SkrisSSL_accept() will either create a new session or retrieve one from the
567355714Skriscache.
567455714Skris
567555714SkrisSSL_SESSION *SSL_get_session(SSL *s);
567655714SkrisThis will return the SSL_SESSION for the current SSL, NULL if there is
567755714Skrisno session associated with the SSL structure.
567855714Skris
567955714SkrisThe SSL sessions are kept in the SSL_CTX in a hash table, to remove a
568055714Skrissession
568155714Skrisvoid    SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c);
568255714Skrisand to add one
568355714Skrisint    SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c);
568455714SkrisSSL_CTX_add_session() returns 1 if the session was already in the cache (so it
568555714Skriswas not added).
568655714SkrisWhenever a new session is created via SSL_connect()/SSL_accept(),
568755714Skristhey are automatically added to the cache, depending on the session_cache_mode
568855714Skrissettings.  SSL_set_session()
568955714Skrisdoes not add it to the cache.  Just call SSL_CTX_add_session() if you do want the
569055714Skrissession added.  For a 'client' this would not normally be the case.
569155714SkrisSSL_CTX_add_session() is not normally ever used, except for doing 'evil' things
569255714Skriswhich the next 2 funtions help you do.
569355714Skris
569455714Skrisint     i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp);
569555714SkrisSSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a,unsigned char **pp,long length);
569655714SkrisThese 2 functions are in the standard ASN1 library form and can be used to
569755714Skrisload and save to a byte format, the SSL_SESSION structure.
569855714SkrisWith these functions, you can save and read these structures to a files or
569955714Skrisarbitary byte string.
570055714SkrisThe PEM_write_SSL_SESSION(fp,x) and PEM_read_SSL_SESSION(fp,x,cb) will
570155714Skriswrite to a file pointer in base64 encoding.
570255714Skris
570355714SkrisWhat you can do with this, is pass session information between separate
570455714Skrisprocesses.  Please note, that you will probably also need to modify the
570555714Skristimeout information on the SSL_SESSIONs.
570655714Skris
570755714Skrislong SSL_get_time(SSL_SESSION *s)
570855714Skriswill return the 'time' that the session
570955714Skriswas loaded.  The timeout is relative to this time.  This information is
571055714Skrissaved when the SSL_SESSION is converted to binarary but it is stored
571155714Skrisin as a unix long, which is rather OS dependant, but easy to convert back.
571255714Skris
571355714Skrislong SSL_set_time(SSL_SESSION *s,long t) will set the above mentioned time.
571455714SkrisThe time value is just the value returned from time(3), and should really
571555714Skrisbe defined by be to be time_t.
571655714Skris
571755714Skrislong SSL_get_timeout(SSL_SESSION *s);
571855714Skrislong SSL_set_timeout(SSL_SESSION *s,long t);
571955714SkrisThese 2 retrieve and set the timeout which is just a number of secconds
572055714Skrisfrom the 'SSL_get_time()' value.  When this time period has elapesed,
572155714Skristhe session will no longer be in the cache (well it will actually be removed
572255714Skristhe next time it is attempted to be retrieved, so you could 'bump'
572355714Skristhe timeout so it remains valid).
572455714SkrisThe 'time' and 'timeout' are set on a session when it is created, not reset
572555714Skriseach time it is reused.  If you did wish to 'bump it', just after establishing
572655714Skrisa connection, do a
572755714SkrisSSL_set_time(ssl,time(NULL));
572855714Skris
572955714SkrisYou can also use
573055714SkrisSSL_CTX_set_timeout(SSL_CTX *ctx,unsigned long t) and
573155714SkrisSSL_CTX_get_timeout(SSL_CTX *ctx) to manipulate the default timeouts for
573255714Skrisall SSL connections created against a SSL_CTX.  If you set a timeout in
573355714Skrisan SSL_CTX, all new SSL's created will inherit the timeout.  It can be over
573455714Skriswritten by the SSL_set_timeout(SSL *s,unsigned long t) function call.
573555714SkrisIf you 'set' the timeout back to 0, the system default will be used.
573655714Skris
573755714SkrisSSL_SESSION *SSL_SESSION_new();
573855714Skrisvoid SSL_SESSION_free(SSL_SESSION *ses);
573955714SkrisThese 2 functions are used to create and dispose of SSL_SESSION functions.
574055714SkrisYou should not ever normally need to use them unless you are using 
574155714Skrisi2d_SSL_SESSION() and/or d2i_SSL_SESSION().  If you 'load' a SSL_SESSION
574255714Skrisvia d2i_SSL_SESSION(), you will need to SSL_SESSION_free() it.
574355714SkrisBoth SSL_set_session() and SSL_CTX_add_session() will 'take copies' of the
574455714Skrisstructure (via reference counts) when it is passed to them.
574555714Skris
574655714SkrisSSL_CTX_flush_sessions(ctx,time);
574755714SkrisThe first function will clear all sessions from the cache, which have expired
574855714Skrisrelative to 'time' (which could just be time(NULL)).
574955714Skris
575055714SkrisSSL_CTX_flush_sessions(ctx,0);
575155714SkrisThis is a special case that clears everything.
575255714Skris
575355714SkrisAs a final comment, a 'session' is not enough to establish a new
575455714Skrisconnection.  If a session has timed out, a certificate and private key
575555714Skrisneed to have been associated with the SSL structure.
575655714SkrisSSL_copy_session_id(SSL *to,SSL *from); will copy not only the session
575755714Skrisstrucutre but also the private key and certificate associated with
575855714Skris'from'.
575955714Skris
576055714SkrisEXAMPLES.
576155714Skris
576272613SkrisSo lets play at being a weird SSL server.
576355714Skris
576455714Skris/* setup a context */
576555714Skrisctx=SSL_CTX_new();
576655714Skris
576755714Skris/* Lets load some session from binary into the cache, why one would do
576855714Skris * this is not toally clear, but passing between programs does make sense
576955714Skris * Perhaps you are using 4096 bit keys and are happy to keep them
577055714Skris * valid for a week, to avoid the RSA overhead of 15 seconds, I'm not toally
577155714Skris * sure, perhaps this is a process called from an SSL inetd and this is being 
577255714Skris * passed to the application. */
577355714Skrissession=d2i_SSL_SESSION(....)
577455714SkrisSSL_CTX_add_session(ctx,session);
577555714Skris
577655714Skris/* Lets even add a session from a file */
577755714Skrissession=PEM_read_SSL_SESSION(....)
577855714SkrisSSL_CTX_add_session(ctx,session);
577955714Skris
578055714Skris/* create a new SSL structure */
578155714Skrisssl=SSL_new(ctx);
578255714Skris
578355714Skris/* At this point we want to be able to 'create' new session if
578455714Skris * required, so we need a certificate and RSAkey. */
578555714SkrisSSL_use_RSAPrivateKey_file(ssl,...)
578655714SkrisSSL_use_certificate_file(ssl,...)
578755714Skris
578855714Skris/* Now since we are a server, it make little sence to load a session against
578955714Skris * the ssl strucutre since a SSL_accept() will either create a new session or
579055714Skris * grab an existing one from the cache. */
579155714Skris
579255714Skris/* grab a socket descriptor */
579355714Skrisfd=accept(...);
579455714Skris
579555714Skris/* associated it with the ssl strucutre */
579655714SkrisSSL_set_fd(ssl,fd);
579755714Skris
579855714SkrisSSL_accept(ssl); /* 'do' SSL using out cert and RSA key */
579955714Skris
580055714Skris/* Lets print out the session details or lets save it to a file,
580155714Skris * perhaps with a secret key cipher, so that we can pass it to the FBI
580255714Skris * when they want to decode the session :-).  While we have RSA
580355714Skris * this does not matter much but when I do SSLv3, this will allow a mechanism
580455714Skris * for the server/client to record the information needed to decode
580555714Skris * the traffic that went over the wire, even when using Diffie-Hellman */
580655714SkrisPEM_write_SSL_SESSION(SSL_get_session(ssl),stdout,....)
580755714Skris
580855714SkrisLets 'connect' back to the caller using the same session id.
580955714Skris
581055714Skrisssl2=SSL_new(ctx);
581155714Skrisfd2=connect(them);
581255714SkrisSSL_set_fd(ssl2,fd2);
581355714SkrisSSL_set_session(ssl2,SSL_get_session(ssl));
581455714SkrisSSL_connect(ssl2);
581555714Skris
581655714Skris/* what the hell, lets accept no more connections using this session */
581755714SkrisSSL_CTX_remove_session(SSL_get_SSL_CTX(ssl),SSL_get_session(ssl));
581855714Skris
581955714Skris/* we could have just as easily used ssl2 since they both are using the
582055714Skris * same session.
582155714Skris * You will note that both ssl and ssl2 are still using the session, and
582255714Skris * the SSL_SESSION structure will be free()ed when both ssl and ssl2
582355714Skris * finish using the session.  Also note that you could continue to initiate
582455714Skris * connections using this session by doing SSL_get_session(ssl) to get the
582555714Skris * existing session, but SSL_accept() will not be able to find it to
582655714Skris * use for incoming connections.
582755714Skris * Of corse, the session will timeout at the far end and it will no
582855714Skris * longer be accepted after a while.  The time and timeout are ignored except
582955714Skris * by SSL_accept(). */
583055714Skris
583155714Skris/* Since we have had our server running for 10 weeks, and memory is getting
583255714Skris * short, perhaps we should clear the session cache to remove those
583355714Skris * 100000 session entries that have expired.  Some may consider this
583455714Skris * a memory leak :-) */
583555714Skris
583655714SkrisSSL_CTX_flush_sessions(ctx,time(NULL));
583755714Skris
583855714Skris/* Ok, after a bit more time we wish to flush all sessions from the cache
583955714Skris * so that all new connections will be authenticated and incure the
584055714Skris * public key operation overhead */
584155714Skris
584255714SkrisSSL_CTX_flush_sessions(ctx,0);
584355714Skris
584455714Skris/* As a final note, to copy everything to do with a SSL, use */
584555714SkrisSSL_copy_session_id(SSL *to,SSL *from);
584655714Skris/* as this also copies the certificate and RSA key so new session can
584755714Skris * be established using the same details */
584855714Skris
584955714Skris
585055714Skris==== sha.doc ========================================================
585155714Skris
585255714SkrisThe SHA (Secure Hash Algorithm) library.
585355714SkrisSHA is a message digest algorithm that can be used to condense an arbitrary
585455714Skrislength message down to a 20 byte hash.  The functions all need to be passed
585555714Skrisa SHA_CTX which is used to hold the SHA context during multiple SHA_Update()
585655714Skrisfunction calls.  The normal method of use for this library is as follows
585755714SkrisThis library contains both SHA and SHA-1 digest algorithms.  SHA-1 is
585855714Skrisan update to SHA (which should really be called SHA-0 now) which
585955714Skristweaks the algorithm slightly.  The SHA-1 algorithm is used by simply
586055714Skrisusing SHA1_Init(), SHA1_Update(), SHA1_Final() and SHA1() instead of the
586155714SkrisSHA*() calls
586255714Skris
586355714SkrisSHA_Init(...);
586455714SkrisSHA_Update(...);
586555714Skris...
586655714SkrisSHA_Update(...);
586755714SkrisSHA_Final(...);
586855714Skris
586955714SkrisThis library requires the inclusion of 'sha.h'.
587055714Skris
587155714SkrisThe functions are as follows:
587255714Skris
587355714Skrisvoid SHA_Init(
587455714SkrisSHA_CTX *c);
587555714Skris	This function needs to be called to initiate a SHA_CTX structure for
587655714Skris	use.
587755714Skris	
587855714Skrisvoid SHA_Update(
587955714SkrisSHA_CTX *c;
588055714Skrisunsigned char *data;
588155714Skrisunsigned long len);
588255714Skris	This updates the message digest context being generated with 'len'
588355714Skris	bytes from the 'data' pointer.  The number of bytes can be any
588455714Skris	length.
588555714Skris
588655714Skrisvoid SHA_Final(
588755714Skrisunsigned char *md;
588855714SkrisSHA_CTX *c;
588955714Skris	This function is called when a message digest of the data digested
589055714Skris	with SHA_Update() is wanted.  The message digest is put in the 'md'
589155714Skris	array and is SHA_DIGEST_LENGTH (20) bytes long.
589255714Skris
589355714Skrisunsigned char *SHA(
589455714Skrisunsigned char *d;
589555714Skrisunsigned long n;
589655714Skrisunsigned char *md;
589755714Skris	This function performs a SHA_Init(), followed by a SHA_Update()
589855714Skris	followed by a SHA_Final() (using a local SHA_CTX).
589955714Skris	The resulting digest is put into 'md' if it is not NULL.
590055714Skris	Regardless of the value of 'md', the message
590155714Skris	digest is returned from the function.  If 'md' was NULL, the message
590255714Skris	digest returned is being stored in a static structure.
590355714Skris	
590455714Skris
590555714Skris==== speed.doc ========================================================
590655714Skris
590755714SkrisTo get an idea of the performance of this library, use
590855714Skrisssleay speed
590955714Skris
591055714Skrisperl util/sp-diff.pl file1 file2
591155714Skris
591255714Skriswill print out the relative differences between the 2 files which are
591355714Skrisexpected to be the output from the speed program.
591455714Skris
591555714SkrisThe performace of the library is very dependant on the Compiler
591655714Skrisquality and various flags used to build.
591755714Skris
591855714Skris---
591955714Skris
592055714SkrisThese are some numbers I did comparing RSAref and SSLeay on a Pentium 100.
592155714Skris[ These numbers are all out of date, as of SSL - 0.6.1 the RSA
592255714Skrisoperations are about 2 times faster, so check the version number ]
592355714Skris
592455714SkrisRSA performance.
592555714Skris
592655714SkrisSSLeay 0.6.0
592755714SkrisPentium 100, 32meg, Windows NT Workstation 3.51
592855714Skrislinux - gcc v 2.7.0 -O3 -fomit-frame-pointer -m486
592955714Skrisand
593055714SkrisWindows NT  - Windows NT 3.51 - Visual C++ 4.1   - 586 code + 32bit assember
593155714SkrisWindows 3.1 - Windows NT 3.51 - Visual C++ 1.52c - 286 code + 32bit assember
593255714SkrisNT Dos Shell- Windows NT 3.51 - Visual C++ 1.52c - 286 code + 16bit assember
593355714Skris
593455714SkrisTimes are how long it takes to do an RSA private key operation.
593555714Skris
593655714Skris	       512bits 1024bits
593755714Skris-------------------------------
593855714SkrisSSLeay NT dll	0.042s   0.202s see above
593955714SkrisSSLeay linux	0.046s   0.218s	Assember inner loops (normal build) 
594055714SkrisSSLeay linux	0.067s   0.380s Pure C code with BN_LLONG defined
594155714SkrisSSLeay W3.1 dll	0.108s 	 0.478s see above
594255714SkrisSSLeay linux	0.109s   0.713s C without BN_LLONG.
594355714SkrisRSAref2.0 linux	0.149s   0.936s
594455714SkrisSSLeay MS-DOS	0.197s   1.049s see above
594555714Skris
594655714Skris486DX66, 32meg, Windows NT Server 3.51
594755714Skris	       512bits 1024bits
594855714Skris-------------------------------
594955714SkrisSSLeay NT dll   0.084s	 0.495s	<- SSLeay 0.6.3
595055714SkrisSSLeay NT dll   0.154s   0.882s
595155714SkrisSSLeay W3.1 dll 0.335s   1.538s
595255714SkrisSSLeay MS-DOS	0.490s   2.790s
595355714Skris
595455714SkrisWhat I find cute is that I'm still faster than RSAref when using standard C,
595555714Skriswithout using the 'long long' data type :-), %35 faster for 512bit and we
595655714Skrisscale up to 3.2 times faster for the 'default linux' build.  I should mention
595755714Skristhat people should 'try' to use either x86-lnx.s (elf), x86-lnxa.s or
595855714Skrisx86-sol.s for any x86 based unix they are building on.  The only problems
595955714Skriswith be with syntax but the performance gain is quite large, especially for
596055714Skrisservers.  The code is very simple, you just need to modify the 'header'.
596155714Skris
596255714SkrisThe message is, if you are stuck using RSAref, the RSA performance will be
596355714Skrisbad. Considering the code was compiled for a pentium, the 486DX66 number
596455714Skriswould indicate 'Use RSAref and turn you Pentium 100 into a 486DX66' :-). 
596555714Skris[ As of verson 0.6.1, it would be correct to say 'turn you pentium 100
596655714Skris into a 486DX33' :-) ]
596755714Skris
596855714SkrisI won't tell people if the DLL's are using RSAref or my stuff if no-one
596955714Skrisasks :-).
597055714Skris
597155714Skriseric
597255714Skris
597355714SkrisPS while I know I could speed things up further, I will probably not do
597455714Skris   so due to the effort involved.  I did do some timings on the
597555714Skris   SSLeay bignum format -> RSAref number format conversion that occurs
597655714Skris   each time RSAref is used by SSLeay, and the numbers are trivial.
597755714Skris   0.00012s a call for 512bit vs 0.149s for the time spent in the function.
597855714Skris   0.00018s for 1024bit vs 0.938s.  Insignificant.
597955714Skris   So the 'way to go', to support faster RSA libraries, if people are keen,
598055714Skris   is to write 'glue' code in a similar way that I do for RSAref and send it
598155714Skris   to me :-).
598255714Skris   My base library still has the advantage of being able to operate on 
598355714Skris   any size numbers, and is not that far from the performance from the
598455714Skris   leaders in the field. (-%30?)
598555714Skris   [ Well as of 0.6.1 I am now the leader in the filed on x86 (we at
598655714Skris     least very close :-) ]
598755714Skris
598855714Skris   I suppose I should also mention some other numbers RSAref numbers, again
598955714Skris   on my Pentium.
599055714Skris		DES CBC		EDE-DES		MD5
599155714Skris   RSAref linux	 830k/s		 302k/s		4390k/s
599255714Skris   SSLeay linux  855k/s          319k/s        10025k/s
599355714Skris   SSLeay NT	1158k/s		 410k/s	       10470k/s
599455714Skris   SSLeay w31	 378k/s		 143k/s         2383k/s (fully 16bit)
599555714Skris
599655714Skris   Got to admit that Visual C++ 4.[01] is a damn fine compiler :-)
599755714Skris--
599855714SkrisEric Young                  | BOOL is tri-state according to Bill Gates.
599955714SkrisAARNet: eay@cryptsoft.com   | RTFM Win32 GetMessage().
600055714Skris
600155714Skris
600255714Skris
600355714Skris
600455714Skris==== ssl-ciph.doc ========================================================
600555714Skris
600655714SkrisThis is a quick high level summery of how things work now.
600755714Skris
600855714SkrisEach SSLv2 and SSLv3 cipher is composed of 4 major attributes plus a few extra
600955714Skrisminor ones.
601055714Skris
601155714SkrisThey are 'The key exchange algorithm', which is RSA for SSLv2 but can also
601255714Skrisbe Diffle-Hellman for SSLv3.
601355714Skris
601455714SkrisAn 'Authenticion algorithm', which can be RSA, Diffle-Helman, DSS or
601555714Skrisnone.
601655714Skris
601755714SkrisThe cipher
601855714Skris
601955714SkrisThe MAC digest.
602055714Skris
602155714SkrisA cipher can also be an export cipher and is either an SSLv2 or a
602255714SkrisSSLv3 ciphers.
602355714Skris
602455714SkrisTo specify which ciphers to use, one can either specify all the ciphers,
602555714Skrisone at a time, or use 'aliases' to specify the preference and order for
602655714Skristhe ciphers.
602755714Skris
602855714SkrisThere are a large number of aliases, but the most importaint are
602955714SkriskRSA, kDHr, kDHd and kEDH for key exchange types.
603055714Skris
603155714SkrisaRSA, aDSS, aNULL and aDH for authentication
603255714SkrisDES, 3DES, RC4, RC2, IDEA and eNULL for ciphers
603355714SkrisMD5, SHA0 and SHA1 digests
603455714Skris
603555714SkrisNow where this becomes interesting is that these can be put together to
603655714Skrisspecify the order and ciphers you wish to use.
603755714Skris
603855714SkrisTo speed this up there are also aliases for certian groups of ciphers.
603955714SkrisThe main ones are
604055714SkrisSSLv2	- all SSLv2 ciphers
604155714SkrisSSLv3	- all SSLv3 ciphers
604255714SkrisEXP	- all export ciphers
604355714SkrisLOW	- all low strngth ciphers (no export ciphers, normally single DES)
604455714SkrisMEDIUM	- 128 bit encryption
604555714SkrisHIGH	- Triple DES
604655714Skris
604755714SkrisThese aliases can be joined in a : separated list which specifies to
604855714Skrisadd ciphers, move them to the current location and delete them.
604955714Skris
605055714SkrisA simpler way to look at all of this is to use the 'ssleay ciphers -v' command.
605155714SkrisThe default library cipher spec is
605255714Skris!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP
605355714Skriswhich means, first, remove from consideration any ciphers that do not
605455714Skrisauthenticate.  Next up, use ciphers using RC4 and RSA.  Next include the HIGH,
605555714SkrisMEDIUM and the LOW security ciphers.  Finish up by adding all the export
605655714Skrisciphers on the end, then 'pull' all the SSLv2 and export ciphers to
605755714Skristhe end of the list.
605855714Skris
605955714SkrisThe results are
606055714Skris$ ssleay ciphers -v '!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP'
606155714Skris
606255714SkrisRC4-SHA                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=SHA1
606355714SkrisRC4-MD5                 SSLv3 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5 
606455714SkrisEDH-RSA-DES-CBC3-SHA    SSLv3 Kx=DH       Au=RSA  Enc=3DES(168) Mac=SHA1
606555714SkrisEDH-DSS-DES-CBC3-SHA    SSLv3 Kx=DH       Au=DSS  Enc=3DES(168) Mac=SHA1
606655714SkrisDES-CBC3-SHA            SSLv3 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=SHA1
606755714SkrisIDEA-CBC-MD5            SSLv3 Kx=RSA      Au=RSA  Enc=IDEA(128) Mac=SHA1
606855714SkrisEDH-RSA-DES-CBC-SHA     SSLv3 Kx=DH       Au=RSA  Enc=DES(56)   Mac=SHA1
606955714SkrisEDH-DSS-DES-CBC-SHA     SSLv3 Kx=DH       Au=DSS  Enc=DES(56)   Mac=SHA1
607055714SkrisDES-CBC-SHA             SSLv3 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=SHA1
607155714SkrisDES-CBC3-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=3DES(168) Mac=MD5 
607255714SkrisDES-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=DES(56)   Mac=MD5 
607355714SkrisIDEA-CBC-MD5            SSLv2 Kx=RSA      Au=RSA  Enc=IDEA(128) Mac=MD5 
607455714SkrisRC2-CBC-MD5             SSLv2 Kx=RSA      Au=RSA  Enc=RC2(128)  Mac=MD5 
607555714SkrisRC4-MD5                 SSLv2 Kx=RSA      Au=RSA  Enc=RC4(128)  Mac=MD5 
607655714SkrisEXP-EDH-RSA-DES-CBC     SSLv3 Kx=DH(512)  Au=RSA  Enc=DES(40)   Mac=SHA1 export
607755714SkrisEXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512)  Au=DSS  Enc=DES(40)   Mac=SHA1 export
607855714SkrisEXP-DES-CBC-SHA         SSLv3 Kx=RSA(512) Au=RSA  Enc=DES(40)   Mac=SHA1 export
607955714SkrisEXP-RC2-CBC-MD5         SSLv3 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
608055714SkrisEXP-RC4-MD5             SSLv3 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
608155714SkrisEXP-RC2-CBC-MD5         SSLv2 Kx=RSA(512) Au=RSA  Enc=RC2(40)   Mac=MD5  export
608255714SkrisEXP-RC4-MD5             SSLv2 Kx=RSA(512) Au=RSA  Enc=RC4(40)   Mac=MD5  export
608355714Skris
608455714SkrisI would recoment people use the 'ssleay ciphers -v "text"'
608555714Skriscommand to check what they are going to use.
608655714Skris
608755714SkrisAnyway, I'm falling asleep here so I'll do some more tomorrow.
608855714Skris
608955714Skriseric
609055714Skris
609155714Skris==== ssl.doc ========================================================
609255714Skris
609355714SkrisSSL_CTX_sessions(SSL_CTX *ctx) - the session-id hash table.
609455714Skris
609555714Skris/* Session-id cache stats */
609655714SkrisSSL_CTX_sess_number
609755714SkrisSSL_CTX_sess_connect
609855714SkrisSSL_CTX_sess_connect_good
609955714SkrisSSL_CTX_sess_accept
610055714SkrisSSL_CTX_sess_accept_good
610155714SkrisSSL_CTX_sess_hits
610255714SkrisSSL_CTX_sess_cb_hits
610355714SkrisSSL_CTX_sess_misses
610455714SkrisSSL_CTX_sess_timeouts
610555714Skris
610655714Skris/* Session-id application notification callbacks */
610755714SkrisSSL_CTX_sess_set_new_cb
610855714SkrisSSL_CTX_sess_get_new_cb
610955714SkrisSSL_CTX_sess_set_get_cb
611055714SkrisSSL_CTX_sess_get_get_cb
611155714Skris
611255714Skris/* Session-id cache operation mode */
611355714SkrisSSL_CTX_set_session_cache_mode
611455714SkrisSSL_CTX_get_session_cache_mode
611555714Skris
611655714Skris/* Set default timeout values to use. */
611755714SkrisSSL_CTX_set_timeout
611855714SkrisSSL_CTX_get_timeout
611955714Skris
612055714Skris/* Global  SSL initalisation informational callback */
612155714SkrisSSL_CTX_set_info_callback
612255714SkrisSSL_CTX_get_info_callback
612355714SkrisSSL_set_info_callback
612455714SkrisSSL_get_info_callback
612555714Skris
612655714Skris/* If the SSL_accept/SSL_connect returned with -1, these indicate when
612755714Skris * we should re-call *.
612855714SkrisSSL_want
612955714SkrisSSL_want_nothing
613055714SkrisSSL_want_read
613155714SkrisSSL_want_write
613255714SkrisSSL_want_x509_lookup
613355714Skris
613455714Skris/* Where we are in SSL initalisation, used in non-blocking, perhaps
613555714Skris * have a look at ssl/bio_ssl.c */
613655714SkrisSSL_state
613755714SkrisSSL_is_init_finished
613855714SkrisSSL_in_init
613955714SkrisSSL_in_connect_init
614055714SkrisSSL_in_accept_init
614155714Skris
614255714Skris/* Used to set the 'inital' state so SSL_in_connect_init and SSL_in_accept_init
614355714Skris * can be used to work out which function to call. */
614455714SkrisSSL_set_connect_state
614555714SkrisSSL_set_accept_state
614655714Skris
614755714Skris/* Where to look for certificates for authentication */
614855714SkrisSSL_set_default_verify_paths /* calles SSL_load_verify_locations */
614955714SkrisSSL_load_verify_locations
615055714Skris
615155714Skris/* get info from an established connection */
615255714SkrisSSL_get_session
615355714SkrisSSL_get_certificate
615455714SkrisSSL_get_SSL_CTX
615555714Skris
615655714SkrisSSL_CTX_new
615755714SkrisSSL_CTX_free
615855714SkrisSSL_new
615955714SkrisSSL_clear
616055714SkrisSSL_free
616155714Skris
616255714SkrisSSL_CTX_set_cipher_list
616355714SkrisSSL_get_cipher
616455714SkrisSSL_set_cipher_list
616555714SkrisSSL_get_cipher_list
616655714SkrisSSL_get_shared_ciphers
616755714Skris
616855714SkrisSSL_accept
616955714SkrisSSL_connect
617055714SkrisSSL_read
617155714SkrisSSL_write
617255714Skris
617355714SkrisSSL_debug
617455714Skris
617555714SkrisSSL_get_read_ahead
617655714SkrisSSL_set_read_ahead
617755714SkrisSSL_set_verify
617855714Skris
617955714SkrisSSL_pending
618055714Skris
618155714SkrisSSL_set_fd
618255714SkrisSSL_set_rfd
618355714SkrisSSL_set_wfd
618455714SkrisSSL_set_bio
618555714SkrisSSL_get_fd
618655714SkrisSSL_get_rbio
618755714SkrisSSL_get_wbio
618855714Skris
618955714SkrisSSL_use_RSAPrivateKey
619055714SkrisSSL_use_RSAPrivateKey_ASN1
619155714SkrisSSL_use_RSAPrivateKey_file
619255714SkrisSSL_use_PrivateKey
619355714SkrisSSL_use_PrivateKey_ASN1
619455714SkrisSSL_use_PrivateKey_file
619555714SkrisSSL_use_certificate
619655714SkrisSSL_use_certificate_ASN1
619755714SkrisSSL_use_certificate_file
619855714Skris
619955714SkrisERR_load_SSL_strings
620055714SkrisSSL_load_error_strings
620155714Skris
620255714Skris/* human readable version of the 'state' of the SSL connection. */
620355714SkrisSSL_state_string
620455714SkrisSSL_state_string_long
620555714Skris/* These 2 report what kind of IO operation the library was trying to
620655714Skris * perform last.  Probably not very usefull. */
620755714SkrisSSL_rstate_string
620855714SkrisSSL_rstate_string_long
620955714Skris
621055714SkrisSSL_get_peer_certificate
621155714Skris
621255714SkrisSSL_SESSION_new
621355714SkrisSSL_SESSION_print_fp
621455714SkrisSSL_SESSION_print
621555714SkrisSSL_SESSION_free
621655714Skrisi2d_SSL_SESSION
621755714Skrisd2i_SSL_SESSION
621855714Skris
621955714SkrisSSL_get_time
622055714SkrisSSL_set_time
622155714SkrisSSL_get_timeout
622255714SkrisSSL_set_timeout
622355714SkrisSSL_copy_session_id
622455714SkrisSSL_set_session
622555714SkrisSSL_CTX_add_session
622655714SkrisSSL_CTX_remove_session
622755714SkrisSSL_CTX_flush_sessions
622855714Skris
622955714SkrisBIO_f_ssl
623055714Skris
623155714Skris/* used to hold information as to why a certificate verification failed */
623255714SkrisSSL_set_verify_result
623355714SkrisSSL_get_verify_result
623455714Skris
623555714Skris/* can be used by the application to associate data with an SSL structure.
623655714Skris * It needs to be 'free()ed' by the application */
623755714SkrisSSL_set_app_data
623855714SkrisSSL_get_app_data
623955714Skris
624055714Skris/* The following all set values that are kept in the SSL_CTX but
624155714Skris * are used as the default values when an SSL session is created.
624255714Skris * They are over writen by the relevent SSL_xxxx functions */
624355714Skris
624455714Skris/* SSL_set_verify */
624555714Skrisvoid SSL_CTX_set_default_verify
624655714Skris
624755714Skris/* This callback, if set, totaly overrides the normal SSLeay verification
6248127128Snectar * functions and should return 1 on success and 0 on failure */
624955714Skrisvoid SSL_CTX_set_cert_verify_callback
625055714Skris
625155714Skris/* The following are the same as the equivilent SSL_xxx functions.
625255714Skris * Only one copy of this information is kept and if a particular
625355714Skris * SSL structure has a local override, it is totally separate structure.
625455714Skris */
625555714Skrisint SSL_CTX_use_RSAPrivateKey
625655714Skrisint SSL_CTX_use_RSAPrivateKey_ASN1
625755714Skrisint SSL_CTX_use_RSAPrivateKey_file
625855714Skrisint SSL_CTX_use_PrivateKey
625955714Skrisint SSL_CTX_use_PrivateKey_ASN1
626055714Skrisint SSL_CTX_use_PrivateKey_file
626155714Skrisint SSL_CTX_use_certificate
626255714Skrisint SSL_CTX_use_certificate_ASN1
626355714Skrisint SSL_CTX_use_certificate_file
626455714Skris
626555714Skris
626655714Skris==== ssl_ctx.doc ========================================================
626755714Skris
626855714SkrisThis is now a bit dated, quite a few of the SSL_ functions could be
626955714SkrisSSL_CTX_ functions.  I will update this in the future. 30 Aug 1996
627055714Skris
627155714SkrisFrom eay@orb.mincom.oz.au Mon Dec 11 21:37:08 1995
627255714SkrisReceived: by orb.mincom.oz.au id AA00696
627355714Skris  (5.65c/IDA-1.4.4 for eay); Mon, 11 Dec 1995 11:37:08 +1000
627455714SkrisDate: Mon, 11 Dec 1995 11:37:08 +1000 (EST)
627555714SkrisFrom: Eric Young <eay@mincom.oz.au>
627655714SkrisX-Sender: eay@orb
627755714SkrisTo: sameer <sameer@c2.org>
627855714SkrisCc: Eric Young <eay@mincom.oz.au>
627955714SkrisSubject: Re: PEM_readX509 oesn't seem to be working
628055714SkrisIn-Reply-To: <199512110102.RAA12521@infinity.c2.org>
628155714SkrisMessage-Id: <Pine.SOL.3.91.951211112115.28608D-100000@orb>
628255714SkrisMime-Version: 1.0
628355714SkrisContent-Type: TEXT/PLAIN; charset=US-ASCII
628455714SkrisStatus: RO
628555714SkrisX-Status: 
628655714Skris
628755714SkrisOn Sun, 10 Dec 1995, sameer wrote:
628855714Skris> 	OK, that's solved. I've found out that it is saying "no
628955714Skris> certificate set" in SSL_accept because s->conn == NULL
629055714Skris> so there is some place I need to initialize s->conn that I am
629155714Skris> not initializing it.
629255714Skris
629355714SkrisThe full order of things for a server should be.
629455714Skris
629555714Skrisctx=SSL_CTX_new();
629655714Skris
629755714Skris/* The next line should not really be using ctx->cert but I'll leave it 
629855714Skris * this way right now... I don't want a X509_ routine to know about an SSL
629955714Skris * structure, there should be an SSL_load_verify_locations... hmm, I may 
630055714Skris * add it tonight.
630155714Skris */
630255714SkrisX509_load_verify_locations(ctx->cert,CAfile,CApath);
630355714Skris
630455714Skris/* Ok now for each new connection we do the following */
630555714Skriscon=SSL_new(ctx);
630655714SkrisSSL_set_fd(con,s);
630755714SkrisSSL_set_verify(con,verify,verify_callback);
630855714Skris
630955714Skris/* set the certificate and private key to use. */
631055714SkrisSSL_use_certificate_ASN1(con,X509_certificate);
631155714SkrisSSL_use_RSAPrivateKey_ASN1(con,RSA_private_key);
631255714Skris
631355714SkrisSSL_accept(con);
631455714Skris
631555714SkrisSSL_read(con)/SSL_write(con);
631655714Skris
631755714SkrisThere is a bit more than that but that is basically the structure.
631855714Skris
631955714SkrisCreate a context and specify where to lookup certificates.
632055714Skris
632155714Skrisforeach connection
632255714Skris	{
632355714Skris	create a SSL structure
632455714Skris	set the certificate and private key
632555714Skris	do a SSL_accept
632655714Skris	
632755714Skris	we should now be ok
632855714Skris	}
632955714Skris
633055714Skriseric
633155714Skris--
633255714SkrisEric Young                  | Signature removed since it was generating
633355714SkrisAARNet: eay@mincom.oz.au    | more followups than the message contents :-)
633455714Skris
633555714Skris
633655714Skris
633755714Skris==== ssleay.doc ========================================================
633855714Skris
633955714SkrisSSLeay: a cryptographic kitchen sink.
634055714Skris
634155714Skris1st December 1995
634255714SkrisWay back at the start of April 1995, I was looking for a mindless
634355714Skrisprogramming project.  A friend of mine (Tim Hudson) said "why don't you do SSL,
634455714Skrisit has DES encryption in it and I would not mind using it in a SSL telnet".
634555714SkrisWhile it was true I had written a DES library in previous years, litle
634655714Skrisdid I know what an expansive task SSL would turn into.
634755714Skris
634855714SkrisFirst of all, the SSL protocol contains DES encryption.  Well and good.  My
634955714SkrisDES library was fast and portable.  It also contained the RSA's RC4 stream
635055714Skriscipher.  Again, not a problem, some-one had just posted to sci.crypt
635155714Skrissomething that was claimed to be RC4.  It also contained IDEA, I had the
635255714Skrisspecifications, not a problem to implement.  MD5, an RFC, trivial, at most
635355714SkrisI could spend a week or so trying to see if I could speed up the
635455714Skrisimplementation.  All in all a nice set of ciphers.
635555714SkrisThen the first 'expantion of the scope', RSA public key
635655714Skrisencryption.  Since I did not knowing a thing about public key encryption
635755714Skrisor number theory, this appeared quite a daunting task.  Just writing a
635855714Skrisbig number library would be problomatic in itself, let alone making it fast.
635955714SkrisAt this point the scope of 'implementing SSL' expands eponentialy.
636055714SkrisFirst of all, the RSA private keys  were being kept in ASN.1 format.
636155714SkrisThankfully the RSA PKCS series of documents explains this format.  So I now
636255714Skrisneeded to be able to encode and decode arbitary ASN.1 objects.  The Public
636355714Skriskeys were embeded in X509 certificates.  Hmm... these are not only
636455714SkrisASN.1 objects but they make up a heirachy of authentication.  To
636555714Skrisauthenticate a X509 certificate one needs to retrieve it's issuers
636655714Skriscertificate etc etc.  Hmm..., so I also need to implement some kind
636755714Skrisof certificate management software.  I would also have to implement
636855714Skrissoftware to authenticate certificates.  At this point the support code made
636955714Skristhe SSL part of my library look quite small.
637055714SkrisAround this time, the first version of SSLeay was released.
637155714Skris
637255714SkrisAh, but here was the problem, I was not happy with the code so far.  As may
637355714Skrishave become obvious, I had been treating all of this as a learning
637455714Skrisexersize, so I have completely written the library myself.  As such, due
637555714Skristo the way it had grown like a fungus, much of the library was not
637655714Skris'elagent' or neat.  There were global and static variables all over the
637755714Skrisplace, the SSL part did not even handle non-blocking IO.
637855714SkrisThe Great rewrite began.
637955714Skris
638055714SkrisAs of this point in time, the 'Great rewrite' has almost finished.  So what
638155714Skrisfollows is an approximate list of what is actually SSLeay 0.5.0
638255714Skris
638355714Skris/********* This needs to be updated for 0.6.0+ *************/
638455714Skris
638555714Skris---
638655714SkrisThe library contains the following routines.  Please note that most of these
638755714Skrisfunctions are not specfic for SSL or any other particular cipher
638855714Skrisimplementation.  I have tried to make all the routines as general purpose
638955714Skrisas possible.  So you should not think of this library as an SSL
639055714Skrisimplemtation, but rather as a library of cryptographic functions
639155714Skristhat also contains SSL.  I refer to each of these function groupings as
639255714Skrislibraries since they are often capable of functioning as independant
639355714Skrislibraries
639455714Skris
639555714SkrisFirst up, the general ciphers and message digests supported by the library.
639655714Skris
639755714SkrisMD2	rfc???, a standard 'by parts' interface to this algorithm.
639855714SkrisMD5	rfc???, the same type of interface as for the MD2 library except a
639955714Skris	different algorithm.
640055714SkrisSHA	THe Secure Hash Algorithm.  Again the same type of interface as
640155714Skris	MD2/MD5 except the digest is 20 bytes.
640255714SkrisSHA1	The 'revised' version of SHA.  Just about identical to SHA except
640355714Skris	for one tweak of an inner loop.
640455714SkrisDES	This is my libdes library that has been floating around for the last
640555714Skris	few years.  It has been enhanced for no other reason than completeness.
640655714Skris	It now supports ecb, cbc, cfb, ofb, cfb64, ofb64 in normal mode and
640755714Skris	triple DES modes of ecb, cbc, cfb64 and ofb64.  cfb64 and ofb64 are
640855714Skris	functional interfaces to the 64 bit modes of cfb and ofb used in
640955714Skris	such a way thay they function as single character interfaces.
641055714SkrisRC4	The RSA Inc. stream cipher.
641155714SkrisRC2	The RSA Inc. block cipher.
641255714SkrisIDEA	An implmentation of the IDEA cipher, the library supports ecb, cbc,
641355714Skris	cfb64 and ofb64 modes of operation.
641455714Skris
641555714SkrisNow all the above mentioned ciphers and digests libraries support high
641655714Skrisspeed, minimal 'crap in the way' type interfaces.  For fastest and
641755714Skrislowest level access, these routines should be used directly.
641855714Skris
641955714SkrisNow there was also the matter of public key crypto systems.  These are
642055714Skrisbased on large integer arithmatic.
642155714Skris
642255714SkrisBN	This is my large integer library.  It supports all the normal
642355714Skris	arithmentic operations.  It uses malloc extensivly and as such has
642455714Skris	no limits of the size of the numbers being manipulated.  If you
642555714Skris	wish to use 4000 bit RSA moduli, these routines will handle it.
642655714Skris	This library also contains routines to 'generate' prime numbers and
642755714Skris	to test for primality.  The RSA and DH libraries sit on top of this
642855714Skris	library.  As of this point in time, I don't support SHA, but
642955714Skris	when I do add it, it will just sit on top of the routines contained
643055714Skris	in this library.
643155714SkrisRSA	This implements the RSA public key algorithm.  It also contains
643255714Skris	routines that will generate a new private/public key pair.
643355714Skris	All the RSA functions conform to the PKCS#1 standard.
643455714SkrisDH	This is an implementation of the
643555714Skris	Diffie-Hellman protocol.  There are all the require routines for
643655714Skris	the protocol, plus extra routines that can be used to generate a
643755714Skris	strong prime for use with a specified generator.  While this last
643855714Skris	routine is not generally required by applications implementing DH,
643955714Skris	It is present for completeness and because I thing it is much
644055714Skris	better to be able to 'generate' your own 'magic' numbers as oposed
644155714Skris	to using numbers suplied by others.  I conform to the PKCS#3
644255714Skris	standard where required.
644355714Skris
644455714SkrisYou may have noticed the preceeding section mentions the 'generation' of
644555714Skrisprime numbers.  Now this requries the use of 'random numbers'. 
644655714Skris
644755714SkrisRAND	This psuedo-random number library is based on MD5 at it's core
644855714Skris	and a large internal state (2k bytes).  Once you have entered enough
644955714Skris	seed data into this random number algorithm I don't feel
645055714Skris	you will ever need to worry about it generating predictable output.
645155714Skris	Due to the way I am writing a portable library, I have left the
645255714Skris	issue of how to get good initial random seed data upto the
645355714Skris	application but I do have support routines for saving and loading a
645455714Skris	persistant random number state for use between program runs.
645555714Skris	
645655714SkrisNow to make all these ciphers easier to use, a higher level
645755714Skrisinterface was required.  In this form, the same function would be used to
645855714Skrisencrypt 'by parts', via any one of the above mentioned ciphers.
645955714Skris
646055714SkrisEVP	The Digital EnVeloPe library is quite large.  At it's core are
646155714Skris	function to perform encryption and decryption by parts while using
646255714Skris	an initial parameter to specify which of the 17 different ciphers
646355714Skris	or 4 different message digests to use.  On top of these are implmented
646455714Skris	the digital signature functions, sign, verify, seal and open.
646555714Skris	Base64 encoding of binary data is also done in this library.
646655714Skris
646755714SkrisPEM	rfc???? describe the format for Privacy Enhanced eMail.
646855714Skris	As part of this standard, methods of encoding digital enveloped
646955714Skris	data is an ascii format are defined.  As such, I use a form of these
647055714Skris	to encode enveloped data.  While at this point in time full support
647155714Skris	for PEM has not been built into the library, a minimal subset of
647255714Skris	the secret key and Base64 encoding is present.  These reoutines are
647355714Skris	mostly used to Ascii encode binary data with a 'type' associated
647455714Skris	with it and perhaps details of private key encryption used to
647555714Skris	encrypt the data.
647655714Skris	
647755714SkrisPKCS7	This is another Digital Envelope encoding standard which uses ASN.1
647855714Skris	to encode the data.  At this point in time, while there are some
647955714Skris	routines to encode and decode this binary format, full support is
648055714Skris	not present.
648155714Skris	
648255714SkrisAs Mentioned, above, there are several different ways to encode
648355714Skrisdata structures.
648455714Skris
648555714SkrisASN1	This library is more a set of primatives used to encode the packing
648655714Skris	and unpacking of data structures.  It is used by the X509
648755714Skris	certificate standard and by the PKCS standards which are used by
648855714Skris	this library.  It also contains routines for duplicating and signing
648955714Skris	the structures asocisated with X509.
649055714Skris	
649155714SkrisX509	The X509 library contains routines for packing and unpacking,
649255714Skris	verifying and just about every thing else you would want to do with
649355714Skris	X509 certificates.
649455714Skris
649555714SkrisPKCS7	PKCS-7 is a standard for encoding digital envelope data
649655714Skris	structures.  At this point in time the routines will load and save
649755714Skris	DER forms of these structees.  They need to be re-worked to support
649855714Skris	the BER form which is the normal way PKCS-7 is encoded.  If the
649955714Skris	previous 2 sentances don't make much sense, don't worry, this
650055714Skris	library is not used by this version of SSLeay anyway.
650155714Skris
650255714SkrisOBJ	ASN.1 uses 'object identifiers' to identify objects.  A set of
650355714Skris	functions were requred to translate from ASN.1 to an intenger, to a
650455714Skris	character string.  This library provieds these translations
650555714Skris	
650655714SkrisNow I mentioned an X509 library.  X509 specified a hieachy of certificates
650755714Skriswhich needs to be traversed to authenticate particular certificates.
650855714Skris
650955714SkrisMETH	This library is used to push 'methods' of retrieving certificates
651055714Skris	into the library.  There are some supplied 'methods' with SSLeay
651155714Skris	but applications can add new methods if they so desire.
651255714Skris	This library has not been finished and is not being used in this
651355714Skris	version.
651455714Skris	
651555714SkrisNow all the above are required for use in the initial point of this project.
651655714Skris
651755714SkrisSSL	The SSL protocol.  This is a full implmentation of SSL v 2.  It
651855714Skris	support both server and client authentication.  SSL v 3 support
651955714Skris	will be added when the SSL v 3 specification is released in it's
652055714Skris	final form.
652155714Skris
652255714SkrisNow quite a few of the above mentioned libraries rely on a few 'complex'
652355714Skrisdata structures.  For each of these I have a library.
652455714Skris
652555714SkrisLhash	This is a hash table library which is used extensivly.
652655714Skris
652755714SkrisSTACK	An implemetation of a Stack data structure.
652855714Skris
652955714SkrisBUF	A simple character array structure that also support a function to
653055714Skris	check that the array is greater that a certain size, if it is not,
653155714Skris	it is realloced so that is it.
653255714Skris	
653355714SkrisTXT_DB	A simple memory based text file data base.  The application can specify
653455714Skris	unique indexes that will be enforced at update time.
653555714Skris
653655714SkrisCONF	Most of the programs written for this library require a configuration
653755714Skris	file.  Instead of letting programs constantly re-implment this
653855714Skris	subsystem, the CONF library provides a consistant and flexable
653955714Skris	interface to not only configuration files but also environment
654055714Skris	variables.
654155714Skris
654255714SkrisBut what about when something goes wrong?
654355714SkrisThe one advantage (and perhaps disadvantage) of all of these
654455714Skrisfunctions being in one library was the ability to implement a
654555714Skrissingle error reporting system.
654655714Skris	
654755714SkrisERR	This library is used to report errors.  The error system records
654855714Skris	library number, function number (in the library) and reason
654955714Skris	number.  Multiple errors can be reported so that an 'error' trace
655055714Skris	is created.  The errors can be printed in numeric or textual form.
655155714Skris
655255714Skris
655355714Skris==== ssluse.doc ========================================================
655455714Skris
655555714SkrisWe have an SSL_CTX which contains global information for lots of
655655714SkrisSSL connections.  The session-id cache and the certificate verificate cache.
655755714SkrisIt also contains default values for use when certificates are used.
655855714Skris
655955714SkrisSSL_CTX
656055714Skris	default cipher list
656155714Skris	session-id cache
656255714Skris	certificate cache
656355714Skris	default session-id timeout period
656455714Skris	New session-id callback
656555714Skris	Required session-id callback
656655714Skris	session-id stats
656755714Skris	Informational callback
656855714Skris	Callback that is set, overrides the SSLeay X509 certificate
656955714Skris	  verification
657055714Skris	The default Certificate/Private Key pair
657155714Skris	Default read ahead mode.
657255714Skris	Default verify mode and verify callback.  These are not used
657355714Skris	  if the over ride callback mentioned above is used.
657455714Skris	
657555714SkrisEach SSL can have the following defined for it before a connection is made.
657655714Skris
657755714SkrisCertificate
657855714SkrisPrivate key
657955714SkrisCiphers to use
658055714SkrisCertificate verify mode and callback
658155714SkrisIO object to use in the comunication.
658255714SkrisSome 'read-ahead' mode information.
658355714SkrisA previous session-id to re-use.
658455714Skris
658555714SkrisA connection is made by using SSL_connect or SSL_accept.
658655714SkrisWhen non-blocking IO is being used, there are functions that can be used
658755714Skristo determin where and why the SSL_connect or SSL_accept did not complete.
658855714SkrisThis information can be used to recall the functions when the 'error'
658955714Skriscondition has dissapeared.
659055714Skris
659155714SkrisAfter the connection has been made, information can be retrived about the
6592238405SjkimSSL session and the session-id values that have been decided upon.
659355714SkrisThe 'peer' certificate can be retrieved.
659455714Skris
659555714SkrisThe session-id values include
659655714Skris'start time'
659755714Skris'timeout length'
659855714Skris
659955714Skris
660055714Skris
660155714Skris==== stack.doc ========================================================
660255714Skris
660355714SkrisThe stack data structure is used to store an ordered list of objects.
660455714SkrisIt is basically misnamed to call it a stack but it can function that way
660555714Skrisand that is what I originally used it for.  Due to the way element
660655714Skrispointers are kept in a malloc()ed array, the most efficient way to use this
660755714Skrisstructure is to add and delete elements from the end via sk_pop() and
660855714Skrissk_push().  If you wish to do 'lookups' sk_find() is quite efficient since
660955714Skrisit will sort the stack (if required) and then do a binary search to lookup 
661055714Skristhe requested item.  This sorting occurs automatically so just sk_push()
661155714Skriselements on the stack and don't worry about the order.  Do remember that if
661255714Skrisyou do a sk_find(), the order of the elements will change.
661355714Skris
661455714SkrisYou should never need to 'touch' this structure directly.
661555714Skristypedef struct stack_st
661655714Skris	{
661755714Skris	unsigned int num;
661855714Skris	char **data;
661955714Skris	int sorted;
662055714Skris
662155714Skris	unsigned int num_alloc;
662255714Skris	int (*comp)();
662355714Skris	} STACK;
662455714Skris
662555714Skris'num' holds the number of elements in the stack, 'data' is the array of
662655714Skriselements.  'sorted' is 1 is the list has been sorted, 0 if not.
662755714Skris
662855714Skrisnum_alloc is the number of 'nodes' allocated in 'data'.  When num becomes
662955714Skrislarger than num_alloc, data is realloced to a larger size.
663055714SkrisIf 'comp' is set, it is a function that is used to compare 2 of the items
663155714Skrisin the stack.  The function should return -1, 0 or 1, depending on the
663255714Skrisordering.
663355714Skris
663455714Skris#define sk_num(sk)	((sk)->num)
663555714Skris#define sk_value(sk,n)	((sk)->data[n])
663655714Skris
663755714SkrisThese 2 macros should be used to access the number of elements in the
663855714Skris'stack' and to access a pointer to one of the values.
663955714Skris
664055714SkrisSTACK *sk_new(int (*c)());
664155714Skris	This creates a new stack.  If 'c', the comparison function, is not
664255714Skrisspecified, the various functions that operate on a sorted 'stack' will not
664355714Skriswork (sk_find()).  NULL is returned on failure.
664455714Skris
664555714Skrisvoid sk_free(STACK *);
664655714Skris	This function free()'s a stack structure.  The elements in the
664755714Skrisstack will not be freed so one should 'pop' and free all elements from the
664855714Skrisstack before calling this function or call sk_pop_free() instead.
664955714Skris
665055714Skrisvoid sk_pop_free(STACK *st; void (*func)());
665155714Skris	This function calls 'func' for each element on the stack, passing
665255714Skristhe element as the argument.  sk_free() is then called to free the 'stack'
665355714Skrisstructure.
665455714Skris
665555714Skrisint sk_insert(STACK *sk,char *data,int where);
665655714Skris	This function inserts 'data' into stack 'sk' at location 'where'.
665755714SkrisIf 'where' is larger that the number of elements in the stack, the element
665855714Skrisis put at the end.  This function tends to be used by other 'stack'
665955714Skrisfunctions.  Returns 0 on failure, otherwise the number of elements in the
666055714Skrisnew stack.
666155714Skris
666255714Skrischar *sk_delete(STACK *st,int loc);
666355714Skris	Remove the item a location 'loc' from the stack and returns it.
666455714SkrisReturns NULL if the 'loc' is out of range.
666555714Skris
666655714Skrischar *sk_delete_ptr(STACK *st, char *p);
666755714Skris	If the data item pointed to by 'p' is in the stack, it is deleted
666855714Skrisfrom the stack and returned.  NULL is returned if the element is not in the
666955714Skrisstack.
667055714Skris
667155714Skrisint sk_find(STACK *st,char *data);
667255714Skris	Returns the location that contains a value that is equal to 
667355714Skristhe 'data' item.  If the comparison function was not set, this function
667455714Skrisdoes a linear search.  This function actually qsort()s the stack if it is not
667555714Skrisin order and then uses bsearch() to do the initial search.  If the
667655714Skrissearch fails,, -1 is returned.  For mutliple items with the same
667755714Skrisvalue, the index of the first in the array is returned.
667855714Skris
667955714Skrisint sk_push(STACK *st,char *data);
668055714Skris	Append 'data' to the stack.  0 is returned if there is a failure
668155714Skris(due to a malloc failure), else 1.  This is 
668255714Skrissk_insert(st,data,sk_num(st));
668355714Skris
668455714Skrisint sk_unshift(STACK *st,char *data);
668555714Skris	Prepend 'data' to the front (location 0) of the stack.  This is
668655714Skrissk_insert(st,data,0);
668755714Skris
668855714Skrischar *sk_shift(STACK *st);
668955714Skris	Return and delete from the stack the first element in the stack.
669055714SkrisThis is sk_delete(st,0);
669155714Skris
669255714Skrischar *sk_pop(STACK *st);
669355714Skris	Return and delete the last element on the stack.  This is
669455714Skrissk_delete(st,sk_num(sk)-1);
669555714Skris
669655714Skrisvoid sk_zero(STACK *st);
669755714Skris	Removes all items from the stack.  It does not 'free'
669855714Skrispointers but is a quick way to clear a 'stack of references'.
669955714Skris
670055714Skris==== threads.doc ========================================================
670155714Skris
670255714SkrisHow to compile SSLeay for multi-threading.
670355714Skris
670455714SkrisWell basically it is quite simple, set the compiler flags and build.
670555714SkrisI have only really done much testing under Solaris and Windows NT.
670655714SkrisIf you library supports localtime_r() and gmtime_r() add,
670755714Skris-DTHREADS to the makefile parameters.  You can probably survive with out
670855714Skristhis define unless you are going to have multiple threads generating
670955714Skriscertificates at once.  It will not affect the SSL side of things.
671055714Skris
671155714SkrisThe approach I have taken to doing locking is to make the application provide
671255714Skriscallbacks to perform locking and so that the SSLeay library can distinguish
671355714Skrisbetween threads (for the error state).
671455714Skris
671555714SkrisTo have a look at an example program, 'cd mt; vi mttest.c'.
671655714SkrisTo build under solaris, sh solaris.sh, for Windows NT or Windows 95,
671755714Skriswin32.bat
671855714Skris
671955714SkrisThis will build mttest which will fire up 10 threads that talk SSL
672055714Skristo each other 10 times.
672155714SkrisTo enable everything to work, the application needs to call
672255714Skris
672355714SkrisCRYPTO_set_id_callback(id_function);
672455714SkrisCRYPTO_set_locking_callback(locking_function);
672555714Skris
672655714Skrisbefore any multithreading is started.
672755714Skrisid_function does not need to be defined under Windows NT or 95, the
672855714Skriscorrect function will be called if it is not.  Under unix, getpid()
672959191Skrisis call if the id_callback is not defined, for Solaris this is wrong
673059191Skris(since threads id's are not pid's) but under Linux it is correct
673155714Skris(threads are just processes sharing the data segement).
673255714Skris
673355714SkrisThe locking_callback is used to perform locking by the SSLeay library.
673455714Skriseg.
673555714Skris
673655714Skrisvoid solaris_locking_callback(mode,type,file,line)
673755714Skrisint mode;
673855714Skrisint type;
673955714Skrischar *file;
674055714Skrisint line;
674155714Skris	{
674255714Skris	if (mode & CRYPTO_LOCK)
674355714Skris		mutex_lock(&(lock_cs[type]));
674455714Skris	else
674555714Skris		mutex_unlock(&(lock_cs[type]));
674655714Skris	}
674755714Skris
674855714SkrisNow in this case I have used mutexes instead of read/write locks, since they
674955714Skrisare faster and there are not many read locks in SSLeay, you may as well
675055714Skrisalways use write locks.  file and line are __FILE__ and __LINE__ from
675155714Skristhe compile and can be usefull when debugging.
675255714Skris
675355714SkrisNow as you can see, 'type' can be one of a range of values, these values are
675455714Skrisdefined in crypto/crypto.h
675555714SkrisCRYPTO_get_lock_name(type) will return a text version of what the lock is.
675655714SkrisThere are CRYPTO_NUM_LOCKS locks required, so under solaris, the setup
675755714Skrisfor multi-threading can be
675855714Skris
675955714Skrisstatic mutex_t lock_cs[CRYPTO_NUM_LOCKS];
676055714Skris
676155714Skrisvoid thread_setup()
676255714Skris	{
676355714Skris	int i;
676455714Skris
676555714Skris	for (i=0; i<CRYPTO_NUM_LOCKS; i++)
676655714Skris		mutex_init(&(lock_cs[i]),USYNC_THREAD,NULL);
676755714Skris	CRYPTO_set_id_callback((unsigned long (*)())solaris_thread_id);
676855714Skris	CRYPTO_set_locking_callback((void (*)())solaris_locking_callback);
676955714Skris	}
677055714Skris
677155714SkrisAs a final note, under Windows NT or Windows 95, you have to be careful
677255714Skrisnot to mix the various threaded, unthreaded and debug libraries.
677355714SkrisNormally if they are mixed incorrectly, mttest will crash just after printing
677455714Skrisout some usage statistics at the end.  This is because the
677555714Skrisdifferent system libraries use different malloc routines and if
677655714Skrisdata is malloc()ed inside crypt32.dll or ssl32.dll and then free()ed by a
677755714Skrisdifferent library malloc, things get very confused.
677855714Skris
677955714SkrisThe default SSLeay DLL builds use /MD, so if you use this on your
678055714Skrisapplication, things will work as expected.  If you use /MDd,
678155714Skrisyou will probably have to rebuild SSLeay using this flag.
678255714SkrisI should modify util/mk1mf.pl so it does all this correctly, but 
678355714Skristhis has not been done yet.
678455714Skris
678555714SkrisOne last warning.  Because locking overheads are actually quite large, the
678655714Skrisstatistics collected against the SSL_CTX for successfull connections etc
678755714Skrisare not locked when updated.  This does make it possible for these
678855714Skrisvalues to be slightly lower than they should be, if you are
678955714Skrisrunning multithreaded on a multi-processor box, but this does not really
679055714Skrismatter much.
679155714Skris
679255714Skris
679355714Skris==== txt_db.doc ========================================================
679455714Skris
679555714SkrisTXT_DB, a simple text based in memory database.
679655714Skris
679755714SkrisIt holds rows of ascii data, for which the only special character is '\0'.
679855714SkrisThe rows can be of an unlimited length.
679955714Skris
680055714Skris==== why.doc ========================================================
680155714Skris
680255714SkrisThis file is more of a note for other people who wish to understand why
680355714Skristhe build environment is the way it is :-).
680455714Skris
680555714SkrisThe include files 'depend' as follows.
680655714SkrisEach of 
680755714Skriscrypto/*/*.c includes crypto/cryptlib.h
680855714Skrisssl/*.c include ssl/ssl_locl.h
680955714Skrisapps/*.c include apps/apps.h
681055714Skriscrypto/cryptlib.h, ssl/ssl_locl.h and apps/apps.h
681155714Skrisall include e_os.h which contains OS/environment specific information.
681255714SkrisIf you need to add something todo with a particular environment,
681355714Skrisadd it to this file.  It is worth remembering that quite a few libraries,
681455714Skrislike lhash, des, md, sha etc etc do not include crypto/cryptlib.h.  This
681555714Skrisis because these libraries should be 'independantly compilable' and so I
681655714Skristry to keep them this way.
681755714Skrise_os.h is not so much a part of SSLeay, as the placing in one spot all the
681855714Skrisevil OS dependant muck.
681955714Skris
682055714SkrisI wanted to automate as many things as possible.  This includes
682155714Skriserror number generation.  A
682255714Skrismake errors
682355714Skriswill scan the source files for error codes, append them to the correct
682455714Skrisheader files, and generate the functions to print the text version
682555714Skrisof the error numbers.  So don't even think about adding error numbers by
682655714Skrishand, put them in the form
682755714SkrisXXXerr(XXXX_F_XXXX,YYYY_R_YYYY);
682855714Skrison line and it will be automatically picked up my a make errors.
682955714Skris
683055714SkrisIn a similar vein, programs to be added into ssleay in the apps directory
683155714Skrisjust need to have an entry added to E_EXE in makefile.ssl and
683255714Skriseverthing will work as expected.  Don't edit progs.h by hand.
683355714Skris
683455714Skrismake links re-generates the symbolic links that are used.  The reason why
683555714SkrisI keep everything in its own directory, and don't put all the
683655714Skristest programs and header files in 'test' and 'include' is because I want
683755714Skristo keep the 'sub-libraries' independant.  I still 'pull' out
683855714Skrisindervidual libraries for use in specific projects where the code is
683955714Skrisrequired.  I have used the 'lhash' library in just about every software
684055714Skrisproject I have worked on :-).
684155714Skris
684255714Skrismake depend generates dependancies and
684355714Skrismake dclean removes them.
684455714Skris
684555714SkrisYou will notice that I use perl quite a bit when I could be using 'sed'.
684655714SkrisThe reason I decided to do this was to just stick to one 'extra' program.
684755714SkrisFor Windows NT, I have perl and no sed.
684855714Skris
684955714SkrisThe util/mk1mf.pl program can be used to generate a single makefile.
685055714SkrisI use this because makefiles under Microsoft are horrific.
685155714SkrisEach C compiler seems to have different linker formats, which have
685255714Skristo be used because the retarted C compilers explode when you do
685355714Skriscl -o file *.o.
685455714Skris
685555714SkrisNow some would argue that I should just use the single makefile.  I don't
685655714Skrislike it during develoment for 2 reasons.  First, the actuall make
685755714Skriscommand takes a long time.  For my current setup, if I'm in
685855714Skriscrypto/bn and I type make, only the crypto/bn directory gets rebuilt,
685955714Skriswhich is nice when you are modifying prototypes in bn.h which
686055714Skrishalf the SSLeay depends on.  The second is that to add a new souce file
686155714SkrisI just plonk it in at the required spot in the local makefile.  This
686255714Skristhen alows me to keep things local, I don't need to modify a 'global'
686355714Skristables (the make for unix, the make for NT, the make for w31...).
686455714SkrisWhen I am ripping apart a library structure, it is nice to only
686555714Skrishave to worry about one directory :-).
686655714Skris
686755714SkrisHaving said all this, for the hell of it I put together 2 files that
686855714Skris#include all the souce code (generated by doing a ls */*.o after a build).
686955714Skriscrypto.c takes only 30 seconds to build under NT and 2 minutes under linux
687055714Skrisfor my pentium100.  Much faster that the normal build :-).
687155714SkrisAgain, the problem is that when using libraries, every program linked
687255714Skristo libcrypto.a would suddenly get 330k of library when it may only need
687355714Skris1k.  This technique does look like a nice way to do shared libraries though.
687455714Skris
687555714SkrisOh yes, as a final note, to 'build' a distribution, I just type
687655714Skrismake dist.
687755714SkrisThis cleans and packages everything.  The directory needs to be called
687855714SkrisSSLeay since the make does a 'cd ..' and renames and tars things up.
687955714Skris
688055714Skris==== req.1 ========================================================
688155714Skris
688255714SkrisThe 'req' command is used to manipulate and deal with pkcs#10
688355714Skriscertificate requests.
688455714Skris
688555714SkrisIt's default mode of operation is to load a certificate and then
688655714Skriswrite it out again.
688755714Skris
688855714SkrisBy default the 'req' is read from stdin in 'PEM' format.
688955714SkrisThe -inform option can be used to specify 'pem' format or 'der'
689055714Skrisformat.  PEM format is the base64 encoding of the DER format.
689155714Skris
689255714SkrisBy default 'req' then writes the request back out. -outform can be used
689355714Skristo indicate the desired output format, be it 'pem' or 'der'.
689455714Skris
689555714SkrisTo specify an input file, use the '-in' option and the '-out' option
689655714Skriscan be used to specify the output file.
689755714Skris
689855714SkrisIf you wish to perform a command and not output the certificate
689955714Skrisrequest afterwards, use the '-noout' option.
690055714Skris
690155714SkrisWhen a certificate is loaded, it can be printed in a human readable
690255714Skrisascii format via the '-text' option.
690355714Skris
690455714SkrisTo check that the signature on a certificate request is correct, use
690555714Skristhe '-verify' option to make sure that the private key contained in the
690655714Skriscertificate request corresponds to the signature.
690755714Skris
690855714SkrisBesides the default mode, there is also the 'generate a certificate
690955714Skrisrequest' mode.  There are several flags that trigger this mode.
691055714Skris
691155714Skris-new will generate a new RSA key (if required) and then prompts
691255714Skristhe user for details for the certificate request.
691355714Skris-newkey has an argument that is the number of bits to make the new
691455714Skriskey.  This function also triggers '-new'.
691555714Skris
691655714SkrisThe '-new' option can have a key to use specified instead of having to
691755714Skrisload one, '-key' is used to specify the file containg the key.
691855714Skris-keyform can be used to specify the format of the key.  Only
691955714Skris'pem' and 'der' formats are supported, later, 'netscape' format may be added.
692055714Skris
692155714SkrisFinally there is the '-x509' options which makes req output a self
692255714Skrissigned x509 certificate instead of a certificate request.
692355714Skris
692455714SkrisNow as you may have noticed, there are lots of default options that
692555714Skriscannot be specified via the command line.  They are held in a 'template'
692655714Skrisor 'configuration file'.  The -config option specifies which configuration
692755714Skrisfile to use.  See conf.doc for details on the syntax of this file.
692855714Skris
692955714SkrisThe req command uses the 'req' section of the config file.
693055714Skris
693155714Skris---
693255714Skris# The following variables are defined.  For this example I will populate
693355714Skris# the various values
693455714Skris[ req ]
693555714Skrisdefault_bits	= 512		# default number of bits to use.
693655714Skrisdefault_keyfile	= testkey.pem	# Where to write the generated keyfile
693755714Skris				# if not specified.
693855714Skrisdistinguished_name= req_dn	# The section that contains the
693955714Skris				# information about which 'object' we
694055714Skris				# want to put in the DN.
694155714Skrisattributes	= req_attr	# The objects we want for the
694255714Skris				# attributes field.
694355714Skrisencrypt_rsa_key	= no		# Should we encrypt newly generated
694455714Skris				# keys.  I strongly recommend 'yes'.
694555714Skris
694655714Skris# The distinguished name section.  For the following entries, the
694755714Skris# object names must exist in the SSLeay header file objects.h.  If they
694855714Skris# do not, they will be silently ignored.  The entries have the following
694955714Skris# format.
695055714Skris# <object_name>		=> string to prompt with
695155714Skris# <object_name>_default	=> default value for people
695255714Skris# <object_name>_value	=> Automatically use this value for this field.
695355714Skris# <object_name>_min	=> minimum number of characters for data (def. 0)
695455714Skris# <object_name>_max	=> maximum number of characters for data (def. inf.)
695555714Skris# All of these entries are optional except for the first one.
695655714Skris[ req_dn ]
695755714SkriscountryName			= Country Name (2 letter code)
695855714SkriscountryName_default		= AU
695955714Skris
696055714SkrisstateOrProvinceName		= State or Province Name (full name)
696155714SkrisstateOrProvinceName_default	= Queensland
696255714Skris
696355714SkrislocalityName			= Locality Name (eg, city)
696455714Skris
696555714SkrisorganizationName		= Organization Name (eg, company)
696655714SkrisorganizationName_default	= Mincom Pty Ltd
696755714Skris
696855714SkrisorganizationalUnitName		= Organizational Unit Name (eg, section)
696955714SkrisorganizationalUnitName_default	= MTR
697055714Skris
697155714SkriscommonName			= Common Name (eg, YOUR name)
697255714SkriscommonName_max			= 64
697355714Skris
697455714SkrisemailAddress			= Email Address
697555714SkrisemailAddress_max		= 40
697655714Skris
697755714Skris# The next section is the attributes section.  This is exactly the
697855714Skris# same as for the previous section except that the resulting objects are
697955714Skris# put in the attributes field. 
698055714Skris[ req_attr ]
698155714SkrischallengePassword		= A challenge password
698255714SkrischallengePassword_min		= 4
698355714SkrischallengePassword_max		= 20
698455714Skris
698555714SkrisunstructuredName		= An optional company name
698655714Skris
698755714Skris----
698855714SkrisAlso note that the order that attributes appear in this file is the
698955714Skrisorder they will be put into the distinguished name.
699055714Skris
699155714SkrisOnce this request has been generated, it can be sent to a CA for
699255714Skriscertifying.
699355714Skris
699455714Skris----
699555714SkrisA few quick examples....
699655714Skris
699755714SkrisTo generate a new request and a new key
699855714Skrisreq -new
699955714Skris
700055714SkrisTo generate a new request and a 1058 bit key
700155714Skrisreq -newkey 1058
700255714Skris
700355714SkrisTo generate a new request using a pre-existing key
700455714Skrisreq -new -key key.pem
700555714Skris
700655714SkrisTo generate a self signed x509 certificate from a certificate
700755714Skrisrequest using a supplied key, and we want to see the text form of the
700855714Skrisoutput certificate (which we will put in the file selfSign.pem
700955714Skrisreq -x509 -in req.pem -key key.pem -text -out selfSign.pem
701055714Skris
701155714SkrisVerify that the signature is correct on a certificate request.
701255714Skrisreq -verify -in req.pem
701355714Skris
701455714SkrisVerify that the signature was made using a specified public key.
701555714Skrisreq -verify -in req.pem -key key.pem
701655714Skris
701755714SkrisPrint the contents of a certificate request
701855714Skrisreq -text -in req.pem
701955714Skris
702055714Skris==== danger ========================================================
702155714Skris
702255714SkrisIf you specify a SSLv2 cipher, and the mode is SSLv23 and the server
702355714Skriscan talk SSLv3, it will claim there is no cipher since you should be
702455714Skrisusing SSLv3.
702555714Skris
702655714SkrisWhen tracing debug stuff, remember BIO_s_socket() is different to
702755714SkrisBIO_s_connect().
702855714Skris
702955714SkrisBSD/OS assember is not working
703055714Skris
7031