Database Reference
In-Depth Information
Using the RSA Cipher
We will use
cipherRSA
to do encryption and decryption. To use it, we will have to provide it with the key
and tell it what mode to use (encryption or decryption), then we will ask it to perform that task on some
data. The
cipherRSA
method calls in Listing 5-5 will be used for that process.
Listing 5-5.
Initialize the Cipher to Do Encryption
cipherRSA.init( Cipher.ENCRYPT_MODE, extRSAPubKey, random );
byte[] encodedBytes = cipherRSA.doFinal( clearBytes );
The first method called here is used for initializing the
Cipher
to a specific mode: encrypt or decrypt.
In this case, we have asked it to be ready to encrypt data (
Cipher.ENCRYPT_MODE
). To decrypt, we would
initialize the
Cipher
to
Cipher.DECRYPT_MODE
.
The second method of
cipherRSA
that we call is
doFinal()
. This method does the encryption or
decryption that we initialized on the data we provide in the parameter (e.g., encrypt
clearBytes
). Note
that the
doFinal()
method of
Cipher
takes a byte array as its parameter and returns a byte array. For that
reason, we will be converting
Strings
and other objects to and from byte arrays as we perform
encryption. Note also that a byte is simply eight bits and a bit is just one memory position being turned
Off or On (value of 0 or 1). A byte array is simply a series of bytes assembled in and handled as a single
list. If some of these concepts are unfamiliar, you can explore computer architecture at
JAVA CONSTANTS
Notice how we specify
ENCRYPT_MODE
in the
Cipher
initialization call in Listing 5-5. This is a member
variable (notice it is not a method call—no parentheses or parameters.) Notice also that it must be static;
we do not refer to a specific instance of
Cipher
to get
ENCRYPT_MODE
, but to the static class definition.
Lastly, notice that the member name is in all uppercase. The uppercasing of this member variable and
underscore characters between words indicates, by
Java naming conventions
, that this is a
constant
. In
Cipher
, it would have been declared like this:
public static final int ENCRYPT_MODE = <some int>;
The modifier
final
helps identify this member as a constant, but
final
may not mean what you might
think at first. It does not mean that the value cannot change, but that the address pointed to in memory
cannot be changed to a new address. For primitive and simple types, like the
int
ENCRYPT_MODE
, this
amounts to the same thing. That includes
Strings
, because they are immutable (refer to Chapter 3).
However, if you had a constant
Date
member, defined like the following
public static final Date BERLIN_WALL_FELL = new Date( 89, 10, 9 );
you could not prevent someone from coming along later and setting:
BERLIN_WALL_FELL.setYear( 80 );
Even though this
Date
is declared
static final
. Wouldn't it be nice to improve history!