This document is intended as a companion to the Java Cryptography Architecture (JCA) API Specification & Reference. References to chapters not present in this document are to chapters in the JCA Specification.
The Java Cryptography Extension (JCE) provides a set of APIs to cryptographic functionality, including symmetric, asymmetric, stream and block encryption, and key agreement. It supplements the security functionality of the JCA in the JDK, which itself includes digital signatures and message digests.
The JCE is provided as a Java extension to the JDK.
The architecture of the JCE follows the same design principles found elsewhere in the JCA: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture.
The JCE API covers:
- Symmetric bulk encryption, such as DES, RC2, and IDEA
- Symmetric stream encryption, such as RC4
- Asymmetric encryption, such as RSA
- Password-based encryption (PBE), such as PbeWithMD5AndDES-CBC (as defined in PKCS#5)
- Key Agreement, such as Diffie-Hellman
JCE comes with a cryptographic provider package ("SunJCE"), which supplies implementations of the following algorithms:
- Data Encryption Standard (DES) in ECB, CBC, CFB, OFB, and PCBC modes with PKCS#5-style padding
- DES-EDE (also known as triple DES) in ECB, CBC, CFB, OFB, and PCBC modes with PKCS#5-style padding
- PbeWithMD5AndDES-CBC
- Diffie-Hellman Key Agreement between 2 parties
Concepts
This section provides a high-level description of the concepts implemented by the API, and the exact meaning of the technical terms used in the API specification.
Encryption and Decryption
Encryption is the process of taking data (called cleartext) and a short string (a key), and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a short key string, and producing cleartext.
Password-Based Encryption
Password-Based Encryption (PBE) generates a key from a password, and encrypts using that key. In order to make the task of getting from password to key very time-consuming for an attacker, most PBE implementations will mix in a random number, known as a salt, to create the key.
Cipher
Encryption and decryption are done using a cipher. A cipher is an object capable of carrying out encryption and decryption according to an encryption scheme (algorithm).
Key Agreement
Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.
The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption. It forms the core of the JCE.
Creating a Cipher Object
Like other engine classes in the API, Cipher objects are created using the
getInstance
factory methods on the Cipher class. A factory method is a static method that returns an instance of a class, in this case, an instance of a Cipher subclass implementing a requested transformation.A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a feedback mode and padding scheme. A transformation is of the form: "algorithm" or "algorithm/mode/padding" (in the former case, defaults are used for mode and padding).
When requesting a block cipher in stream cipher mode (e.g.,
DES
inCFB
orOFB
mode), you may optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the Sun JCE provider uses a default of 64 bits.)To create a Cipher object, you must specify the transformation name. You may also specify which provider you want to supply the implementation of the requested transformation:
public static Cipher getInstance(String transformation);public static Cipher getInstance(String transformation, String provider);
If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, if there is a preferred one.
If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not.
For example, use the following to specify the DES algorithm, ECB mode, and PKCS#5 padding:
Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding");Standard names to be used to specify the algorithm, mode, and padding components of a transformation are discussed in Appendix A in this document.
The objects returned by factory methods are uninitialized, and must be initialized before they become usable.
Initializing a Cipher Object
A Cipher object obtained from
getInstance
must be initialized for one of two modes (encryption or decryption), which are defined as final integer constants in theCipher
class. The two modes can be referenced by their symbolic names:Each of the Cipher initialization methods takes a mode parameter (
- ENCRYPT_MODE
- DECRYPT_MODE
opmode
), and initializes the Cipher object for that mode. Other parameters include the key (key
), algorithm parameters (params
), and a source of randomness (random
).To initialize a Cipher object, call one of the
init
methods:public void init(int opmode, Key key);public void init(int opmode, Key key, SecureRandom random);
public void init(int opmode, Key key, AlgorithmParameterSpec params);
public void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random);
Note that when a Cipher object is initialized, it loses all previously-acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state acquired while in decryption mode.
Encrypting and Decrypting Data
Data can be encrypted/decrypted in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.
To encrypt or decrypt data in a single step, call one of the
doFinal
methods:public byte[] doFinal(byte[] input);public byte[] doFinal(byte[] input, int inputOffset, int inputLen);
public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output);
public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
To encrypt or decrypt data in multiple steps, call one of the
update
methods:public byte[] update(byte[] input);public byte[] update(byte[] input, int inputOffset, int inputLen);
public int update(byte[] input, int inputOffset, int inputLen, byte[] output);
public int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
A multiple-part operation must be terminated by one of the above
doFinal
methods (if there is still some input data left for the last step), or by one of the followingdoFinal
methods (if there is no input data left for the last step):public byte[] doFinal();public int doFinal(byte[] output, int outputOffset);
All the
doFinal
methods take care of any necessary padding or unpadding, if padding (or unpadding) has been specified as part of the transformation.
JCE introduces the concept of cipher stream classes, which combine an InputStream or OutputStream with a Cipher object. There are two types of cipher stream classes: CipherInputStream and CipherOutputStream.
CipherInputStream
This class is a FilterInputStream that encrypts or decrypts the data passing through it. Typically, this stream would be used as a filter to read an encrypted file.
This class has a constructor that takes an initialized Cipher and an InputStream as arguments. The Cipher is used to encrypt or decrypt all data read through the stream. The data is encrypted or decrypted, depending on the initialization of the Cipher.
This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.FilterInputStream and java.io.InputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, the
skip(long)
method skips only data that have been processed by the Cipher.It is crucial for a programmer using this class not to use methods that are not defined or overriden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherInputStream.
As an example of its usage, suppose
cipher1
andcipher2
have been initialized for encryption and decryption (with corresponding keys), respectively. The code below demonstrates how to easily connect several instances of CipherInputStream and InputStream:FileInputStream fis = new FileInputStream("/tmp/a.txt"); CipherInputStream cis1 = new CipherInputStream(fis, cipher1); CipherInputStream cis2 = new CipherInputStream(cis1, cipher2); FileOutputStream fos = new FileOutputStream("/tmp/b.txt"); byte[] b = new byte[8]; int i = cis2.read(b); while (i != -1) { fos.write(b, 0, i); i = cis2.read(b); }The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back when it is read from /tmp/a.txt.
CipherOutputStream
This class is a FilterOutputStream that encrypts or decrypts the data passing through it. Typically, this stream would be used as a filter to store data in encrypted format in a file.
This class has a constructor that takes an initialized Cipher and an OutputStream as arguments. The Cipher is used to encrypt or decrypt all data supplied via calls to one of the
write
methods. The data is encrypted or decrypted, depending on the initialization of the Cipher, and the result is written to the output stream.This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.OutputStream and java.io.FilterOutputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all. Moreover, this class catches all exceptions that are not thrown by its ancestor classes.
It is crucial for a programmer using this class not to use methods that are not defined or overriden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherOutputStream.
The following example demonstrates the usage of CipherOutputStream, where several instances of CipherOutputStream and OutputStream are connected. It is assumed that
cipher1
andcipher2
have been initialized for decryption and encryption (with corresponding keys), respectively:FileInputStream fis = new FileInputStream("/tmp/a.txt"); FileOutputStream fos = new FileOutputStream("/tmp/b.txt"); CipherOutputStream cos1 = new CipherOutputStream(fos, cipher1); CipherOutputStream cos2 = new CipherOutputStream(cos1, cipher2); byte[] b = new byte[8]; int i = fis.read(b); while (i != -1) { cos2.write(b, 0, i); i = fis.read(b); } cos2.flush();The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back before it is written to /tmp/b.txt.
A key generator is used to generate secret keys for symmetric algorithms.
Creating a Key Generator
Like other engine classes in the API, KeyGenerator objects are created using the
getInstance
factory methods on the KeyGenerator class. A factory method is a static method that returns an instance of a class, in this case, an instance of a KeyGenerator subclass for the requested symmetric algorithm.
getInstance
takes as its argument the name of a symmetric algorithm for which a secret key is to be generated. Optionally, a package provider name may be specified:public static KeyGenerator getInstance(String algorithm);public static KeyGenerator getInstance(String algorithm, String provider);
If just an algorithm name is specified, the system will determine if there is an implementation of the requested key generator available in the environment, and if there is more than one, if there is a preferred one.
If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key generator in the package requested, and throw an exception if there is not.
Initializing a KeyGenerator Object
A key generator for a particular algorithm creates a secret key that can be used with that algorithm. It also associates algorithm-specific parameters (if any) with the generated key.
There are two ways to generate a secret key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the KeyGenerator object:
If none of the above
- Algorithm-Independent Initialization
All key generators share the concept a source of randomness. There is an
init
method in the KeyGenerator class that takes a SecureRandom object as its argument:public void init(SecureRandom random);Since no other parameters are specified when you call the above
init
method, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with the key.
- Algorithm-Specific Initialization
For situations where you want to specify algorithm-specific parameters, there are two
init
methods that have anAlgorithmParameterSpec
argument. One also has aSecureRandom
argument, while the source of randomness is system-provided for the other:public void init(AlgorithmParameterSpec params);public void init(AlgorithmParameterSpec params, SecureRandom random);
init
methods is called, the KeyGenerator will use a system-provided source of randomness to generate the secret key.Creating a Key
The following method generates a secret key:public SecretKey generateKey();
This class represents a factory for secret keys.
Key factories are used to convert keys (opaque cryptographic keys of type
Key
) into key specifications (transparent representations of the underlying key material), and vice versa. Secret key factories only operate on secret (symmetric) keys.Key factories are bi-directional, i.e., they allow to build an opaque key object from a given key specification (key material), or to retrieve the underlying key material of a key object in a suitable format.
A provider should document the key specifications supported by its secret key factory. For example, the
SecretKeyFactory
for DES keys supplied by the Sun provider supportsDESKeySpec
as a transparent representation of DES keys, theSecretKeyFactory
for DES-EDE keys supportsDESedeKeySpec
as a transparent representation of DES-EDE keys, and theSecretKeyFactory
for PBE supportsPBEKeySpec
as a transparent representation of the underlying password.The following is an example of how to use a
SecretKeyFactory
to convert secret key data into aSecretKey
object, which can be used for a subsequentCipher
operation:byte[] desKeyData; DESKeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
This class enables a programmer to create an object and protect its confidentiality with a cryptographic algorithm.
Given any Serializable object, one can create a SealedObject that encapsulates the original object, in serialized format (i.e., a "deep copy"), and seals (encrypts) its serialized contents, using a cryptographic algorithm such as DES, to protect its confidentiality. The encrypted content can later be decrypted (with the corresponding algorithm using the correct decryption key) and de-serialized, yielding the original object.
A typical usage is illustrated in the following code segment. This example assumes that
cipher
is a Cipher object for DES and has been initialized for encryption using the DES keydesKey
:// create SealedObject SealedObject so = new SealedObject("we are here", cipher); ... // retrieve the original object cipher.init(Cipher.DECRYPT_MODE, desKey); try { String s = (String)so.getContent(cipher); } catch (Exception e) {};Note that the Cipher object must be fully initialized with the correct algorithm, key, padding scheme, etc., before being applied to a SealedObject.
The KeyAgreement class provides the functionality of a key agreement protocol. The keys involved in establishing a shared secret are created by one of the key generators (
KeyPairGenerator
orKeyGenerator
), aKeyFactory
, or as a result from an intermediate phase of the key agreement protocol.Creating a KeyAgreement Object
Each party involved in the key agreement has to create a KeyAgreement object. Like other engine classes in the API, KeyAgreement objects are created using the
getInstance
factory methods on the KeyAgreement class. A factory method is a static method that returns an instance of a class, in this case, an instance of a KeyAgreement subclass for the requested key agreement algorithm.
getInstance
takes as its argument the name of a key agreement algorithm. Optionally, a package provider name may be specified:public static KeyAgreement getInstance(String algorithm);public static KeyAgreement getInstance(String algorithm, String provider);
If just an algorithm name is specified, the system will determine if there is an implementation of the requested key agreement available in the environment, and if there is more than one, if there is a preferred one.
If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key agreement in the package requested, and throw an exception if there is not.
Initializing a KeyAgreement Object
A KeyAgreement object may be initialized with a source of randomness and a set of parameters, if this is required by the key agreement algorithm.
To initialize a Cipher object, call one of the
init
methods:public void init(SecureRandom random);public void init(AlgorithmParameterSpec params);
public void init(AlgorithmParameterSpec params, SecureRandom random);
Executing a KeyAgreement Phase
Every key agreement protocol consists of a number of phases that need to be executed by each party involved in the key agreement.
To execute a phase of the key agreement, call the
doPhase
method:public Key doPhase(int phase, Key key);The
phase
parameter identifies the phase to be executed, and thekey
parameter contains the key to be processed by that phase. An (intermediate) Key object may be returned as the result of executing a phase, to be used by subsequent phases.Let's look at the Diffie-Hellman key agreement protocol as an example. This protocol has 2 phases when executed between 2 parties: Phase 1 uses a party's own private key, and Phase 2 uses the other party's public key. There are no intermediate keys returned by any of the phases.
Generating the Shared Secret
After each party has executed all the required key agreement phases, it can compute the shared secret by calling one of the
generateSecret
methods:public byte[] generateSecret();public int generateSecret(byte[] sharedSecret, int offset);
Cryptographic providers for the JCE are installed and configured in much the same way as cryptographic providers for the JDK. There are two parts to installing a provider: installing the provider package classes, and configuring the provider. The Installing Providers section in the Java Cryptography Architecture API Specification & Reference document explains how to do this.
The masterClassName of Sun's cryptographic provider for the JCE ("SunJCE") is
javax.crypto.provider.SunJCE
. In order to statically add SunJCE to your list of approved providers, add the following line to thejava.security
file in thelib/security
directory of the JDK:security.provider.n=javax.crypto.provider.SunJCEThis declares the SunJCE provider, and specifies its preference order n.
To dynamically add the SunJCE provider to your list of providers, call either the
addProvider
orinsertProviderAt
method in theSecurity
class:Provider sunJce = new javax.crypto.provider.SunJCE(); Security.addProvider(sunJce);The latter type of registration is not persistent and can only be done by "trusted" programs.
Some of the
update
anddoFinal
methods of Cipher allow the caller to specify the output buffer into which to encrypt or decrypt the data. In these cases, it is important to pass a buffer that is large enough to hold the result of the encryption or decryption operation.The following method in Cipher can be used to determine how big the output buffer should be:
public int outOutputSize(int inputLen)
This section is a short tutorial on how to use the major features of the Java Cryptography Extension API.
Simple Encryption Example
This section takes the user through the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. Throughout this example, we use the Data Encryption Standard (DES).
Generating a Key
To create a DES key, we have to instantiate a KeyGenerator for DES. We do not specify a provider, because we do not care about a particular DES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness will be used to create the DES key:
KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey();After the key has been generated, the same KeyGenerator object can be re-used to create further keys.
Creating a Cipher
The next step is to create a Cipher instance. To do this, we use one of the
getInstance
factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/):
- the algorithm name
- the mode (optional)
- the padding scheme (optional)
In this example, we create a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS#5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation.
The standard algorithm name for DES is "DES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS#5-style padding is "PKCS5Padding":
Cipher desCipher;// Create the cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
We use the generated
desKey
from above to initialize the Cipher object for encryption:// Initialize the cipher for encryption desCipher.init(Cipher.ENCRYPT_MODE, desKey);// Our cleartext byte[] cleartext = "This is just an example".getBytes();
// Encrypt the cleartext byte[] ciphertext = desCipher.doFinal(cleartext);
// Initialize the same cipher for decryption desCipher.init(Cipher.DECRYPT_MODE, desKey);
// Decrypt the ciphertext byte[] cleartext1 = desCipher.doFinal(ciphertext);
cleartext
andcleartext1
are identical.Password-Based Encryption Example
In this example, the string "Do not share this with anybody" is used as the encryption password.
In order to use Password-Based Encryption (PBE) as defined in PKCS#5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption.
PBEKeySpec pbeKeySpec; PBEParameterSpec pbeParamSpec; SecretKeyFactory keyFac;// Salt byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 };
// Iteration count int count = 20;
// Create PBE parameter set pbeParamSpec = new PBEParameterSpec(salt, count);
// Convert password into SecretKey object, // using a PBE key factory pbeKeySpec = new PBEKeySpec("Do not share this with anybody"); keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext byte[] cleartext = "This is another example".getBytes();
// Encrypt the cleartext byte[] ciphertext = pbeCipher.doFinal(cleartext);
Key Agreement Example
The following example shows the Diffie-Hellman key agreement between two parties, Alice and Bob.
In Phase 1 of the Diffie-Hellman protocol, Alice and Bob each generate a Diffie-Hellman key pair, consisting of a public value and a private value.
In Phase 2, they trade public values and each uses the other's public value with their own private value to generate the same secret value.
The following code describes the key agreement protocol from Alice's perspective:
import java.security.*; import java.security.spec.*;KeyPairGenerator dhKeyPairGenerator;
// ALICE: creates her own Diffie-Hellman key pair; she chooses // a prime modulus size of 1024 bits. As part of the key pair // generation process, Diffie-Hellman parameters are created, // too. dhKeyPairGenerator = KeyPairGenerator.getInstance("DH"); dhKeyPairGenerator.initialize(1024); KeyPair dhKeyPair = dhKeyPairGenerator.generateKeyPair();
// ALICE: transmits her public key (in encoded format) to Bob. // The encoded key also contains her Diffie-Hellman parameters. byte[] dhPubKeyEncoded = dhKeyPair.getPublic().getEncoded();
// Out-of-band transmission of
dhPubKeyEncoded
to Bob// ALICE: initiates her version of the key agreement protocol // with her own private value KeyAgreement dhKeyAgree = KeyAgreement.getInstance("DH"); dhKeyAgree.doPhase(1, dhKeyPair.getPrivate());
// Meanwhile, Bob has created his own Diffie-Hellman key pair. // He has initialized his key pair generator with the // Diffie-Hellman parameters that he retrieved from Alice's // public key. // Bob sends his own public value (in encoded format) to Alice.
// ALICE: uses the appropriate key factory to convert the // encoding of Bob's key into a
PublicKey
KeyFactory dhKeyFactory = KeyFactory.getInstance("DH"); X509EncodedKeySpec dhBobPubKeySpec = new X509EncodedKeySpec (dhBobPubKeyEncoded); PublicKey dhBobPubKey = dhKeyFactory.generatePublic (dhBobPubKeySpec);// ALICE: completes her version of the key agreement protocol dhKeyAgree.doPhase(2, dhBobPubKey);
// ALICE: generates the shared secret byte[] secret = dhKeyAgree.generateSecret();
The API requires and utilizes a set of standard names for various algorithms, algorithm modes, padding schemes, etc. This appendix extends the standard set of names defined by Appendix A in the Java Cryptography Architecture API Specification & Reference as follows (please note that the following names are case-insensitive):
Cipher
Algorithm
DES
DESede
PBEWithMD5AndDES: Password-Based Encryption, as defined in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993.
Mode
ECB: Electronic Codebook Mode, as defined in: The National Institute of Standards and Technology (NIST) Federal Information Processing Standard (FIPS) PUB 81, "DES Modes of Operation," U.S. Department of Commerce, Dec 1980.
CBC: Cipher Block Chaining Mode, as defined in NIST FIPS PUB 81.
CFB: Cipher Feedback Mode, as defined in NIST FIPS PUB 81.
OFB: Output Feedback Mode, as defined in NIST FIPS PUB 81.
PCBC: Plaintext Cipher Block Chaining, as defined by Kerberos.
Padding
NoPadding: No padding.
PKCS5Padding: The padding scheme described in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993.
KeyAgreement
DH: Diffie-Hellman Key Agreement as defined in: RSA Laboratories, "PKCS #3: Diffie-Hellman Key-Agreement Standard," version 1.4, Nov 1993.