Java Reference
In-Depth Information
1. Generate the plaintext you want to encrypt as an array of bytes.
2. Generate the key you want to use to encrypt your plaintext, again as an array
of bytes.
3. Get an instance of the desired cipher implementation, which will be an instance
of java.security.Cipher .
4. Initialize the cipher.
5. Either encrypt the plaintext progressively using the Cipher 's update method, or
perform the encryption in a single operation using the Cipher 's doFinal method.
Predictably, decryption is the reverse of encryption; instead of specifying a cipher in
step 3, specify the cipher and indicate that it should be used in decryption mode. Instead
of passing plaintext in step 5, pass the enciphered text. Consider Listing 15-4, which
demonstrates encrypting a message.
Listing 15-4. Encrypting a Message
String algo= "RC4";
byte[] secretKey = { … };
String plainText = "Here there be treasure";
byte[] plainTextBytes = plainText.getBytes();
try {
java.security.Key key =
new SecretKeySpec(secretKey, 0, secretKey.length, algo);
java.security.Cipher cipher;
cipher = Cipher.getInstance(algo);
cipher.init(Cipher. ENCRYPT_MODE, key);
int ciphertextLength = plainText.length();
byte[] cipherTextBytes = new byte[ciphertextLength];
cipher.doFinal(plainTextBytes, 0, plainText.length, cipherTextBytes, 0);
} catch (Exception e) {…}
This follows the algorithm I outlined step for step; note especially the use of
ENCRYPT_MODE as the selected mode when initializing the Cipher instance. Decryption
would be the reverse of encryption, and the code would just need to pass DECRYPT_MODE for
the corresponding argument to init . After this code has run, assuming there are no
exceptions, the byte array cipherTextBytes will contain the encrypted text.
 
Search WWH ::




Custom Search