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