Java Reference
In-Depth Information
As with message digests, the interface to the Bouncy Castle API is conceptually
similar to the JCA and the SATSA-CRYPTO API but not exactly the same. Again, instead
of using a factory to create the desired cipher engine, you simply instantiate the engine
directly. You initialize the resulting engine similarly, specifying whether you want the
engine to encrypt (pass true ) or decrypt (pass false ) along with options for the engine
to its init method. Finally, you pass the bytes to be encrypted or decrypted to the
engine for processing. How the engine accepts the bytes you want it to process
depends on whether the engine implements a block cipher or stream cipher. You
pass bytes to a block cipher or asymmetric block cipher for processing using the
processBlock method, passing a complete block each time. You can determine the block
size of a block cipher by invoking its getBlockSize method, or an asymmetric block
cipher by invoking either getInputBlockSize or getOutputBlockSize for the input or
output block size, respectively. You pass bytes to a stream cipher using the processBytes
method.
In either case, the cipher engine returns the result to the method you invoked for
processing. This method may throw one of a number of exceptions, including the
DataLengthException if the data array is of an invalid length, or the IllegalStateException
if you failed to initialize the cipher.
Although this example uses the (relatively weak) RC4 algorithm, a number of other
supported ciphers are packaged with the Bouncy Castle API. Unlike the SATSA-CRYPTO
API, the algorithms are implemented for both symmetric and asymmetric ciphers, so
applications requiring both encryption and decryption of public-key ciphers benefit
from using the Bouncy Castle API instead of the SATSA-CRYPTO API.
In addition to supporting many different ciphers, the Bouncy Castle API also pro-
vides key-generation algorithms for the ciphers it supports. This is an important feature
of the API, because secure key generation and distribution is a challenge when writing
applications. The classes contained by org.bouncycastle.crypto.generators include
generators for supported ciphers; creating a key is as simple as creating the appropriate
generator and invoking a method. For example, to create a random key for DES, you
might write the code shown in Listing 15-7.
Listing 15-7. Generating a Random Key
org.bouncycastle.crypto.generators.DESKeyGenerator generator =
new org.bouncycastle.crypto.generators.DESKeyGenerator();
byte[] key = generator.generateKey();
Some key generators must be initialized first, so be sure to check the documentation
for the cipher system and key generator you choose. These key generators are usually
those that provide keys for public-key cryptography, in which a pair of keys—one public
for distribution to other parties and the other private for decryption—are used for
message encryption and decryption.
 
Search WWH ::




Custom Search