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
Cipher
using thegetInstance()
factory method.Initialize the
Cipher
for encryption or decryption usinginit()
. These methods accept a mode (eitherCipher.ENCRYPT_MODE
orCipher.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 ...
Get Java Cryptography now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.