javax.crypto.Cipher
The
javax.crypto.Cipher
class encapsulates a cipher algorithm. A
Cipher either encrypts data or decrypts data. The
Cipher class encompasses both asymmetric (public
key) and symmetric (private key) algorithms.
This class is part of the JCE, a piece of software that cannot be exported from the United States. For a description of the JCE, refer to Chapter 3. Groups outside the United States have implemented the JCE based on its documentation. Two such implementations are Cryptix (http://www.systemics.com/software/cryptix-java/) and IAIK-JCE (http://www.jce.iaik.tu-graz.ac.at/).
Cipher
is an abstract class, so you can’t
instantiate it directly. Like the classes in the JCA, it provides
factory methods that return useful instances. Using a
Cipher is a three-step process:
Obtain a
Cipherusing thegetInstance()factory method.Initialize the
Cipherfor encryption or decryption usinginit(). These methods accept a mode (eitherCipher.ENCRYPT_MODEorCipher.DECRYPT_MODE) and aKey. The type of key you use, public, private, or secret, depends on theCipher’s algorithm.Encrypt or decrypt data using the
update()anddoFinal()methods.
In the SecretWriting example from Chapter 1, for the encrypting case, these steps look
like:
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] raw = cipher.doFinal(stringBytes);You probably noticed that the call to
getInstance() specifies more than just an algorithm name. As a matter of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access