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) 1.2 provides a framework for encryption, key agreement, and message authentication. It includes interfaces and implementations of ciphers (symmetric, asymmetric, block, and stream ciphers), secure Java streams, sealed Java objects, and session key generation.
JCE 1.2 is designed so that other cryptography libraries can be plugged in as a service provider, and new algorithms can be added seamlessly.
JCE 1.2 supplements the Java Development Kit 1.2 (JDK), which already includes interfaces and implementations of message digests and digital signatures. JCE 1.2 is provided as a Java extension to the Java platform.
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 1.2 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)
- Key Agreement, such as Diffie-Hellman
- Message Authentication Codes (MAC)
JCE 1.2 comes with a built-in cryptographic provider ("SunJCE"), which supplies implementations of the following algorithms:
- Data Encryption Standard (DES) and Triple DES in ECB, CBC, CFB, OFB, and PCBC modes with PKCS#5-style padding
- MD5 with DES-CBC password-based encryption (as defined in PKCS #5)
- Diffie-Hellman Key Agreement between 2 parties
- HMAC-MD5 and HMAC-SHA1
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.
Message Authentication Code (MAC)
A MAC provides a way to check the integrity of information transmitted over or stored in an unreliable medium, based on a secret key. Typically, message authentication codes are used between two parties that share a secret key in order to validate information transmitted between these parties.
A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.
The Cipher Class
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 of the Cipher class. A factory method is a static method that returns an instance of a class, in this case, an instance ofCipher
which provides the 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 requested as part of the specified transformation.The Cipher Stream Classes
JCE 1.2 introduces the concept of secure Java streams, which combine an InputStream or OutputStream with a Cipher object. Secure Java streams are provided by the
CipherInputStream
andCipherOutputStream
classes.CipherInputStream
This class is a
FilterInputStream
that encrypts or decrypts the data passing through it. It is composed of anInputStream
, or one of its subclasses, and aCipher
. CipherInputStream represents a secure input stream into which a Cipher object has been interposed. Theread
methods of CipherInputStream return data that are read from the underlying InputStream but have additionally been processed by the embedded Cipher object. The Cipher object must be fully initialized before being used by a CipherInputStream.For example, if the embedded Cipher has been initialized for decryption, the CipherInputStream will attempt to decrypt the data it reads from the underlying InputStream before returning them to the application.
This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes
java.io.FilterInputStream
andjava.io.InputStream
. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that the data are additonally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, theskip(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. It is composed of anOutputStream
, or one of its subclasses, and aCipher
. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. Thewrite
methods of CipherOutputStream first process the data with the embedded Cipher object before writing them out to the underlying OutputStream. The Cipher object must be fully initialized before being used by a CipherOutputStream.For example, if the embedded Cipher has been initialized for encryption, the CipherOutputStream will encrypt its data, before writing them out to the underlying 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, so that all data are additionally processed by the embedded cipher. 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.
The Key Generator Class
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 of the KeyGenerator class. A factory method is a static method that returns an instance of a class, in this case, an instance ofKeyGenerator
which provides an implementation of the requested key generator.
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 symmetric-key algorithm creates a symmetric 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 key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object:
- Algorithm-Independent Initialization
All key generators share the concepts of a "strength" and a source of randomness. The measure of strength is universally shared by all algorithms, though it is interpreted differently for different algorithms. There is an
init
method that takes these two universally shared types of arguments. There is also one that takes just astrength
argument, and uses a system-provided source of randomness, and one that takes just a source of randomness:public void init(SecureRandom random); public void init(int strength); public void init(int strength, SecureRandom random);Since no other parameters are specified when you call the above algorithm-independent
init
methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with the generated key.
- Algorithm-Specific Initialization
For situations where a set of algorithm-specific parameters already exists, 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);In case the client does not explicitly initialize the KeyGenerator (via a call to an
init
method), each provider must supply (and document) a default initialization.Creating a Key
The following method generates a secret key:public SecretKey generateKey();The SecretKeyFactory Class
This class represents a factory for secret keys.
Key factories are used to convert keys (opaque cryptographic keys of type
java.security.Key
) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.A
javax.crypto.SecretKeyFactory
object operates only on secret (symmetric) keys, whereas ajava.security.KeyFactory
object processes the public and private key components of a key pair.Objects of type
java.security.Key
, of whichjava.security.PublicKey
,java.security.PrivateKey
, andjavax.crypto.SecretKey
are subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and may be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value
y
, the prime modulusp
, and the baseg
, and you feed the same specification to Diffie-Hellman key factories from different providers, the resultingPublicKey
objects will most likely have different underlying implementations.A provider should document the key specifications supported by its secret key factory. For example, the
SecretKeyFactory
for DES keys supplied by the SunJCE 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 = { (byte)0x01, (byte)0x02, ...}; DESKeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);In this case, the underlying implementation of
secretKey
is based on the provider ofkeyFactory
.An alternative, provider-independent way of creating a functionally equivalent
SecretKey
object from the same key material is to use theSecretKeySpec
class, which implements thejavax.crypto.SecretKey
interface:byte[] desKeyData = { (byte)0x01, (byte)0x02, ...}; SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");The SealedObject Class
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("This is secret", cipher); ... // retrieve the original object cipher.init(Cipher.DECRYPT_MODE, desKey); try { String s = (String)so.getObject(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
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 of the KeyAgreement class. A factory method is a static method that returns an instance of a class, in this case, an instance ofKeyAgreement
which provides 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
You initialize a KeyAgreement object with your private information. In the case of Diffie-Hellman, you initialize it with your Diffie-Hellman private key. Additional initialization information may contain a source of randomness and/or a set of algorithm parameters. Note that if the requested key agreement algorithm requires the specification of algorithm parameters, and only a key, but no parameters are provided to initialize the KeyAgreement object, the key must contain the required algorithm parameters. (For example, the Diffie-Hellman algorithm uses a prime modulus
p
and a base generatorg
as its parameters.)To initialize a Cipher object, call one of the
init
methods:public void init(Key key); public void init(Key key, SecureRandom random); public void init(Key key, AlgorithmParameterSpec params); public void init(Key key, 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 the next phase in the key agreement, call the
doPhase
method:public Key doPhase(Key key, boolean lastPhase);The
key
parameter contains the key to be processed by that phase. In most cases, this is the public key of one of the other parties involved in the key agreement, or an intermediate key that was generated by a previous phase.doPhase
may return an intermediate key that you may have to send to the other parties of this key agreement, so they can process it in a subsequent phase.The
lastPhase
parameter specifies whether or not the phase to be executed is the last one in the key agreeement: A value ofFALSE
indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value ofTRUE
indicates that this is the last phase of the key agreement and the key agreement is completed, i.e.,generateSecret
can be called next.In the example of Diffie-Hellman between two parties (see Appendix B), you call
doPhase
once, withlastPhase
set toTRUE
. In the example of Diffie-Hellman between three parties, you calldoPhase
twice: the first time withlastPhase
set toFALSE
, the 2nd time withlastPhase
set toTRUE
.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); public SecretKey generateSecret(String algorithm);The Mac Class
The Mac class provides the functionality of a Message Authentication Code (MAC).
Creating a Mac Object
Like other engine classes in the API, Mac objects are created using the
getInstance
factory methods of the Mac class. A factory method is a static method that returns an instance of a class, in this case, an instance ofMac
which provides the requested MAC algorithm.
getInstance
takes as its argument the name of a MAC algorithm. Optionally, a package provider name may be specified:public static Mac getInstance(String algorithm); public static Mac getInstance(String algorithm, String provider);If just an algorithm name is specified, the system will determine if there is an implementation of the requested MAC algorithm 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 MAC algorithm in the package requested, and throw an exception if there is not.
Initializing a Mac Object
A Mac object is always initialized with a secret key, which may be the result of a key agreement protocol, and may also be initialized with a set of parameters, if this is required by the requested MAC algorithm.
To initialize a Mac object, call one of the
init
methods:public void init(Key key); public void init(Key key, AlgorithmParameterSpec params);Computing a MAC
A MAC can be computed 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 compute the MAC of some data in a single step, call one of the
doFinal
methods:public byte[] doFinal(byte[] input);To compute the MAC of some data in multiple steps, call one of the
update
methods:public void update(byte input); public void update(byte[] input); public void update(byte[] input, int inputOffset, int inputLen);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 void doFinal(byte[] output, int outOffset);
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
com.sun.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=com.sun.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 com.sun.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 some of the major features of the JCE APIs. Complete sample programs that exercise the APIs can be found in Appendix B in this document.
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" 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"); 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
Please refer to Appendix B for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties, respectively.
The API requires and utilizes a set of standard names for various algorithms, algorithm modes, padding schemes, etc. This appendix supplements the standard set of names defined by Appendix A in the Java Cryptography Architecture API Specification & Reference. Note that algorithm names are treated case-insensitive.
Cipher
Algorithm
DES
DESede (alias: TripleDES)
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, November 1993.
KeyAgreement
DH: Diffie-Hellman Key Agreement as defined in: RSA Laboratories, "PKCS #3: Diffie-Hellman Key-Agreement Standard," version 1.4, November 1993.
MAC
HmacMD5: The HMAC-MD5 keyed-hashing algorithm as defined in: RFC 2104, "HMAC: Keyed-Hashing for Message Authentication," February 1997.
HmacSHA1: The HMAC-SHA1 keyed-hashing algorithm as defined in: RFC 2104, "HMAC: Keyed-Hashing for Message Authentication," February 1997.
/* * Copyright 1993-1997 Sun Microsystems, Inc. 901 San Antonio Road, * Palo Alto, California, 94303, U.S.A. All Rights Reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. * * CopyrightVersion 1.2 * */ import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import java.security.interfaces.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import com.sun.crypto.provider.SunJCE; /** * This test utility executes the Diffie-Hellman key agreement protocol * between 2 parties: Alice and Bob. * * By default, preconfigured parameters (1024 bit prime modulus and base * generator used by SKIP) are used. * If this program is called with the "-gen" option, a new set of parameters * (512 bit prime modulus and base generator) are created. (Parameter * generation takes a very long time to complete!) */ public class DHKeyAgreement2 { private DHKeyAgreement2() {} public static void main(String argv[]) { try { String mode = "USE_SKIP_DH_PARAMS"; // Add JCE to the list of providers SunJCE jce = new SunJCE(); Security.addProvider(jce); DHKeyAgreement2 keyAgree = new DHKeyAgreement2(); if (argv.length > 1) { keyAgree.usage(); throw new Exception("Wrong number of command options"); } else if (argv.length == 1) { if (!(argv[0].equals("-gen"))) { keyAgree.usage(); throw new Exception("Unrecognized flag: " + argv[0]); } mode = "GENERATE_DH_PARAMS"; } keyAgree.run(mode); } catch (Exception e) { System.err.println("Error: " + e); System.exit(1); } } private void run(String mode) throws Exception { DHParameterSpec dhSkipParamSpec; if (mode.equals("GENERATE_DH_PARAMS")) { // Some central authority creates new DH parameters System.err.println ("Creating Diffie-Hellman parameters (takes VERY long) ..."); AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH"); paramGen.init(512); AlgorithmParameters params = paramGen.generateParameters(); dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec (DHParameterSpec.class); } else { // use some pre-generated, default DH parameters System.err.println("Using SKIP Diffie-Hellman parameters"); dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base); } /* * Alice creates her own DH key pair, using the DH parameters from * above */ System.err.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(dhSkipParamSpec); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // Alice executes Phase1 of her version of the DH protocol System.err.println("ALICE: Execute PHASE1 ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Alice encodes her public key, and sends it over to Bob. byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded(); /* * Let's turn over to Bob. Bob has received Alice's public key * in encoded format. * He instantiates a DH public key from the encoded key material. */ KeyFactory bobKeyFac = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec (alicePubKeyEnc); PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec); /* * Bob gets the DH parameters associated with Alice's public key. * He must use the same parameters when he generates his own key * pair. */ DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams(); // Bob creates his own DH key pair System.err.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Bob executes Phase1 of his version of the DH protocol System.err.println("BOB: Execute PHASE1 ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Bob encodes his public key, and sends it over to Alice. byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded(); /* * Alice uses Bob's public key for Phase2 of her version of the DH * protocol. * Before she can do so, she has to instanticate a DH public key * from Bob's encoded key material. */ KeyFactory aliceKeyFac = KeyFactory.getInstance("DH"); x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc); PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec); System.err.println("ALICE: Execute PHASE2 ..."); aliceKeyAgree.doPhase(bobPubKey, true); /* * Bob uses Alice's public key for Phase2 of his version of the DH * protocol. */ System.err.println("BOB: Execute PHASE2 ..."); bobKeyAgree.doPhase(alicePubKey, true); /* * At this stage, both Alice and Bob have completed the DH key * agreement protocol. * Each generates the (same) shared secret. */ byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); int aliceLen = aliceSharedSecret.length; byte[] bobSharedSecret = new byte[aliceLen]; int bobLen; try { // provide output buffer that is too short bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1); } catch (ShortBufferException e) { System.out.println(e.getMessage()); } // provide output buffer of required size bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); if (aliceLen != bobLen) { throw new Exception("Shared secrets have different lengths"); } for (int i=0; i> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } /* * Prints the usage of this test. */ private void usage() { System.err.print("DHKeyAgreement usage: "); System.err.println("[-gen]"); } // The 1024 bit Diffie-Hellman modulus values used by SKIP private static final byte skip1024ModulusBytes[] = { (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58, (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD, (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4, (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B, (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D, (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C, (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C, (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6, (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0, (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B, (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB, (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D, (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD, (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43, (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C, (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C, (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C, (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40, (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C, (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72, (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03, (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29, (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C, (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB, (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B, (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08, (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D, (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C, (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22, (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB, (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55, (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7 }; // The SKIP 1024 bit modulus private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes); // The base used with the SKIP 1024 bit modulus private static final BigInteger skip1024Base = BigInteger.valueOf(2); }
/* * Copyright 1993-1997 Sun Microsystems, Inc. 901 San Antonio Road, * Palo Alto, California, 94303, U.S.A. All Rights Reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. * * CopyrightVersion 1.2 * */ import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import java.security.interfaces.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import com.sun.crypto.provider.SunJCE; /** * This test utility executes the Diffie-Hellman key agreement protocol * between 3 parties: Alice, Bob, and Carol. * * We use the same 1024 bit prime modulus and base generator that are used by * SKIP. */ public class DHKeyAgreement3 { private DHKeyAgreement3() {} public static void main(String argv[]) { try { // Add JCE to the list of providers SunJCE jce = new SunJCE(); Security.addProvider(jce); DHKeyAgreement3 keyAgree = new DHKeyAgreement3(); keyAgree.run(); } catch (Exception e) { System.err.println("Error: " + e); System.exit(1); } } private void run() throws Exception { DHParameterSpec dhSkipParamSpec; System.err.println("Using SKIP Diffie-Hellman parameters"); dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base); // Alice creates her own DH key pair System.err.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(dhSkipParamSpec); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // Bob creates his own DH key pair System.err.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhSkipParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Carol creates her own DH key pair System.err.println("CAROL: Generate DH keypair ..."); KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH"); carolKpairGen.initialize(dhSkipParamSpec); KeyPair carolKpair = carolKpairGen.generateKeyPair(); // Alice initialize System.err.println("ALICE: Initialize ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Bob initialize System.err.println("BOB: Initialize ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Carol initialize System.err.println("CAROL: Initialize ..."); KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH"); carolKeyAgree.init(carolKpair.getPrivate()); // Alice uses Carol's public key Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false); // Bob uses Alice's public key Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); // Carol uses Bob's public key Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false); // Alice uses Carol's result from above aliceKeyAgree.doPhase(cb, true); // Bob uses Alice's result from above bobKeyAgree.doPhase(ac, true); // Carol uses Bob's result from above carolKeyAgree.doPhase(ba, true); // Alice, Bob and Carol compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); int aliceLen = aliceSharedSecret.length; System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); int bobLen = bobSharedSecret.length; System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); int carolLen = carolSharedSecret.length; System.out.println("Carol secret: " + toHexString(carolSharedSecret)); // Compare Alice and Bob if (aliceLen != bobLen) { throw new Exception("Alice and Bob have different lengths"); } for (int i=0; i> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } /* * Prints the usage of this test. */ private void usage() { System.err.print("DHKeyAgreement usage: "); System.err.println("[-gen]"); } // The 1024 bit Diffie-Hellman modulus values used by SKIP private static final byte skip1024ModulusBytes[] = { (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58, (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD, (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4, (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B, (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D, (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C, (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C, (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6, (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0, (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B, (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB, (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D, (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD, (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43, (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C, (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C, (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C, (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40, (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C, (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72, (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03, (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29, (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C, (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB, (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B, (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08, (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D, (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C, (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22, (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB, (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55, (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7 }; // The SKIP 1024 bit modulus private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes); // The base used with the SKIP 1024 bit modulus private static final BigInteger skip1024Base = BigInteger.valueOf(2); }