Java Reference
In-Depth Information
Using Bouncy Castle Ciphers
In the Bouncy Castle cryptography package, stream ciphers are represented by the
org.bouncycastle.crypto.StreamCipher
interface. You just need to initialize the cipher,
using
init()
, and then you can encrypt or decrypt data using
processBytes()
.
The Bouncy Castle package only provides one direct stream cipher implementation,
org.bouncycastle.crypto.engines.RC4
. If you'd prefer to use a different algorithm, you can use a
block cipher instead. You can treat block ciphers like stream ciphers using Cipher Feedback (CFB)
mode. In the Bouncy Castle package, this is implemented in the
org.bouncycastle.crypto
➥
.StreamBlockCipher
class. This technique gives you access to Bouncy Castle's considerable
arsenal of block cipher implementations, from the wizened DES through AES, Blowfish, Rijndael,
and more. For more information on cipher modes, see Chapter 7 of
Java Cryptography
.
Our simple implementation instantiates a pair of
RC4
objects, something like this:
StreamCipher inCipher = new RC4Engine();
StreamCipher outCipher = new RC4Engine();
The ciphers need to be initialized before they can be used. The first parameter to
init()
should be
true
if the cipher will be encrypting data,
false
for decryption. The second parameter is
essentially the key, wrapped up in a
KeyParameter
object.
// Assume we have retrieved inKey and outKey, both byte arrays.
inCipher.init(false, new KeyParameter(inKey));
outCipher.init(true, new KeyParameter(outKey));
To encrypt data, we just need to create an array to hold the ciphertext. Then call the stream
cipher's
processBytes()
method to perform the encryption. The
processBytes()
method
accepts the plaintext array, an index into the plaintext, the number of bytes that should be
processed, the ciphertext array, and the index at which the ciphertext should be written.
// Assume we have a byte array called plaintext.
byte[] ciphertext = new byte[plaintext.length];
outCipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);
Decryption is identical, except you would use a cipher that has been initialized for
decryption.
Implementation
The source code for
StealthMIDlet
is shown in Listing 18-5. This MIDlet has a simple user
interface, initialized in the
startApp()
method. The MIDlet's ciphers are also created and
initialized in
startApp().
Search WWH ::
Custom Search