JavaTM Cryptography Extension (JCE)

Reference Guide

for the JavaTM 2 Platform Standard Edition Development Kit (JDK) 5.0



Introduction


What's New in JCE in the JDK 5.0


Cryptographic Concepts

Encryption and Decryption

Password-Based Encryption

Cipher

Key Agreement

Message Authentication Code


Core Classes

The Cipher Class

The Cipher Stream Classes

The CipherInputStream Class

The CipherOutputStream Class

The KeyGenerator Class

The SecretKeyFactory Class

The SealedObject Class

The KeyAgreement Class

The Mac Class


How to Make Applications "Exempt" from Cryptographic Restrictions


Installing JCE Providers for the JDK 5.0


JCE Keystore


Code Examples

Using Encryption

Using Password-Based Encryption

Using Key Agreement



Appendix A: Standard Names


Appendix B: SunJCE Default Keysizes


Appendix C: SunJCE Keysize Restrictions


Appendix D: Jurisdiction Policy File Format


Appendix E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files


Appendix F: Sample Programs

Diffie-Hellman Key Exchange between 2 Parties

Diffie-Hellman Key Exchange between 3 Parties

Blowfish Example

HMAC-MD5 Example

Introduction

This document is intended as a companion to the JavaTM Cryptography Architecture (JCA) API Specification & Reference. References to chapters not present in this document are to chapters in the JCA Specification.

The JavaTM Cryptography Extension (JCE) provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has been integrated into the Java 2 SDK since the 1.4 release.

JCE is based on the same design principles found elsewhere in the JCA: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture. Providers signed by a trusted entity can be plugged into the JCE framework, and new algorithms can be added seamlessly.

The JCE API covers:

The JDK 5.0 release comes standard with a JCE provider named "SunJCE", which comes pre-installed and registered and which supplies the following cryptographic services:

A Note on Terminology

The JCE within the JDK 5.0 includes two software components:

Throughout this document, the term "JCE" by itself refers to the JCE framework in the JDK 5.0. Whenever the JCE provider supplied with the JDK 5.0 is mentioned, it will be referred to explicitly as the "SunJCE" provider.

What's New in JCE in the JDK 5.0

Here are the differences in JCE between v1.4 and 5.0:

Support for PKCS #11 Based Crypto Provider

In JDK 5.0, a JCA/JCE provider, SunPKCS11 that acts as a generic gateway to the native PKCS#11 API has been implemented. PKCS#11 is the de-facto standard for crypto accelerators and also widely used to access cryptographic smartcards. The administrator/user can configure this provider to talk any PKCS#11 v2.x compliant token.

Here's an example of the configuration file format.

Integration with Solaris Cryptographic Framework

On Solaris 10, the default Java security provider configuration has been changed in JDK 5.0 to include an instance of the SunPKCS11 provider that uses the Solaris Cryptographic Framework. It is the provider with the highest precedence thereby allowing all existing applications to take advantage of the improved performance on Solaris 10. There is no change in behavior on Solaris 8 and Solaris 9 systems.

As a result of this change, many cryptographic operations will execute several times as fast as before on all Solaris 10 systems. On systems with cryptographic hardware acceleration, the performance improvements may be two orders of magnitude.

Support for ECC Algorithm

Prior to JDK 5.0 the JCA/JCE framework did not include support classes for ECC-related crypto algorithms. Users who wanted to use ECC had to depend on a 3rd party library that implemented ECC. However, this did not integrate well with existing JCA/JCE framework.

Starting in JDK 5.0, full support for ECC classes to facilitate providers that support ECC have been included.

The following interfaces have been added:

The following classes have been added:

Added ByteBuffer API Support

Methods that take ByteBuffer arguments have been added to the JCE API and SPI classes that are used to process bulk data. Providers can override the engine* methods if they can process ByteBuffers more efficiently than byte[].

The following JCE methods have been added to support ByteBuffers:

    javax.crypto.Mac.update(ByteBuffer input)
javax.crypto.MacSpi.engineUpdate(ByteBuffer input)
javax.crypto.Cipher.update(ByteBuffer input, ByteBuffer output)
javax.crypto.Cipher.doFinal(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineUpdate(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineDoFinal(ByteBuffer input, ByteBuffer output)
The following JCA methods have been added to support ByteBuffers:
    java.security.MessageDigest.update(ByteBuffer input)
java.security.Signature.update(ByteBuffer data)
java.security.SignatureSpi.engineUpdate(ByteBuffer data)
java.security.MessageDigestSpi.engineUpdate(ByteBuffer input)

Support for RC2ParameterSpec

The RC2 algorithm implementation has been enhanced in JDK 5.0 to support effective key size that is distinct from the length of the input key.

Full support for XML Encryption RSA-OAEP Algorithm

Prior to JDK 5.0, JCE did not define any parameter class for specifying the non-default values used in OAEP and PSS padding as defined in PKCS#1 v2.1 and the RSA-OAEP Key Transport algorithm in the W3C Recommendation for XML Encryption. Therefore, there was no generic way for applications to specify non-default values used in OAEP and PSS padding.

In JDK 5.0, new parameter classes have been added to fully support OAEP padding and the existing PSS parameter class was enhanced with APIs to fully support RSA PSS signature implementations. Also, SunJCE provider has been enhanced to accept OAEPParameterSpec when OAEPPadding is used.

The following classes have been added:

The following methods and fields have been added to java.security.spec.PSSParameterSpec:

    public static final PSSParameterSpec DEFAULT
public PSSParameterSpec(String mdName, String mgfName,
AlgorithmParameterSpec mgfSpec,
int saltLen, int trailerField)
public String getDigestAlgorithm()
public String getMGFAlgorithm()
public AlgorithmParameterSpec getMGFParameters()
public int getTrailerField()

Simplified Retrieval of PKCS8EncodedKeySpec from javax.crypto.EncryptedPrivateKeyInfo

In JDK 5.0, javax.crypto.EncryptedPrivateKeyInfo only has one method, getKeySpec(Cipher) for retrieving the PKCS8EncodedKeySpec from the encrypted data. This limitation requires users to specify a cipher which is initialized with the decryption key and parameters. When users only have the decryption key, they would have to first retrieve the parameters out of this EncryptedPrivateKeyInfo object, get hold of matching Cipher implementation, initialize it, and then call the getKeySpec(Cipher) method.

To make EncyptedPrivateKeyInfo easier to use and to make its API consistent with javax.crypto.SealedObject, the following methods have been added to javax.crypto.EncryptedPrivateKeyInfo:

    getKeySpec(Key decryptKey)
getKeySpec(Key decryptKey, String provider)

Ability to Dynamically Determine Maximum Allowable Key Length

In 1.4.2, the crypto jurisdiction policy files bundled in J2SE limits the maximum key length (and parameter value for some crypto algorithms) that can be used for encryption/decryption. Users who desire unlimited version of crypto jurisdiction files must download them separately.

Also, an exception is thrown when the Cipher instance is initialized with keys (or parameters for certain crypto algorithms) exceeds the maximum values allowed by the crypto jurisdiction files.

In JDK 5.0, the Cipher class has been updated to provide the maximum values for key length and parameters configured in the jurisdiction policy files, so that applications can use a shorter key length when the default (limited strength) jurisdiction policy files are installed.

The following methods have been added to javax.crypto.Cipher:

    public static final int getMaxAllowedKeyLength(String transformation)
throws NoSuchAlgorithmException

public static final AlgorithmParameterSpec
getMaxAllowedParameterSpec(String transformation)
throws NoSuchAlgorithmException;

Support for HmacSHA256, HmacSHA384, HmacSHA512

Support for HmacSHA-256, HmacSHA-384, and HmacSHA-512 algorithms have been added to JDK 5.0.

Support for RSA Encryption to SunJCE Provider

A publicly accessible RSA encryption implementation has been added to the SunJCE provider.

Support for RC2 and ARCFOUR Ciphers to SunJCE Provider

The SunJCE provider now implements the RC2 (RFC 2268) and ARCFOUR (an RC4TM-compatible algorithm) ciphers.

Support for "PBEWithSHA1AndDESede" and "PBEWithSHA1AndRC2_40" Ciphers

Added support for PBEWithSHA1AndDESede and PBEWithSHA1AndRC2_40 ciphers in SunJCE provider.

Support for XML Encryption Padding Algorithm in JCE Block Encryption Ciphers

W3C XML Encryption defines a new padding algorithm, "ISO10126Padding," for block ciphers. See 5.2 Block Encryption Algorithms for more information.

To allow Sun's provider to be used by XML Encryption implementations and JSR 106 providers, we have added support for this padding in JDK 5.0.

Cryptographic 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) derives an encryption key from a password. 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

A Message Authentication Code (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.


Core Classes


How to Make Applications "Exempt" from Cryptographic Restrictions

[Note 1: This section should be ignored by most application developers. It is only for people whose applications may be exported to those few countries whose governments mandate cryptographic restrictions, if it desired that such applications have fewer cryptographic restrictions than those mandated. If you want to skip this section, you can go on to Installing JCE Providers for JDK 5.0.]

[Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

The JCE framework within JDK 5.0 includes an ability to enforce restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different jurisdiction contexts (locations). Any such restrictions are specified in "jurisdiction policy files".

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK 5.0 from Sun Microsystems specify that "strong" but limited cryptography may be used. An "unlimited strength" version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the "strong" version can be imported into those countries whose governments mandate restrictions. The JCE framework will enforce the restrictions specified in the installed jurisdiction policy files.

It is possible that the governments of some or all such countries may allow certain applications to become exempt from some or all cryptographic restrictions. For example, they may consider certain types of applications as "special" and thus exempt. Or they may exempt any application that utilizes an "exemption mechanism," such as key recovery. Applications deemed to be exempt could get access to stronger cryptography than that allowed for non-exempt applications in such countries.

In order for an application to be recognized as "exempt" at runtime, it must meet the following conditions:

Below are sample steps required in order to make an application exempt from some or all cryptographic restrictions. This is a basic outline that includes information about what is required by JCE in order to recognize and treat applications as being exempt. You will need to know the exemption requirements of the particular country or countries in which you would like your application to be able to be run but whose governments require cryptographic restrictions. You will also need to know the requirements of a JCE framework vendor that has a process in place for handling exempt applications. Consult such a vendor for further information. (Note: The SunJCE provider does not supply an implementation of the ExemptionMechanismSpi class.)


Special Code Requirements for Applications that Use Exemption Mechanisms

When an application has a permission policy file associated with it (in the same JAR file) and that permission policy file specifies an exemption mechanism, then when the Cipher getInstance method is called to instantiate a Cipher, the JCE code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCE instantiates an ExemptionMechanism API object associated with the provider's implementation, and then associates the ExemptionMechanism object with the Cipher returned by getInstance.

After instantiating a Cipher, and prior to initializing it (via a call to the Cipher init method), your code must call the following Cipher method:

    public ExemptionMechanism getExemptionMechanism()

This call returns the ExemptionMechanism object associated with the Cipher. You must then initialize the exemption mechanism implementation by calling the following method on the returned ExemptionMechanism:

     public final void init(Key key)

The argument you supply should be the same as the argument of the same types that you will subsequently supply to a Cipher init method.

Once you have initialized the ExemptionMechanism, you can proceed as usual to initialize and use the Cipher.

Permission Policy Files

In order for an application to be recognized at runtime as being "exempt" from some or all cryptographic restrictions, it must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).

Note: The permission policy file bundled with an application must be named cryptoPerms.

The format of a permission entry in a permission policy file that accompanies an exempt application is the same as the format for a jurisdiction policy file downloaded with the JDK 5.0, which is:

permission <crypto permission class name>[ <alg_name>
[[, <exemption mechanism name>][, <maxKeySize>
[, <AlgorithmParameterSpec class name>,
<parameters for constructing an AlgorithmParameterSpec object>]]]];

See Appendix D for more information about the jurisdiction policy file format.

Permission Policy Files for Exempt Applications

Some applications may be allowed to be completely unrestricted. Thus, the permission policy file that accompanies such an application usually just needs to contain the following:

grant {
// There are no restrictions to any algorithms.
permission javax.crypto.CryptoAllPermission;
};

If an application just uses a single algorithm (or several specific algorithms), then the permission policy file could simply mention that algorithm (or algorithms) explicitly, rather than granting CryptoAllPermission. For example, if an application just uses the Blowfish algorithm, the permission policy file doesn't have to grant CryptoAllPermission to all algorithms. It could just specify that there is no cryptographic restriction if the Blowfish algorithm is used. In order to do this, the permission policy file would look like the following:

grant {
permission javax.crypto.CryptoPermission "Blowfish";
};

Permission Policy Files for Applications Exempt Due to Exemption Mechanisms

If an application is considered "exempt" if an exemption mechanism is enforced, then the permission policy file that accompanies the application must specify one or more exemption mechanisms. At runtime, the application will be considered exempt if any of those exemption mechanisms is enforced. Each exemption mechanism must be specified in a permission entry that looks like the following:

    // No algorithm restrictions if specified
// exemption mechanism is enforced.
permission javax.crypto.CryptoPermission *,
"<ExemptionMechanismName>";

where <ExemptionMechanismName> specifies the name of an exemption mechanism. The list of possible exemption mechanism names includes:

  • KeyRecovery

  • KeyEscrow

  • KeyWeakening
As an example, suppose your application is exempt if either key recovery or key escrow is enforced. Then your permission policy file should contain the following:
grant {
// No algorithm restrictions if KeyRecovery is enforced.
permission javax.crypto.CryptoPermission *,
"KeyRecovery";
// No algorithm restrictions if KeyEscrow is enforced.
permission javax.crypto.CryptoPermission *,
"KeyEscrow";
};

Note: Permission entries that specify exemption mechanisms should not also specify maximum key sizes. The allowed key sizes are actually determined from the installed exempt jurisdiction policy files, as described in the next section.

How Bundled Permission Policy Files Affect Cryptographic Permissions

At runtime, when an application instantiates a Cipher (via a call to its getInstance method) and that application has an associated permission policy file, JCE checks to see whether the permission policy file has an entry that applies to the algorithm specified in the getInstance call. If it does, and the entry grants CryptoAllPermission or does not specify that an exemption mechanism must be enforced, it means there is no cryptographic restriction for this particular algorithm.

If the permission policy file has an entry that applies to the algorithm specified in the getInstance call and the entry does specify that an exemption mechanism must be enforced, then the exempt jurisdiction policy file(s) are examined. If the exempt permissions include an entry for the relevant algorithm and exemption mechanism, and that entry is implied by the permissions in the permission policy file bundled with the application, and if there is an implementation of the specified exemption mechanism available from one of the registered providers, then the maximum key size and algorithm parameter values for the Cipher are determined from the exempt permission entry.

If there is no exempt permission entry implied by the relevant entry in the permission policy file bundled with the application, or if there is no implementation of the specified exemption mechanism available from any of the registered providers, then the application is only allowed the standard default cryptographic permissions.


Installing JCE Providers for JDK 5.0

In order to be used, a cryptographic provider must be installed and registered, either statically or dynamically. Cryptographic providers for JCE in JDK 5.0 are installed and configured the same way as all other providers for the JavaTM 2 platform. More information about installing and configuring providers can be found in the Installing Providers section of the JavaTM Cryptography Architecture API Specification & Reference document.

You do not need to register the "SunJCE" provider because it is pre-registered. If you want to use other providers, read the following sections to see how to register them.

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider. In some situations you will also need to set permissions for the provider prior to using it.

Installing the Provider Classes

The first thing you must do is make the provider classes available so that they can be found when requested. Provider classes are shipped as a signed JAR (Java ARchive) file.

There are two possible ways to install the provider classes:

The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:

<java-home>/lib/ext         [Solaris]
<java-home>\lib\ext [Windows]

Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. For example, if you have JDK 5.0 installed on Solaris in a directory named /home/user1/JDK1.5.0, or on Microsoft Windows in a directory named C:\Java DK1.5.0, then you need to install the JAR file in the following directory:

/home/user1/JDK1.5.0/jre/lib/ext    [Solaris]
C:\JDK1.5.0\jre\lib\ext [Windows]

Similarly, if you have the JRE 5.0 installed on Solaris in a directory named /home/user1/jre1.5.0, or on Microsoft Windows in a directory named C:\jre1.5.0, you need to install the JAR file in the following directory:

/home/user1/jre1.5.0/lib/ext         [Solaris]
C:\jre1.5.0\lib\ext [Windows]

For more information, refer to these sections in the "Extension Mechanism Architecture" specification: Installed Extensions and Bundled Extensions.

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file

<java-home>/lib/security/java.security     [Solaris]
<java-home>\lib\security\java.security [Windows]

Here <java-home> refers to the directory where the JRE was installed. For example, if you have JDK 5.0 installed on Solaris in a directory named /home/user1/JDK1.5.0, or on Microsoft Windows in a directory named C:\JDK1.5.0, then you need to edit the following file:

/home/user1/JDK1.5.0/jre/lib/security/java.security  [Solaris]
C:\JDK1.5.0\jre\lib\security\java.security [Windows]

Similarly, if you have the Java 2 Runtime Environment, v 1.4 installed on Solaris in a directory named /home/user1/jre1.5.0, or on Microsoft Windows in a directory named C:\jre1.5.0, then you need to edit this file:

/home/user1/jre1.5.0/lib/security/java.security       [Solaris]
C:\jre1.5.0\lib\security\java.security [Windows]

For each provider, this file should have a statement of the following form:

    security.provider.n=masterClassName
    

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of the provider's "master class". The provider vendor should supply you this name.

JDK 5.0 comes standard with a provider named "SUN", which is automatically configured as a static provider in the java.security properties file, as follows:

security.provider.1=sun.security.provider.Sun

(The "SUN" provider's master class is the Sun class in the sun.security.provider package.)

The JCE provider "SunJCE" and other security-related providers shipped with the Java 2 platform are also automatically configured as static providers.

To utilize another JCE provider, add a line registering the alternate provider, giving it whatever preference order you prefer (and making corresponding adjustments to the other providers' orders, if needed).

Suppose that the master class of a provider you want to register is the CryptoX class in the com.cryptox.provider package, and that you would like to make this provider the second preferred provider. To do so, add the following line to the java.security file below the line for the "SUN" provider, and increment the preference order numbers for all other providers whose numbers were greater than or equal to 2 before your addition:

    security.provider.2=com.cryptox.provider.CryptoX
Note: Providers may also be registered dynamically. To do so, a program can call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by code which is granted the following permission:
java.security.SecurityPermission "insertProvider.{name}"
where {name} is replaced by the actual provider name. For example, if the provider name is "MyJCE" and if your code that dynamically registers this provider is in the MyApp.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:
grant codeBase "file:/localWork/MyApp.jar" {
permission java.security.SecurityPermission
"insertProvider.MyJCE";
};

Setting Provider Permissions

Whenever JCE providers are not installed extensions, permissions must be granted for when applets or applications using JCE are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy configuration file grants all permissions to installed extensions.

The documentation from the vendor of each provider you will be using should include information as to which permissions it requires, and how to grant such permissions. For example, the following permissions may be needed by a provider if it is not an installed extension and a security manager is installed:

For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar file is assumed to be in the /localWork directory.

grant codeBase "file:/localWork/myjce_provider.jar" {
permission java.lang.RuntimePermission "getProtectionDomain";
permission java.security.SecurityPermission
"putProviderProperty.MyJCE";
};

JCE Keystore

The "SunJCE" provider supplies its own implementation of the java.security.KeyStore class in the JDK 5.0. Its implementation employs a much stronger protection of private keys (using password-based encryption with Triple DES) than the keystore implementation supplied by the "SUN" provider in the JDK 5.0 (Note that because the JDK 5.0 is distributed world-wide in binary and source format, it cannot employ any strong encryption mechanisms.)

In order to take advantage of the keystore implementation of the "SunJCE" provider, you specify "JCEKS" as the keystore type.

You may upgrade your keystore of type "JKS" - this is the name of the keystore type implemented by the "SUN" provider in the Java 2 SDK - to a JCE keystore of type "JCEKS" by changing the password of a private-key entry in your keystore.

To apply the cryptographically strong(er) key protection supplied by "SunJCE" to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords:

    keytool -keypasswd -alias signkey -storetype jceks

You may want to change the password back to its old value, using the same command.

See Security Tools for more information about keytool and about keystores and how they are managed.


Code Examples

This section is a short tutorial on how to use some of the major features of the JCE APIs in the JDK 5.0 Complete sample programs that exercise the APIs can be found in Appendix F of this document.

Using Encryption

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 and cleartext1 are identical.

Using Password-Based Encryption

In this example, we prompt the user for a password from which we derive an encryption key.

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.

The following method is an example of how to collect a user password as a char array:

    /**
* Reads user password from given input stream.
*/
public char[] readPasswd(InputStream in) throws IOException {
char[] lineBuffer;
char[] buf;
int i;

buf = lineBuffer = new char[128];

int room = buf.length;
int offset = 0;
int c;

loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;

case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) {
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
} else
break loop;

default:
if (--room < 0) {
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}

if (offset == 0) {
return null;
}

char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');

return ret;
}

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);

// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPasswd" method from above), and convert
// it into a SecretKey object, using a PBE key
// factory.
System.out.print("Enter encryption password: ");
System.out.flush();
pbeKeySpec = new PBEKeySpec(readPasswd(System.in));
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);

Using Key Agreement

Please refer to Appendix F for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties, respectively.


Appendix A: Standard Names

The JCE API requires and utilizes a set of standard names for algorithms, algorithm modes, and padding schemes. This specification establishes the following names as standard names. It supplements the list of standard names defined in Appendix A in the JavaTM Cryptography Architecture API Specification & Reference. Note that algorithm names are treated case-insensitively.

In some cases naming conventions are suggested for forming names that are not explicitly listed, to facilitate name consistency across provider implementations. Such suggestions use items in angle brackets (such as <digest> and <encryption>) as placeholders to be replaced by specific message digest, encryption algorithm, and other names.

Cipher

Algorithm

The following names can be specified as the algorithm component in a transformation when requesting an instance of Cipher:

  • AES: Advanced Encryption Standard as specified by NIST in a draft FIPS. Based on the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits.

  • ARCFOUR/RC4: A stream cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt.

  • Blowfish: The block cipher designed by Bruce Schneier.

  • DES: The Digital Encryption Standard as described in FIPS PUB 46-2.

  • DESede: Triple DES Encryption (DES-EDE).

  • ECIES (Elliptic Curve Integrated Encryption Scheme)

  • PBEWith<digest>And<encryption> or PBEWith<prf>And<encryption>: The password-based encryption algorithm (PKCS #5), using the specified message digest (<digest>) or pseudo-random function (<prf>) and encryption algorithm (<encryption>). Examples:

    • PBEWithMD5AndDES: The password-based encryption algorithm as defined in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993. Note that this algorithm implies CBC as the cipher mode and PKCS5Padding as the padding scheme and cannot be used with any other cipher modes or padding schemes.

    • PBEWithHmacSHA1AndDESede: The password-based encryption algorithm as defined in: RSA Laboratories, "PKCS #5: Password-Based Cryptography Standard," version 2.0, March 1999.

  • RC2, RC4, and RC5: Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.

  • RSA: The RSA encryption algorithm as defined in PKCS #1.

Mode

The following names can be specified as the mode component in a transformation when requesting an instance of Cipher:

  • NONE: No mode.

  • CBC: Cipher Block Chaining Mode, as defined in FIPS PUB 81.

  • CFB: Cipher Feedback Mode, as defined in FIPS PUB 81.

  • 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.

  • OFB: Output Feedback Mode, as defined in FIPS PUB 81.

  • PCBC: Propagating Cipher Block Chaining, as defined by Kerberos V4.

Padding

The following names can be specified as the padding component in a transformation when requesting an instance of Cipher:

  • ISO10126Padding. This padding for block ciphers is described in 5.2 Block Encryption Algorithms in the W3C's "XML Encryption Syntax and Processing" document.

  • NoPadding: No padding.

  • OAEPWith<digest>And<mgf>Padding: Optimal Asymmetric Encryption Padding scheme defined in PKCS #1, where <digest> should be replaced by the message digest and <mgf> by the mask generation function. Example: OAEPWithMD5AndMGF1Padding.

  • PKCS5Padding: The padding scheme described in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, November 1993.

  • SSL3Padding: The padding scheme defined in the SSL Protocol Version 3.0, November 18, 1996, section 5.2.3.2 (CBC block cipher):
        block-ciphered struct {
    opaque content[SSLCompressed.length];
    opaque MAC[CipherSpec.hash_size];
    uint8 padding[GenericBlockCipher.padding_length];
    uint8 padding_length;
    } GenericBlockCipher;

    The size of an instance of a GenericBlockCipher must be a multiple of the block cipher's block length.

    The padding length, which is always present, contributes to the padding, which implies that if:

        sizeof(content) + sizeof(MAC) % block_length = 0,
    padding has to be (block_length - 1) bytes long, because of the existence of padding_length.

    This make the padding scheme similar (but not quite) to PKCS5Padding, where the padding length is encoded in the padding (and ranges from 1 to block_length). With the SSL scheme, the sizeof(padding) is encoded in the always present padding_length and therefore ranges from 0 to block_length-1.

    Note that this padding mechanism is not supported by the "SunJCE" provider.

KeyAgreement

The following algorithm names can be specified when requesting an instance of KeyAgreement:

KeyGenerator

The following algorithm names can be specified when requesting an instance of KeyGenerator:

KeyPairGenerator

The following algorithm names can be specified when requesting an instance of KeyPairGenerator:

SecretKeyFactory

The following algorithm names can be specified when requesting an instance of SecretKeyFactory:

KeyFactory

The following algorithm names can be specified when requesting an instance of KeyFactory:

AlgorithmParameterGenerator

The following algorithm names can be specified when requesting an instance of AlgorithmParameterGenerator:

AlgorithmParameters

The following algorithm names can be specified when requesting an instance of AlgorithmParameters:

MAC

The following algorithm names can be specified when requesting an instance of Mac:

Keystore Types

The following types can be specified when requesting an instance of KeyStore:

Exemption Mechanisms

The following exemption mechanism names can be specified in the permission policy file that accompanies an application considered "exempt" from cryptographic restrictions:


Appendix B: SunJCE Default Keysizes

The SunJCE provider uses the following default keysizes:


Appendix C: SunJCE Keysize Restrictions

The SunJCE provider enforces the following restrictions on the keysize passed to the initialization methods of the following classes:


Appendix D: Jurisdiction Policy File Format

JCE represents its jurisdiction policy files as J2SE-style policy files with corresponding permission statements. As described in Default Policy Implementation and Policy File Syntax, a J2SE policy file specifies what permissions are allowed for code from specified code sources. A permission represents access to a system resource. In the case of JCE, the "resources" are cryptography algorithms, and code sources do not need to be specified, because the cryptographic restrictions apply to all code.

A jurisdiction policy file consists of a very basic "grant entry" containing one or more "permission entries."

grant {
<permission entries>;
};

The format of a permission entry in a jurisdiction policy file is:

permission <crypto permission class name>[ <alg_name>
[[, <exemption mechanism name>][, <maxKeySize>
[, <AlgorithmParameterSpec class name>,
<parameters for constructing an
AlgorithmParameterSpec object>]]]];

A sample jurisdiction policy file that includes restricting the "Blowfish" algorithm to maximum key sizes of 64 bits is:

grant {
permission javax.crypto.CryptoPermission "Blowfish", 64;
. . .;
};

A permission entry must begin with the word permission. The <crypto permission class name> in the template above would actually be a specific permission class name, such as javax.crypto.CryptoPermission. A crypto permission class reflects the ability of an application/applet to use certain algorithms with certain key sizes in certain environments. There are two crypto permission classes: CryptoPermission and CryptoAllPermission. The special CryptoAllPermission class implies all cryptography-related permissions, that is, it specifies that there are no cryptography-related restrictions.

The <alg_name>, when utilized, is a quoted string specifying the standard name (see Appendix A) of a cryptography algorithm, such as "DES" or "RSA".

The <exemption mechanism name>, when specified, is a quoted string indicating an exemption mechanism which, if enforced, enables a reduction in cryptographic restrictions. Exemption mechanism names that can be used include "KeyRecovery" "KeyEscrow", and "KeyWeakening".

<maxKeySize> is an integer specifying the maximum key size (in bits) allowed for the specified algorithm.

For some algorithms it may not be sufficient to specify the algorithm strength in terms of just a key size. For example, in the case of the "RC5" algorithm, the number of rounds must also be considered. For algorithms whose strength needs to be expressed as more than a key size, the permission entry should also specify an AlgorithmParameterSpec class name (such as javax.crypto.spec.RC5ParameterSpec) and a list of parameters for constructing the specified AlgorithmParameterSpec object.

Items that appear in a permission entry must appear in the specified order. An entry is terminated with a semicolon.

Case is unimportant for the identifiers (grant, permission) but is significant for the <crypto permission class name> or for any string that is passed in as a value.

Note: An "*" can be used as a wildcard for any permission entry option. For example, an "*" (without the quotes) for an <alg_name> option means "all algorithms."


Appendix E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Due to import control restrictions, the jurisdiction policy files shipped with JDK 5.0 allow "strong" but limited cryptography to be used. Here are the maximum key sizes allowed by this "strong" version of the jurisdiction policy files:

Algorithm

Maximum Key Size

DES

64

DESede

*

RC2

128

RC4

128

RC5

128

RSA

2048

* (all others)

128


Appendix F: Sample Programs


Copyright ¨ 1996-2004 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@java.sun.com.

Java Software
Last modified: 29 Jan 2004