/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss or reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

/**	@addtogroup crypto */
/**	@{ */
/**		@defgroup hash		Hashing functions */
/**		@defgroup cipher	Encryption functions */
/**		@defgroup rsa		Public key cryptography */
/**		@defgroup nanu		Natural numbers module */
/**	@} */

/**	@addtogroup crypto

Often used cryptographic functions.

This library contains implementations of often used cryptographic
functions. These include various hash functions, encryption and decryption
functions.
<br><br>
The library is reasonably portable. It is intended for 32-bit targets
(or possibly 16-bit ones that have some HW support for 32-bit operations).
Thus, the library assumes that a <tt>short</tt> is 16 bits wide,
an <tt>int</tt> is a 32-bit type while <tt>long long</tt> is 64 bits.
This is the default for most 32-bit processors for which gcc compiles and
for 16-bit targets you can tell gcc to treat <tt>int</tt> as a 32-bit
quantity.<br>
There are no assumptions on the endianness of the processor or other
architectural features. Very few gcc specific features are used, thus it
should not be an issue to port this library to any other 32-bit architecture
and/or a different C compiler. To facilitate that, the library is entirely
self-contained, it does not call any external functions, not even memcpy()
or memset(). The only ARM specific part is a bunch of assembly functions
in the natural numbers submodule, involved mostly in modular exponentiation,
but those functions are also provided in pure C form.
<br><br>
@par <b>IMPORTANT:</b>
The cryptographic library is re-entrant but isn't strictly thread safe.<br>
As long as all threads use different state descriptors (i.e. different blocks
of memory), they can call the cryptographic functions simultaneously (that is,
the library itself does not use any static data).
However, if two threads share a single state descriptor then you <b>must</b>
guarantee that only one of them calls a function operating on that state at
any given time. That is, if you have two separate data streams, each processed
by a separate thread and each thread has its own hash state, both threads can
call the hash functions (passing their own hash state descriptors) without any
mutual exclusivity protection. However, if there are two threads working on
a single hash state (i.e. they calculate a single hash of their collective
data), then you must guarantee that if one thread called a hash function,
passing the shared state to it, the other thread will not call a hash function
<i>with the same shared state</i> until the first invocation returns.<br>In
other words, the functions are re-entrant but the state descriptors are not.
If you share descriptors between threads, you must guarantee mutual exlusivity
protection (just like for any other shared data item).<br>
The implementation of such protection is entirely your responsibility. If you
call into the library simultaneously from different threads, <i>using the same
state descriptor object</i>, then if you are lucky you get messed up
results, if you are unlucky, you will end up with misterious memory
corruptions and possibly a crash.<br>
Note that for DES and AES the key schedule data, as far as encryption and
decryption is concerned, is constant, so you can run two instances of
AES in parallel using the same key schedule. In the case of ARC4, however,
it is a <i>state</i>, which changes with every invocation of the function,
therefore you can not use the same key descriptor for two parallel instances.
I tried to be consistent in the wording and if you see that a function
has a <i>state</i> parameter, you know that that parameter can not be shared
by two simultaneous instances. Parameters that are invariant are called
by other names and they are declared <tt>const</tt> in the function
prototype.

@par Conformance:
The implementations are based on the following specifications:
- RFC-1321 for MD5
- RFC-3174 for SHA-1
- RFC-2104 for HMAC
- NIST-SP-800-67 (includes FIPS-46-3) for DES and TDEA (a.k.a. triple-DES)
- NIST-SP-800-38A for the block cipher modes
- FIPS-197 for AES
- PKCS#1-1.5 for RSA (and ASN.1 for the key conversion tool)
- There is no formal spec for ARC4, but it's described at many places,
  including Applied Cryptography (a must!) and various IETS documents,
  most prominently the ARCFOUR internet draft from 1999.

@par General advice:
I am not a cryptography expert. Chances are, neither are you. Do not
try to be clever. Do not try to invent cunning tricks to hide your
data even better. More often than not the result is less secure than it was
before you added your clever twist. Follow the basic rules that those who
<i>are</i> experts of the field repeat over and over:
-	Security by obscurity does not work. If you try to protect data by using
	a cryptographically unsafe function that you keep secret and hope that
	your adversaries can't figure it out, you might as well not bother at all.
	See the entertainment industry's futile attempt to encrypt DVDs (CSS).
	They had a much larger budget than you do, they worked on it a lot,
	figured that it was safe <i>and</i> they managed to keep it secret.
	Well, a Norwegian teenager broke that crown jewel of the copyright lobby,
	because he wanted to watch DVDs on his computer (which Hollywood did
	not consider to be an "endorsed player").<br>
-	Using security but then exposing your keys is just straight dumb. Having
	your key stored in an external EEPROM is equivalent to writing them on the
	box with fluoro texter. If the device has to hold a key, store it in
	a secure location. The only place you can consider secure is inside
	the controller chip and only if you can guarantee that it is not
	possible to read from the chip or to execute malicious code on the
	chip. Anything external, anything that can be accessed by desoldering
	the chip and putting it into a debug environment - you might as well
	not waste your time with it because it will be broken. A notable exception
	from this rule is the public key for RSA. Using RSA you can establish a
	secure channel (to a secure server) using ephemeral keys - after all,
	that's what RSA is for.<br>
-	Assume that your adversary has every bit of information about your system,
	including schematics, source code, deployment configuration etc. The
	only thing (s)he doesn't have is your key(s). If assuming the above
	makes your system vulnerable, then you are using the security by
	obscurity model, which is flawed.<br>
-	Follow the standards. Don't tweak them. Innocent looking changes
	may result in dramatic loss of security.<br>
-	Do not try to invent authentication and key establishment schemes.
    Even if you use a fairly safe cryptographic core function, a badly
	designed method around it can render it useless. The spectacular disaster
	called WEP for 802.11 is a prominent example of that.
-	Do not give away information. If in a multiple step security verification
	the first step fails, keep on going. Declare failure only at the end. That
	way on the one hand you wasted the resources of your adversary and on the
	other you did not tell him/her what step failed. Do not specify the reason
	of failure, only the fact that the process was not successful. Note that
	'keep on going' means to actually perform all calculations even if you
	know that the results will be thrown away - otherwise your adversary can
	monitor your power consumption, for example, and realise that you do not
	really do anything, even if you pretend to be busy calculating something.
	<br>

@par Note:
Cryptographic functions are big, need a lot of memory and CPU cycles.
Most state descriptors are large (several tens or even hundreds of bytes),
and the functions require up to several hundred bytes of stack space.
You need reasonably beefy chips to use the cryptographic library.
*/

/** @addtogroup hash

Common cryptographic hash functions.

A hash function is a function that receives some input of arbitrary length
and generates a fixed length output. Since the input is usually much longer
than the output, you can not recover the input from the output. Furthermore,
even a single bit change in the input will cause many bits of the output to
change. Since the output is of a fixed length capable of representing only
a finite number of possible values but there are infinitely many possible
inputs, there will be clashes, when two different inputs generate the same
output. However, cryptographic hash functions are designed to make such
clashes extremely improbable on similar inputs. Therefore, hash functions
can be used to verify that a message is not altered.
<br><br>
The most commonly used two cryptographic hash functions, MD5 and SHA-1 are
implemented in this sub-module. In addition, HMAC, the keyed hash message
authentication code (using MD5 or SHA-1) is also provided.
<br><br>
Although MD5 has been broken (meaning that there exist programs that can
generate input that will hash to a given output value), it is probably
the most frequently used cryptographic hash function. SHA-1 is more resistent;
even though vulnerabilities of the algorithm were identified, as of 2009 it
has not been broken yet.
<br><br>
To use the these functions, you need to include <b><tt>crypto/hash.h</tt></b>.
<br><br>
The following table gives you a rough idea about the performance of
the various hash functions. The values represent the time (in milliseconds)
required to calculate the hash of 1KB of data using various functions.
The final calculation of the hash is included in the time. The performance
of these functions is significantly different depending on whether you use
the ARM or the THUMB versions. If you can afford the FLASH, you should
consider enabling interworking and use the ARM version of the crypto library
even if you use THUMB mode otherwise. The times were measured on an LPC23xx
running at 60MHz.
<b>
@verbatim
Time needed to hash 1KB of data [ms]

Hash function     ARM      THUMB
@endverbatim
</b>
@verbatim
MD5               1.38     2.30
MD5 fast          0.77     1.25
SHA1              1.48     2.92
SHA1 fast         1.13     1.81
@endverbatim
*/

/** @addtogroup cipher

Common ciphers.

This sub-module implements some commonly used cipher functions.
Ciphers come in two flavours, stream ciphers and block ciphers.

@section stream Stream ciphers
A stream cipher works on a stream of bytes. There is an internal state that
changes after the encryption of each byte, therefore even if you feed the
same data repeatedly to the cipher, you will get different results. For all
intents and purposes a stream cipher is a pseudo random number generator that
generates a random byte for each input byte and XOR-s that byte with the input.
To decode, you generate the same random sequence and XOR it with the encrypted
stream. There are versions of stream ciphers that feed back the output into the
encryption process, thus a change of an input byte will change all the
output bytes after that. Others do not feed back anything and thus a single
input byte affects only a single output byte.
@subsection rc4 ARC4
The library provides the ARC4 stream cipher. This cipher is very fast and
was very popular. It was invented by RSA and was named RC4. RSA kept the
algorithm secret, but it was somehow leaked to the Internet. The name
ARC4 stands for Alleged RC4. It was later demonstrated that the leaked
algorithm is indeed the RC4 algorithm.<br>
ARC4 has several weaknesses and is not considered really secure. However,
you can use it to achieve reasonable security if after creating the original
state from the key you use the algorithm to encrypt a certain amount of data
that you discard (that is, you advance the state of the pseudo-random generator
by a certain amount). As a minimum, 768 bytes should be generated and discarded
but 3072 bytes is strongly suggested.

@section block Block ciphers
Block ciphers process a fixed length of input at a time (a block). They
have no internal state, therefore if you provide the same input, they will
generate the same output (using the same key, that is). That is a disadvantage,
because that means that repeated patterns in the cleartext will generate
repeated patterns in the ciphertext and your adversary can use that to
try to infer information about the nature of your message. To overcome this
drawback, there are ways of using a feedback that effectively turns a block
cipher into a stream cipher, although one that operates block sized chunks of
the stream. Depending on how you organise the feedback, your cipher operates
in a certain <i>mode</i>.
@subsection modes Common block cipher modes
-	ECB<br>
	This mode actually does nothing. There is no feedback at all and it is
	just a name for using the block cipher as a block cipher, through the
	stream cipher like interface.
-	CBC<br>
	This mode feeds back the output of the previous encryption block to the
	input of the next, thus turning it into a stream cipher.
	Any input byte will affect all subsequent output blocks.
-	CFB<br>
	Similar to CBC, but the feed-back mechanism is different. Like CBC, a
	change of an input byte will affect all subsequent blocks.
-	OFB<br>
	This mode turns the block cipher into a pseudo-random generator and
	uses that as the basis of a stream cipher. Any change in the input will
	only affect the corresponding byte of the output, changes do not
	propagate, not even within the block.
-	CTR<br>
	This mode also turns the block cipher into a pseudo-random generator,
	but it does it by feeding it a count of blocks processed so far. Like
	with OFB, a change in the input only affects the corresponding output byte.

With the exception of ECB, all those modes have an initial vector (or nonce)
associated with them. This is a block-length size data that is usually
generated random (and exchanged by public-key method) so that even if the
encryption key is the same and the data is the same, the encrypted stream
will still be different, thus your adversaries can not deduce that you are
sending the same message or not and they can not fool you by replaying
an encrypted message that they have captured earlier. In this implementation
in case of the CTR mode the nonce is used to initialise the counter.
<br><br>
As mentioned, the CTR mode initialises the counter to the nonce and then
increments it by one after each operation. The most often used CTR mode
generates a the block-size number needed for each step by using the
nonce smaller than the block size and use that as the more significant
half of the block sized number, while the less significant half is the
counter; you are not supposed to send a message that has more blocks than
what you can count on this less significant half.
Therefore, if that is the case, when you receive the nonce, you must place
it in the more significant half of the initial vector and zero all the
remaining bytes of the vector. The initial vector is always stored in
big-endian byte order, that is, you store your nonce in the first n bytes
of the buffer and zero the remaining block size - n bytes. An other common
method is that the nonce is block sized and the block you use for a step is
the arithmetic sum of the nonce and the counter; the latter is also block
sized, starting with the value of 0. This of course is equivalent to
initialising the counter to the nonce and just incrementing it, which is
what the routine in the library does.
<br><br>
There's an other important issue of your message not being an exact multiple
of the block size. In that case, you have to use a padding to make it so.
There is no set standard on how to pad messages to multiples of block sizes,
therefore the library leaves that to you. The most often, but not exclusively
used method is appending 0x80 after your message and then as many 0x00 bytes
as needed to make it a multiple of block size; if your original message was
a multiple of the block size, you still do this, making a message one block
longer. Nevertheless, the library doesn't do it for you, it's up to you
(or more likely the standard that you implement) what padding scheme you use.

@subsection des DES and TDEA
DES is a very old encryption standard. It is easy to implement in hardware,
but it is not designed for efficient software implementation. DES uses a
56-bit key and is considered unsecure; a common PC can break DES in a fairly
short time. TDEA is a standard that uses DES and makes it secure. It processes
the data by running it through DES three times (encrypt, decrypt, encrypt)
using two or three different DES keys. TDEA is also known as triple-DES.
While TDEA is secure, it is much slower than AES. Both DES and TDEA works
on 8-byte blocks.

@subsection aes AES
AES has been developed to counter the problems with DES. AES is secure,
uses longer keys and, unlike DES, is software friendly. AES has several
variants, depending on block size and key size. The library supports
16-byte blocks with 128, 192 or 256 bit (16, 24 or 32 bytes) keys.

<br><br>
To use the these ciphers, you need to include <b><tt>crypto/cipher.h</tt></b>.
<br><br>
The following table gives you a rough idea about the performance of
the various functions in the library. The values represent the time,
in milliseconds, that are required to perform the given function on
1KB of data. In case of the block ciphers, ECB mode is used (i.e. no
pre- or postprocessing of the data). The preparation of the key schedule
is not included in the time shown. The performance of these functions
is significantly different depending on whether you use the ARM or the
THUMB versions. If you can afford the FLASH, you should consider enabling
interworking and use the ARM version of the crypto library even if you use
THUMB mode otherwise. The times were measured on an LPC23xx running at 60MHz.
<br>
DES and ARC4 needs the same time to encrypt and decrypt. AES, however, is
slower in decrypting. Therefore, for AES the decryption time is given
separately.
<b>
@verbatim
Time needed to encrypt (decrypt) 1KB of data [ms]

Crypto        ARM      THUMB       ARM      THUMB
function       (encryption)         (decryption)
@endverbatim
</b>
@verbatim
AES-128       3.44     5.48        5.79     7.81
AES-192       4.05     6.55        6.94     9.38
AES-256       4.66     7.61        8.06    10.95
DES           6.90    10.97
3-DES        20.22    32.40
ARC4          0.63     1.01
@endverbatim
*/

/** @addtogroup rsa

Public key cryptography.

Public key cryptography refers to a class of cryptographic methods where
you have different keys for encrypting and decrypting the message. There
are several such asymmetric methods, the most frequently used ones are the
Diffie-Hellman key exchange algorithm, the Digital Signature Algorithm (DSA)
and the Rivest-Shamir-Adleman (RSA) algorithm. The library contains an
implementation of the RSA algorithm.

@section rsa_theo The theory behind the RSA algorithm

The RSA public key cryptography is based on the mathematical properties of
finite fields. The basic idea is the following: You select two big primes,
p and q. These are typically several hundred to several thousand bits long.
Then you calculate their product, n = p * q. The number n is called the
<i>modulus</i>. Naturally, the length of the modulus is the sum of the
lengths of p and q. The length of this modulus is the "key length", which,
according to the current standards, is minimum 768 bits, typically 1024
or 2048 bits.
Then you select a number, e, with certain properties. The value of e, which
is called the <i>public exponent</i>, is fairly small, the largest value
occuring in practice is 17 bits long. The SSH key generator tool typically
chooses the value of 35, a mere 6 bits. Then you calculate a third number, d,
which is called the <i>private exponent</i>. This number is in the same
magnitude as the modulus, that is, 1024 or 2048 bits long. The way d is
calculated from p, q and e guarantees some important properties. Let x
be a number that is less than the modulus. Then the following will be true:
<br><br>
( x<sup>e</sup> mod n )<sup>d</sup> mod n = x<br>
( x<sup>d</sup> mod n )<sup>e</sup> mod n = x
<br><br>
Furthermore, for the given n and e there's no number other than d for which
the above holds true. Now to calculate d from p, q and e is easy but to
calculate d from n and e is not possible, unless you manage to find p and q
that make up n. Since factoring big numbers is a very hard problem,
you can assume that d can not be calculated from n and e. A further property
of modular exponentiation is that even if you know e, n and x<sup>e</sup> mod
n, finding x from these is no simpler than finding p and q that make up n.
<br><br>
So, to use the above for cryptographic purposes, you publish n and e.
Everybody can know those. On the other hand, you keep d (and of course p and q)
secret. When someone wants to send you a secret message, they turn a message
into a big number M (which is just a string of bytes, really) and calculate
<br>
C = M<sup>e</sup> mod n
<br>
and send the resulting number, C to you. Anyone can see C on transit but without
knowing d they can't do anything with it. Only you can recover the message by
calculating<br>
M = C<sup>d</sup> mod n
<br>
So, we have a way by which people can send you messages that only you can read.
Unfortunately, if you want to send a secret message, the above doesn't work.
If you calculate
<br>
A = M<sup>d</sup> mod n
<br>
then everybody who knows e and n can decode the message. It is still a useful
operation, however. For any given M you are the only one who can generate A
so that decoding A using e and n will result in M. Therefore, this method can
be used to authenticate messages. Anyone can read it, but you can guarantee
that it was originated by you and was not tampered width.
<br><br>
The (n,e) tuple is called the <i>public key</i> and you publish it. The
(n,d) tuple is your <i>private key</i> and you keep it secret. So, if each
party has his/her own private key and a public key, we have two basic
operations now: when you want to send a secret message, you encode it with the
recipient's public key and the recipient decodes it with his/her private key
and when you want to send an authenticated (but not secret) message, you encode
it with your private key and all recipients can verify its authenticity by
decoding it with your public key. You can combine these to send secret,
authenticated messages. <i>Note that the proper algorithm for message
authentication is DSA, which uses similar maths but is not the same as
RSA.</i>

@section rsa_prac Practical considerations

The theory is simple enough (unless you actually want to understand <i>why</i>
modular exponentiation has these properties, of course).
There are a few practical issues, though. One is that usually the message
you want to send is longer than 1024 or 2048 bits.
The other is that modular exponentiation of large numbers is a very CPU
intensive activity. Using the public key is relatively cheap, because e is
small. However, since d is typically as large as the modulus, private key
operations are several orders of magnitude slower. In addition, the time
needed for public operations increases quadraticly with the key length
(assuming that the public exponent remains the same) while the private
operations' time requirement increases cubicly.
<br><br>
Thus, it is not feasible to use the RSA algorithm to encrypt the actual
message itself. Instead, when you want to establish a secure communication
channel with your party, you choose a random encryption key. It is called the
<i>session key</i>. You encrypt it with the other party's public key and
send it over, using RSA. You and your partner now share a randomly generated
encryption key that can be used to encrypt and decrypt messages using a
symmetric (and fast) cipher, such as AES. When you finish the current
communication session, the key gets discareded (it is said that the session
key is <i>ephemeral</i>) and if you start a new session, you generate a new
key that you again exchange using RSA. The important point is that you use
RSA to facilitate a secure <i>key exchange</i>, the encryption of the actual
data is not done by RSA.

@section rsa_stand Standards

There are standards that describe the format of the RSA messages and the
the format of the keys. The most important standard is the PKCS#1, published
by RSA (the company founded by the inventors of RSA). PKCS#1 has several
versions, the latest one is 2.1. However, the library implements the data
encapsulation described in version 1.5 of the standard, because that is the
most widely used method today.
<br><br>
The above standard also describes how the keys should be formatted and in
turn it refers to the ASN.1 standard that defines a way of exchanging
arbitrary structured information - a little bit like XML but binary, not
text. From that point on, it's a Wild West. Every package that is based
on RSA has its own favourite method of storing the information described
by PKCS#1 and ASN.1 in some textual container and they have little utilities
to convert keys from one package's format to the other's.
<br><br>
This library is no exception. The RSA functions in the library require the
keys to be in a specific non-standard format. In particular, the keys
are represented as C structure objects. That is more efficient than the
DER encoding described by the standards and it is certainly more compiler
friendly. A tool is provided in the package that can turn keys generated
by the <tt>ssh-keygen</tt> program (part of the SSH package) to the format
required by the library. See the documentation for the \ref lpc_rsa program.

@section rsa_impl About this implementation

The RSA functions use the natural numbers module in the library for the actual
calculations. Although the RSA functions hide all the natural number processing
details, there is one function in the natural number library, namely
BC_NanuInit() which you will have to call directly, to prepare the workspace
for the calculations performed by the RSA routines.
<br><br>
To use these functions, you need to include <b><tt>crypto/rsa.h</tt></b>.
<br><br>
The most time critical parts of the natural numbers library are written
in assembly. Therefore, there's little difference between ARM and THUMB
mode execution times. The table below gives you the run-time of private
and public operations with various key lengths (the public exponent in
all cases was 35) on a 60MHz LPC23xx chip.
<b>@verbatim
 Key      Public   Private
[bit]      [ms]     [ms]
@endverbatim </b>
@verbatim
 768          5      180
1024          8      360
2048         27     2330
4096        103    17150
@endverbatim
*/

/** @addtogroup nanu

Natural numbers processing.

Certain cryptographic functions, most prominently the RSA public key
cryptography and the Diffie-Hellman key exchange algorithm depend on
number theory problems that are computationally very hard to solve.
These functions are all working on natural numbers, that is, non-negative
integers (we consider 0 as a natural number). Quite often the operations
involve calculating the remainder of division by a large number. The maths
behind the whole thing is the finite field theory and if you want to understand
how (and why) the algorithms work, you should get a finite field textbook.<br>
In practice, the numbers you deal with tend to be several hundred or a few
thousand bits long and the most prominent operation is modular exponentiation.
<br><br>
If you consider that a 2048 bit number is roughly 600 decimal digits,
you can appreciate the computational demand of raising a 600 digit number
to a 600 digit power, resulting in a number about a million decimal digits
long, then calculating the remainder of dividing that million-digit number
by a 600 digit number. Fortunately, the properties of finite fields allow
you to do that efficiently, without any million-digit numbers and 600 digit
divisions. That's what this library gives you: efficient implementations
of elementary arithmetic functions operating on large natural numbers.
<br><br>
The natural numbers module is part of the cryptographic library because the
RSA implementation uses it, but it is a self-contained unit. It provides the
basic arithmetic operations on large positive integers. It actually offers
more than what RSA needs, so that you can, if you want, implement more
advanced cryptographic operations with it.
<br><br>
The module needs a chunk of memory as its workspace. You pass that memory
to the initialisation function and you shall not touch that memory until you
finished all operations. The operations are all performed on a stack. If you
have used RPN (Reverse Polish Notation) calculators or programmed in the FORTH
language then you will find the functions in this library very familiar.
If not, here's a quick run-down:
<br><br>
Numbers are pushed to a stack. The arithmetic operations are carried out by
removing the operator's operands from the top of the stack, perform the
operation on the operands and pushing the result back to the stack. Therefore,
if you want to calculate <tt>a - b</tt> then you push <tt>a</tt> to the stack
first, then you push <tt>b</tt> and then you subtract. The subtract
operation will pop both <tt>a</tt> and <tt>b</tt> from the stack,
calculate the difference and push that onto the stack.<br>
Since any operation thus destroys its operands, you have a handful of operators
that manipulate the stack itself. You can duplicate elements, swap them, destroy
them and so on, so that you don't have to push and pop numbers all the time.
Normally you do not need external temporary storage, because the stack
manipulation operations are powerful enough to let you use the stack itself
for temporary storage - that's the whole idea, actually, that you perform all
operations on the stack.<br>
You never see the stack itself. The only interface between your code and the
stack is pushing a number and popping a number, to and from the top of the
stack. You can not take a look at, let alone modify, the third element of the
stack, or any element of it, for that matter. If you have never worked with
stack machines, then it looks weird at first, but you can get used to it very
quickly.
<br><br>
The function descriptions all contain a diagram of what they do to the stack.
The left hand side of the "==>" symbol indicates the stack before the operation
and the right hand side of "==>" is how the stack looks after the operation.
The numbers on the stack are repsesented by a symbol or an expression, separated
by space. The leftmost such element is the top of the stack (note that this is
the opposite of the convention used for FORTH words!). The ... is used to
indicate some other stack elements that are not relevant for the operation;
it does not matter what they are or if they exist at all, they have no effect
on the operation and the operation doesn't affect them. For example, when you
add two numbers, a and b, your stack behaves like this:
@verbatim
           before              after

          +-------+
          |   b   |
          +-------+          +-------+
          |   a   |          |  a+b  |
          +-------+          +-------+
          |  ...  |          |  ...  |
          |  ...  |          |  ...  |
@endverbatim
and that will be represented by the stack diagram:
@verbatim
          b a ... ==> a+b ...
@endverbatim
Every function returns an integer error code. If there was an error, then
the returned value is negative. The error codes are defined in the header.
If there was no error and the function gives you some result, it is always
a non-negative integer. If the function does not have a return value as such,
it will return <tt>BC_NANU_NANU<sup>*</sup></tt>, which is a non-negative
number.
<br><br><b>Note:</b> If an error occurs, then the entire stack is emptied
and the state is of the whole natutal number engine is reset. You should
check the returned code for each operation.
<br><br>
<i><sup>*</sup> Hommage to Robin Williams.</i>
<br><br>
To use these functions, you need to include <b><tt>crypto/nanu.h</tt></b>.
*/

