Beta Draft: 2017-03-27

5 Java Cryptography Architecture (JCA) Reference Guide

The Java Cryptography Architecture (JCA) is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashes), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few.

Introduction to Java Cryptography Architecture

The Java platform strongly emphasizes security, including language safety, cryptography, public key infrastructure, authentication, secure communication, and access control.

The JCA is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashes), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few. These APIs allow developers to easily integrate security into their application code. The architecture was designed around the following principles:

  • Implementation independence: Applications do not need to implement security algorithms. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.

  • Implementation interoperability: Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.

  • Algorithm extensibility: The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.

Other cryptographic communication libraries available in the JDK use the JCA provider architecture, but are described elsewhere. The Java Secure Socket Extension (JSSE) Reference Guide provides access to Secure Socket Layer (SSL), Transport Layer Security (TLS), and Datagram Transport Layer Security (DTLS) implementations. The JAAS and Java GSS-API Tutorial (via Kerberos) APIs, and the Java SASL API Programming and Deployment Guide can also be used for securely exchanging messages between communicating applications.

Notes on Terminology

  • Prior to JDK 1.4, the JCE was an unbundled product, and as such, the JCA and JCE were regularly referred to as separate, distinct components. As JCE is now bundled in the JDK, the distinction is becoming less apparent. Since the JCE uses the same architecture as the JCA, the JCE should be more properly thought of as a part of the JCA.

  • The JCA within the JDK includes two software components:

    1. the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as java.security, javax.crypto, javax.crypto.spec, and javax.crypto.interfaces.
    2. the actual providers such as Sun, SunRsaSign, SunJCE, which contain the actual cryptographic implementations.

    Whenever a specific JCA provider is mentioned, it will be referred to explicitly by the provider's name.

WARNING:

The JCA makes it easy to incorporate security features into your application. However, this document does not cover the theory of security/cryptography beyond an elementary introduction to concepts necessary to discuss the APIs. This document also does not cover the strengths/weaknesses of specific algorithms, not does it cover protocol design. Cryptography is an advanced topic and one should consult a solid, preferably recent, reference in order to make best use of these tools.

You should always understand what you are doing and why: DO NOT simply copy random code and expect it to fully solve your usage scenario. Many applications have been deployed that contain significant security or performance problems because the wrong tool or algorithm was selected.

Who Should Read This Document

Programmers that only need to use the Java Security API to access existing cryptography algorithms and other services do not need to read this document.

This document is intended for experienced programmers wishing to create their own provider packages supplying cryptographic service implementations. It documents what you need to do in order to integrate your provider into Java so that your algorithms and other services can be found when Java Security API clients request them.

JCA Design Principles

The JCA design principles are based on implementation independence and interoperability, algorithm independence and extensibility.

The JCA was designed around these principles:

  • Implementation independence and interoperability
  • Algorithm independence and extensibility

Implementation independence and algorithm independence are complementary; you can use cryptographic services, such as digital signatures and message digests, without worrying about the implementation details or even the algorithms that form the basis for these concepts. While complete algorithm-independence is not possible, the JCA provides standardized, algorithm-specific APIs. When implementation-independence is not desirable, the JCA lets developers indicate a specific implementation.

Algorithm independence is achieved by defining types of cryptographic "engines" (services), and defining classes that provide the functionality of these cryptographic engines. These classes are called engine classes, and examples are the MessageDigest Class, Signature Class, KeyFactory Class, KeyPairGenerator Class, and Cipher Class.

Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Providers (used interchangeably with "provider" in this document) refers to a package or set of packages that implement one or more cryptographic services, such as digital signature algorithms, message digest algorithms, and key conversion services. A program may simply request a particular type of object (such as a Signature object) implementing a particular service (such as the DSA signature algorithm) and get an implementation from one of the installed providers. If desired, a program may instead request an implementation from a specific provider. Providers may be updated transparently to the application, for example when faster or more secure versions are available.

Implementation interoperability means that various implementations can work with each other, use each other's keys, or verify each other's signatures. This would mean, for example, that for the same algorithms, a key generated by one provider would be usable by another, and a signature generated by one provider would be verifiable by another.

Algorithm extensibility means that new algorithms that fit in one of the supported engine classes can be added easily.

Provider Architecture

Providers contain a package (or a set of packages) that supply concrete implementations for the advertised cryptographic algorithms.

Cryptographic Service Providers

java.security.Provider is the base class for all security providers. Each CSP contains an instance of this class which contains the provider's name and lists all of the security services/algorithms it implements.

When an instance of a particular algorithm is needed, the JCA framework consults the provider's database, and if a suitable match is found, the instance is created.

Providers contain a package (or a set of packages) that supply concrete implementations for the advertised cryptographic algorithms. Each JDK installation has one or more providers installed and configured by default. Additional providers may be added statically or dynamically. Clients may configure their runtime environment to specify the provider preference order. The preference order is the order in which providers are searched for requested services when no specific provider is requested.

To use the JCA, an application simply requests a particular type of object (such as a MessageDigest) and a particular algorithm or service (such as the "MD5" algorithm), and gets an implementation from one of the installed providers. Alternatively, the program can request the objects from a specific provider. Each provider has a name used to refer to it.

    md = MessageDigest.getInstance("MD5");
    md = MessageDigest.getInstance("MD5", "ProviderC");

The following figure illustrates requesting an "MD5" message digest implementation. The figure show three different providers that implement various message digest algorithms ("SHA-1", "MD5", "SHA-256", and "SHA-512"). The providers are ordered by preference from left to right (1-3). In the first illustration, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In the second figure, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from ProviderC is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.

Figure 5-1 MD5 Message Digest Implementation or Options for Requesting an MD5 Message Digest Implementation


Description of Figure 5-1 follows
Description of "Figure 5-1 MD5 Message Digest Implementation or Options for Requesting an MD5 Message Digest Implementation"

Cryptographic implementations in the JDK are distributed via several different providers (Sun, SunJSSE, SunJCE, SunRsaSign) primarily for historical reasons, but to a lesser extent by the type of functionality and algorithms they provide. Other Java runtime environments may not necessarily contain these Sun providers, so applications should not request an provider-specific implementation unless it is known that a particular provider will be available.

The JCA offers a set of APIs that allow users to query which providers are installed and what services they support.

This architecture also makes it easy for end-users to add additional providers. Many third party provider implementations are already available. See Provider .

How Providers Are Actually Implemented

Algorithm independence is achieved by defining a generic high-level Application Programming Interface (API) that all applications use to access a service type. Implementation independence is achieved by having all provider implementations conform to well-defined interfaces. Instances of engine classes are thus "backed" by implementation classes which have the same method signatures. Application calls are routed through the engine class and are delivered to the underlying backing implementation. The implementation handles the request and return the proper results.

The application API methods in each engine class are routed to the provider's implementations through classes that implement the corresponding Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class which defines the methods that each cryptographic service provider's algorithm must implement. The name of each SPI class is the same as that of the corresponding engine class, followed by Spi. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual provider implementation is supplied in a subclass of SignatureSpi. Applications call the engine class' API methods, which in turn call the SPI methods in the actual implementation.

Each SPI class is abstract. To supply the implementation of a particular type of service for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

For each engine class in the API, implementation instances are requested and instantiated by calling the getInstance() factory method in the engine class. A factory method is a static method that returns an instance of a class. The engine classes use the framework provider selection mechanism described above to obtain the actual backing implementation (SPI), and then creates the actual engine object. Each instance of the engine class encapsulates (as a private field) the instance of the corresponding SPI class, known as the SPI object. All API methods of an API object are declared final and their implementations invoke the corresponding SPI methods of the encapsulated SPI object.

To make this clearer, review Example 5-1 and Figure 5-2:

Example 5-1 Sample Code for Getting an Instance of an Engine Class

    import javax.crypto.*;

    Cipher c = Cipher.getInstance("AES");
    c.init(ENCRYPT_MODE, key);

Figure 5-2 Application Retrieves “AES” Cipher Instance

Description of Figure 5-2 follows
Description of "Figure 5-2 Application Retrieves “AES” Cipher Instance"

Here an application wants an "AES" javax.crypto.Cipher instance, and doesn't care which provider is used. The application calls the getInstance() factory methods of the Cipher engine class, which in turn asks the JCA framework to find the first provider instance that supports "AES". The framework consults each installed provider, and obtains the provider's instance of the Provider class. (Recall that the Provider class is a database of available algorithms.) The framework searches each provider, finally finding a suitable entry in CSP3. This database entry points to the implementation class com.foo.AESCipher which extends CipherSpi, and is thus suitable for use by the Cipher engine class. An instance of com.foo.AESCipher is created, and is encapsulated in a newly-created instance of javax.crypto.Cipher, which is returned to the application. When the application now does the init() operation on the Cipher instance, the Cipher engine class routes the request into the corresponding engineInit() backing method in the com.foo.AESCipher class.

Java Cryptography Architecture Standard Algorithm Name Documentation lists the Standard Names defined for the Java environment. Other third-party providers may define their own implementations of these services, or even additional services.

Key Management

A database called a "keystore" can be used to manage a repository of keys and certificates. Keystores are available to applications that need data for authentication, encryption, or signing purposes.

Applications can access a keystore via an implementation of the KeyStore class, which is in the java.security package. As of JDK 9, the default keystore type (format) is "pkcs12" which is based on the RSA PKCS12 Personal Information Exchange Syntax Standard. Previously, the default keystore type was "jks" which is a proprietary format. Other keystore formats are available, such as "jceks" which is an alternate proprietary keystore format with stronger encryption than "jks", and "pkcs11", which is based on the RSA PKCS11 Standard and supports access to cryptographic tokens such as hardware security modules and smartcards.

Applications can choose different keystore implementations from different providers, using the same provider mechanism described above.

Keystore Location

The user keystore is by default stored in a file named .keystore in the user's home directory, as determined by the "user.home" system property. On Solaris systems "user.home" defaults to the user's home directory. On Win32 systems, given user name uName, "user.home" defaults to:

  • C:\Winnt\Profiles\uName on multi-user Windows NT systems
  • C:\Windows\Profiles\uName on multi-user Windows 95/98/2000 systems
  • C:\Windows on single-user Windows 95/98/2000 systems

Of course, keystore files can be located as desired. In some environments, it may make sense for multiple keystores to exist. For example, one keystore might hold a user's private keys, and another might hold certificates used to establish trust relationships.

In addition to the user's keystore, the JDK also maintains a system-wide keystore which is used to store trusted certificates from a variety of Certificate Authorities (CA's). These CA certificates can be used to help make trust decisions. For example, in SSL/TLS/DTLS when the SunJSSE provider is presented with certificates from a remote peer, the default trustmanager will consult the:

  • Solaris, Linux, or macOS: <java-home>/lib/ext/cacerts
  • Windows: <java-home>\lib\ext\cacerts

file to determine if the connection is to be trusted. Instead of using the system-wide cacerts keystore, applications can set up and use their own keystores, or even use the user keystore described above.

Keystore Implementation

The KeyStore class supplies well-defined interfaces to access and modify the information in a keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore.

Currently, there are two command-line tools that make use of KeyStore: keytool and jarsigner, and also a GUI-based tool named policytool. It is also used by the Policy reference implementation when it processes policy files specifying the permissions (allowed accesses to system resources) to be granted to code from various sources. Since KeyStore is publicly available, JDK users can write additional security applications that use it.

Applications can choose different types of keystore implementations from different providers, using the getInstance factory method in the KeyStore class. A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible.

The default keystore implementation is "pkcs12". This is a cross platform keystore based on the RSA PKCS12 Personal Information Exchange Syntax Standard. This standard is primarily meant for storing or transporting a user's private keys, certificates, and miscellaneous secrets. Arbitrary attributes can be associated with individual entries in a PKCS12 keystore.

    keystore.type=pkcs12

To have tools and other applications use a different default keystore implementation, you can change that line to specify a default type. If you have a provider package that supplies a keystore implementation for a keystore type called "jceks", change the line to:

    keystore.type=jceks

Some applications, such as keytool, also let you override the default keystore type (via the -storetype command-line parameter).

There are three other types of keystores that come with the JDK implementation.

  1. "jceks" is an alternate proprietary keystore format to "jks" that uses much stronger encryption in the form of Password-Based Encryption with Triple-DES.

    The Sun "jceks" implementation can parse and convert a "jks" keystore file to the "jceks" format. You may upgrade your keystore of type "jks" to a keystore of type "jceks" by changing the password of a private-key entry in your keystore and specifying "-storetype jceks" as the keystore type. To apply the cryptographically strong(er) key protection supplied 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 -keypass -alias signkey -storetype jceks
    
    See keytool in the Java Platform, Standard Edition Tools Reference for Oracle JDK .
  2. "jks" is another option. It implements the keystore as a file, utilizing a proprietary keystore type (format). It protects each private key with its own individual password, and also protects the integrity of the entire keystore with a (possibly different) password.
  3. "dks" is a domain keystore. It is a collection of keystores presented as a single logical keystore. The keystores that comprise a given domain are specified by configuration data whose syntax is described in DomainLoadStoreParameter.

Keystore implementations are provider-based. Developers interested in writing their own KeyStore implementations should consult Provider Architecture.

Engine Classes and Corresponding Service Provider Interface Classes

An engine class defines a cryptographic service in an abstract fashion (without a concrete implementation). A cryptographic service is always associated with a particular algorithm or type.

The engines provide either of the following:

  • Cryptographic operations (encryption, digital signatures, message digests, etc.)
  • Generators or converters of cryptographic material (keys and algorithm parameters)
  • Objects (keystores or certificates) that encapsulate the cryptographic data and can be used at higher layers of abstraction.

cryptographic service either provides cryptographic operations (like those for digital signatures or message digests, ciphers or key agreement protocols); generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations; or generates data objects (keystores or certificates) that encapsulate cryptographic keys (which can be used in a cryptographic operation) in a secure fashion.

For example, here are four engine classes:

  • Signature class provides access to the functionality of a digital signature algorithm.
  • A DSA KeyFactory class supplies a DSA private or public key (from its encoding or transparent specification) in a format usable by the initSign or initVerify methods, respectively, of a DSA Signature object.
  • Cipher class provides access to the functionality of an encryption algorithm (such as DES)
  • KeyAgreement class provides access to the functionality of a key agreement protocol (such as Diffie-Hellman)

The Java Cryptography Architecture encompasses the classes comprising the Security package that relate to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations. The JDK defines the following engine classes:

  • MessageDigest - used to calculate the message digest (hash) of specified data.
  • Signature - used to sign data and verify digital signatures.
  • KeyPairGenerator - used to generate a pair of public and private keys suitable for a specified algorithm.
  • KeyFactory - used to convert opaque cryptographic keys of type Key into key specifications (transparent representations of the underlying key material), and vice versa.
  • KeyStore - used to create and manage a keystore. A keystore is a database of keys. Private keys in a keystore have a certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.
  • CertificateFactory - used to create public key certificates and Certificate Revocation Lists (CRLs).
  • AlgorithmParameters - used to manage the parameters for a particular algorithm, including parameter encoding and decoding.
  • AlgorithmParameterGenerator - used to generate a set of parameters suitable for a specified algorithm.
  • SecureRandom - used to generate random or pseudo-random numbers.
  • Cipher - used to encrypt or decrypt some specified data.
  • KeyAgreement - used to execute a key agreement (key exchange) protocol between 2 or more parties.
  • KeyGenerator - used to generate a secret (symmetric) key suitable for a specified algorithm.
  • Mac: used to compute the message authentication code of some specified data.
  • SecretKeyFactory - used to convert opaque cryptographic keys of type SecretKey into key specifications (transparent representations of the underlying key material), and vice versa.
  • CertPathBuilder - used to create public key certificates and Certificate Revocation Lists (CRLs).
  • CertPathValidator - used to validate certificate chains.
  • CertStore - used to retrieve Certificates and CRLs from a repository.
  • ExemptionMechanism - used to provide the functionality of an exemption mechanism such as key recovery, key weakening, key escrow, or any other (custom) exemption mechanism. Applications or applets that use an exemption mechanism may be granted stronger encryption capabilities than those which don't. However, please note that cryptographic restrictions are no longer required for most countries, and thus exemption mechanisms may only be useful in those few countries whose governments mandate restrictions.

Note:

A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).

An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines Application Programming Interface (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi subclass (see next paragraph) would be that for a specific kind of signature algorithm, such as SHA1 with DSA, SHA1 with RSA, or MD5 with RSA.

The application interfaces supplied by an engine class are implemented in terms of a Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class, which defines the Service Provider Interface methods that cryptographic service providers must implement.

An instance of an engine class, the "API object", encapsulates (as a private field) an instance of the corresponding SPI class, the "SPI object". All API methods of an API object are declared "final", and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the getInstance factory method of the engine class.

The name of each SPI class is the same as that of the corresponding engine class, followed by "Spi". For example, the SPI class corresponding to the Signature engine class is the SignatureSpi class.

Each SPI class is abstract. To supply the implementation of a particular type of service and for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

Another example of an engine class is the MessageDigest class, which provides access to a message digest algorithm. Its implementations, in MessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA-1, MD5, or MD2.

As a final example, the KeyFactory engine class supports the conversion from opaque keys to transparent key specifications, and vice versa. See Key Specification Interfaces and Classes Required by Key Factories. The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, e.g., DSA public and private keys.

Note:

A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).

Core Classes and Interfaces

The list of core classes and interfaces provided in the JCA.

  • Provider and Security
  • SecureRandom , MessageDigest , Signature , Cipher , Mac , KeyFactory , SecretKeyFactory , KeyPairGenerator , KeyGenerator , KeyAgreement , AlgorithmParameter , AlgorithmParameterGenerator , KeyStore , CertificateFactory , and engine
  • Key Interface, KeyPair
  • AlgorithmParameterSpec Interface, AlgorithmParameters , AlgorithmParameterGenerator , and algorithm parameter specification interfaces and classes in the java.security.spec and javax.crypto.spec packages.
  • KeySpec Interface, EncodedKeySpec , PKCS8EncodedKeySpec , and X509EncodedKeySpec .
  • SecretKeyFactory , KeyFactory , KeyPairGenerator , KeyGenerator , KeyAgreement , and KeyStore .

Note:

See CertPathBuilder , CertPathValidator , and CertStore engine classes in the Java PKI Programmers Guide.

The complete reference documentation for the relevant Security API packages can be found in the package summaries:

The Provider Class

The Provider class is the interface to such a package or set of packages.

The term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) refers to a package or set of packages that supply a concrete implementation of a subset of the JDK Security API cryptography features. The Provider class is the interface to such a package or set of packages. It has methods for accessing the provider name, version number, and other information. Please note that in addition to registering implementations of cryptographic services, the Provider class can also be used to register implementations of other security services that might get defined as part of the JDK Security API or one of its extensions.

To supply implementations of cryptographic services, an entity (e.g., a development group) writes the implementation code and creates a subclass of the Provider class. The constructor of the Provider subclass sets the values of various properties; the JDK Security API uses these values to look up the services that the provider implements. In other words, the subclass specifies the names of the classes implementing the services.

There are several types of services that can be implemented by provider packages; See Engine Classes and Corresponding Service Provider Interface Classes.

The different implementations may have different characteristics. Some may be software-based, while others may be hardware-based. Some may be platform-independent, while others may be platform-specific. Some provider source code may be available for review and evaluation, while some may not. The JCA lets both end-users and developers decide what their needs are.

You can find information about how end-users install the cryptography implementations that fit their needs, and how developers request the implementations that fit theirs.

Note:

To implement a provider, see Steps to Implement and Integrate a Provider.

How Provider Implementations Are Requested and Supplied

Sample code about calling the getInstance methods on the engine class to request a provider.

For each Engine Classes and Corresponding Service Provider Interface Classes in the API, a implementation instance is requested and instantiated by calling one of the getInstance methods on the engine class, specifying the name of the desired algorithm and, optionally, the name of the provider (or the Provider class) whose implementation is desired.

static EngineClassName getInstance(String algorithm)
    throws NoSuchAlgorithmException

static EngineClassName getInstance(String algorithm, String provider)
    throws NoSuchAlgorithmException, NoSuchProviderException

static EngineClassName getInstance(String algorithm, Provider provider)
    throws NoSuchAlgorithmException

where

EngineClassName

is the desired engine type (MessageDigest/Cipher/etc). For example:

    MessageDigest md = MessageDigest.getInstance("MD5");
    KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");

return an instance of the "MD5" MessageDigest and "DH" KeyAgreement objects, respectively.

Appendix A: Standard Names contains the list of names that have been standardized for use with the Java environment. Some providers may choose to also include alias names that also refer to the same algorithm. For example, the "SHA-1" algorithm might be referred to as "SHA1". Applications should use standard names instead of an alias, as not all providers may alias algorithm names in the same way.

Note:

The algorithm name is not case-sensitive. For example, all the following calls are equivalent:
MessageDigest.getInstance("SHA-1")
MessageDigest.getInstance("sha-1")
MessageDigest.getInstance("sHa-1")

If no provider is specified, getInstance searches the registered providers for an implementation of the requested cryptographic service associated with the named algorithm. In any given Java Virtual Machine (JVM), providers are Installing Providers in a given preference order, the order in which the provider list is searched if a specific provider is not requested. For example, suppose there are two providers installed in a JVM, PROVIDER_1 and PROVIDER_2. Assume that:

  • PROVIDER_1 implements SHA1withDSA, SHA-1, MD5, DES, and DES3. PROVIDER_1 has preference order 1 (the highest priority).
  • PROVIDER_2 implements SHA1withDSA, MD5withRSA, MD2withRSA, MD2, MD5, RC4, RC5, DES, and RSA. PROVIDER_2 has preference order 2.

Now let's look at three scenarios:

  1. If we are looking for an MD5 implementation. Both providers supply such an implementation. The PROVIDER_1 implementation is returned since PROVIDER_1 has the highest priority and is searched first.
  2. If we are looking for an MD5withRSA signature algorithm, PROVIDER_1 is first searched for it. No implementation is found, so PROVIDER_2 is searched. Since an implementation is found, it is returned.
  3. Suppose we are looking for a SHA1withRSA signature algorithm. Since no installed provider implements it, a NoSuchAlgorithmException is thrown.

The getInstance methods that include a provider argument are for developers who want to specify which provider they want an algorithm from. A federal agency, for example, will want to use a provider implementation that has received federal certification. Let's assume that the SHA1withDSA implementation from PROVIDER_1 has not received such certification, while the DSA implementation of PROVIDER_2 has received it.

A federal agency program would then have the following call, specifying PROVIDER_2 since it has the certified implementation:

Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");

In this case, if PROVIDER_2 was not installed, a NoSuchProviderException would be thrown, even if another installed provider implements the algorithm requested.

A program also has the option of getting a list of all the installed providers (using the getProviders method in The Security Class class) and choosing one from the list.

Note:

General purpose applications SHOULD NOT request cryptographic services from specific providers. Otherwise, applications are tied to specific providers which may not be available on other Java implementations. They also might not be able to take advantage of available optimized providers (for example hardware accelerators via PKCS11 or native OS implementations such as Microsoft's MSCAPI) that have a higher preference order than the specific requested provider.

Installing Providers

In order to be used, a cryptographic provider must first be installed, then registered either statically or dynamically. There are a variety of Sun providers shipped with this release (SUN, SunJCE, SunJSSE, SunRsaSign, etc.) that are already installed and registered. The following sections describe how to install and register additional providers.

Installing the Provider Classes

Procedure to install provider classes.

There are two possible ways to install the provider classes:
  1. Optional: On the normal Java classpath Place a zip or JAR file containing the classes anywhere in your classpath. Some algorithms types (Ciphers) require the provider be a signed Jar file.
  2. Optional: As an Installed/Bundled Extension The provider will be considered an installed extension if it is placed in the standard extension directory. In the JDK, that would be located in:
    • Solaris, Linux, or macOS : <java-home>/lib/ext
    • Windows: <java-home>\lib\ext
    Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the Java Runtime Environment (JRE) or the jre directory in the Java JDK software. For example, if you have JDK 6 installed on Solaris in a directory named /home/user1/JDK1.6.0, or on Microsoft Windows in a directory named C:\Java\JDK1.6.0, then you need to install the JAR file in the following directory:
    • Solaris, Linux, or macOS : /home/user1/JDK1.6.0/jre/lib/ext
    • Windows: C:\JDK1.6.0\jre\lib\ext

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

    • Solaris, Linux, or macOS: /home/user1/jre1.6.0/lib/ext
    • Windows: C:\jre1.6.0\lib\ext

Register the Provider

A provider can be registered either statically or dynamically.

The next step is to add the provider to your list of registered providers. Providers can be registered statically by editing a security properties configuration file before running a Java application, or dynamically by calling a method at runtime. To prevent the installation of rogue providers being added to the runtime environment, applications attempting to dynamically register a provider must possess the appropriate runtime privilege.

Register a Provider Statically

Providers can be registered statically by editing a security properties configuration file before running a Java application

The security properties configuration file is located in the following location:

  • Solaris, Linux, or macOS: <java-home>/conf/security/java.security
  • Windows: <java-home>\conf\security\java.security

For each registered 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 provider's master class. The provider's documentation will specify its master class. This class is always a subclass of the Provider class. The subclass constructor sets the values of various properties that are required for the Java Cryptography API to look up the algorithms or other facilities the provider implements.

The JDK comes standard with automatically installed and configured providers such as "SUN" and "SunJCE". The "SUN" provider's master class is the SUN class in the sun.security.provider package, and the corresponding java.security file entry is as follows:

    security.provider.5=sun.security.provider.Sun

To utilize another JCA provider, add a line referencing the alternate provider, specify the preference order ( making corresponding adjustments to the other providers' orders, if needed).

Suppose that the master class of CompanyX's provider is com.companyx.provider.ProviderX, and that you would like to configure this provider as the eighth most-preferred. To do so, you would add the following line to the java.security file:

    security.provider.8=com.companyx.provider.ProviderX
Register a Provider Dynamically

To register providers dynamically, applications call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent across VM instances, and can only be done by "trusted" programs with the appropriate privilege. See Security.

Setting the Provider Permissions

Examples to set permissions in the providers that are not installed as an extension. Permissions do not need to be granted to providers that are installed as extensions.

Whenever encryption providers are used (that is, those that supply implementations of Cipher, KeyAgreement, KeyGenerator, Mac, or SecretKeyFactory), and the provider is not an installed extension Permissions in the Java Development Kit (JDK) may need to be granted for when applets or applications using JCA 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 Default Policy Implementation and Policy File Syntax grants all permissions to installed extensions (that is, installed in the Installing the Provider Classes).

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:

  • java.lang.RuntimePermission "getProtectionDomain" to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
  • java.security.SecurityPermission "putProviderProperty.{name}" to set provider properties, where {name} is replaced by the actual provider name.

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";
     };

Provider Class Methods

Each Provider class instance has a (currently case-sensitive) name, a version number, and a string description of the provider and its services.

You can query the Provider instance for this information by calling the following methods:

public String getName()
public double getVersion()
public String getInfo()

The Security Class

The Security class manages installed providers and security-wide properties.

It only contains static methods and is never instantiated. The methods for adding or removing providers, and for setting Security properties, can only be executed by a trusted program. Currently, a "trusted program" is either

  • A local application not running under a security manager, or
  • An applet or application with permission to execute the specified method (see below).

The determination that code is considered trusted to perform an attempted action (such as adding a provider) requires that the applet is granted the proper permission(s) for that particular action. The policy configuration file(s) for a JDK installation specify what permissions (which types of system resource accesses) are allowed by code from specified code sources. (See below and the Default Policy Implementation and Policy File Syntax and Java Security Architecture Specification files.)

Code being executed is always considered to come from a particular "code source". The code source includes not only the location (URL) where the code originated from, but also a reference to any public key(s) corresponding to the private key(s) that may have been used to sign the code. Public keys in a code source are referenced by (symbolic) alias names from the user's .

In a policy configuration file, a code source is represented by two components: a code base (URL), and an alias name (preceded by signedBy), where the alias name identifies the keystore entry containing the public key that must be used to verify the code's signature.

Each "grant" statement in such a file grants a specified code source a set of permissions, specifying which actions are allowed.

Here is a sample policy configuration file:

grant codeBase "file:/home/sysadmin/", signedBy "sysadmin" {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
    permission java.security.SecurityPermission "putProviderProperty.*";
};

This configuration file specifies that code loaded from a signed JAR file from beneath the /home/sysadmin/ directory on the local file system can add or remove providers or set provider properties. (Note that the signature of the JAR file can be verified using the public key referenced by the alias name sysadmin in the user's keystore.).

Either component of the code source (or both) may be missing. Here's an example of a configuration file where the codeBase is omitted:

grant signedBy "sysadmin" {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
};

If this policy is in effect, code that comes in a JAR File signed by /home/sysadmin/ directory on the local filesystem can add or remove providers. The code does not need to be signed.

An example where neither codeBase nor signedBy is included is:

grant {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
};

Here, with both code source components missing, any code (regardless of where it originates, or whether or not it is signed, or who signed it) can add/remove providers. Obviously, this is definitely not recommended, as this grant could open a security hole. Untrusted code could install a Provider, thus affecting later code that is depending on a properly functioning implementation. (For example, a rogue Cipher object might capture and store the sensitive information it receives.)

Managing Providers

List of methods in the Security class to query, add, or remove Providers that are installed.

The following tables summarize the methods in the Security class you can use to query which Providers are installed, as well as to install or remove providers at runtime.

Querying Providers

Method Description
static Provider[] getProviders() Returns an array containing all the installed providers (technically, the Provider subclass for each package provider). The order of the Providers in the array is their preference order.
static Provider getProvider (String providerName) Returns the Provider named providerName. It returns null if the Provider is not found.

Adding Providers

Method Description
static int addProvider(Provider provider) Adds a Provider to the end of the list of installed Providers. It returns the preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.
static int insertProviderAt (Provider provider, int position) Adds a new Provider at a specified position. If the given provider is installed at the requested position, the provider formerly at that position and all providers with a position greater than position are shifted up one position (towards the end of the list). This method returns the preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.

Removing Providers

Method Description
static void removeProvider(String name) Removes the Provider with the specified name. It returns silently if the provider is not installed. When the specified provider is removed, all providers located at a position greater than where the specified provider was are shifted down one position (towards the head of the list of installed providers).

Note:

If you want to change the preference position of a provider, you must first remove it, and then insert it back in at the new preference position.

Security Properties

The Security class maintains a list of system-wide security properties which can be set statically or dynamically.

The Security class maintains a list of system-wide security properties. These properties are similar to the System properties, but are security-related. These properties can be set statically or dynamically. The static security properties are security.provider.i and jdk.security.provider.preferred, see Customizing the Provider Implementation. If you want to set properties dynamically, trusted programs can use the following methods:

static String getProperty(String key)
static void setProperty(String key, String datum)

Note:

The list of security providers is established during VM startup, therefore the methods described above must be used to alter the provider list.

Remember:

The configuration file is located in the following location:

  • Solaris, Linux, or macOS: <java-home>/conf/security/java.security
  • Windows: <java-home>\conf\security\java.security

The SecureRandom Class

The SecureRandom class generates cryptographically strong random numbers.

The SecureRandom class is an Engine Classes and Corresponding Service Provider Interface Classes that provides the functionality of pseudo-random number generator (PRNG, also known as deterministic random bits generator or DRBG functions as specified in NIST SP 800-90Ar1), which means they use a deterministic algorithm to produce a pseudo-random sequence from a random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques. A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1.

All Java SE implementations must indicate the strongest (most random) implementation of SecureRandom that they provide in the securerandom.strongAlgorithms property of the java.security.Security class. This implementation can be used when a particularly strong random value is required.

The securerandom.drbg.config property is used to specify the DRBG SecureRandom configuration and implementations in the SUN provider. The securerandom.drbg.config is a property of the java.security.Security class. Other DRBG implementations can also use the securerandom.drbg.config property.

Figure 5-5 SecureRandom class

Description of Figure 5-5 follows
Description of "Figure 5-5 SecureRandom class"

Creating a SecureRandom Object

Alternative options to create an instance of SecureRandom object.

There are several ways to obtain an instance of SecureRandom:

  • All Java SE implementations provide a default SecureRandom using the no-argument constructor: new SecureRandom().

  • To get a specific implementation of SecureRandom, use one of the How Provider Implementations Are Requested and Supplied.

  • Use the getInstanceStrong() method to obtain a strong SecureRandom implementation as defined by the securerandom.strongAlgorithms property of the java.security.Security class. This property lists platform implementations that are suitable for generating important values.

Seeding or Re-Seeding the SecureRandom Object

Procedure to seed or re-seed the SecureRandom object.

The SecureRandom implementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to a getInstance method with a call to one of the setSeed methods:

    void setSeed(byte[] seed)
    void setSeed(long seed)

Once the SecureRandom object has been seeded, it will produce bits as random as the original seeds.

At any time a SecureRandom object may be re-seeded using one of the setSeed or reseed methods. The given seed for setSeed supplements, rather than replaces, the existing seed; therefore, repeated calls are guaranteed never to reduce randomness.

Using a SecureRandom Object

Method to use the SecureRandom object to get random bytes.

To get random bytes, a caller simply passes an array of any length, which is then filled with random bytes:

    void nextBytes(byte[] bytes)

Generating Seed Bytes

Method to invoke to generate seed bytes.

If desired, it is possible to invoke the generateSeed method to generate a given number of seed bytes (to seed other random number generators, for example):

byte[] generateSeed(int numBytes)

The MessageDigest Class

The MessageDigest class is designed to provide the functionality of cryptographically secure message digests such as SHA-1 or MD5.

The MessageDigest class is an Engine Classes and Corresponding Service Provider Interface Classes designed to provide the functionality of cryptographically secure message digests such as SHA-1 or MD5. A cryptographically secure message digest takes arbitrary-sized input (a byte array), and generates a fixed-size output, called a digest or hash.

Figure 5-6 MessageDigest Class

Description of Figure 5-6 follows
Description of "Figure 5-6 MessageDigest Class"

For example, the MD5 algorithm produces a 16 byte digest, and SHA1's is 20 bytes.

A digest has two properties:

  • It should be computationally infeasible to find two messages that hash to the same value.
  • The digest should not reveal anything about the input that was used to generate it.

Message digests are used to produce unique and reliable identifiers of data. They are sometimes called "checksums" or the "digital fingerprints" of the data. Changes to just one bit of the message should produce a different digest value.

Message digests have many uses and can determine when data has been modified, intentionally or not. Recently, there has been considerable effort to determine if there are any weaknesses in popular algorithms, with mixed results. When selecting a digest algorithm, one should always consult a recent reference to determine its status and appropriateness for the task at hand.

Creating a MessageDigest Object

Procedure to create a MessageDigest object.

  • To compute a digest, create a message digest instance. The MessageDigest objects are obtained by using one of the getInstance() methods in the MessageDigest class. See How Provider Implementations Are Requested and Supplied.
    The factory method returns an initialized message digest object. It thus does not need further initialization.

Updating a Message Digest Object

Procedure to update the Message Digest object.

  • To calculate the digest of some data, you have to supply the data to the initialized message digest object. It can be provided all at once, or in chunks. Pieces can be fed to the message digest by calling one of the update methods:
    void update(byte input)
    void update(byte[] input)
    void update(byte[] input, int offset, int len)
    

Computing the Digest

Procedure to compute the digest using different types of digest() methods.

The data chunks have to be supplied by calls to update method. See Updating a Message Digest Object.
  • The digest is computed using a call to one of the digest methods:
    byte[] digest()
    byte[] digest(byte[] input)
    int digest(byte[] buf, int offset, int len)
    
    1. The byte[] digest() method return the computed digest.
    2. The byte[] digest(byte[] input) method does a final update(input) with the input byte array before calling digest(), which returns the digest byte array.
    3. The int digest(byte[] buf, int offset, int len) method stores the computed digest in the provided buffer buf, starting at offset. len is the number of bytes in buf allotted for the digest, the method returns the number of bytes actually stored in buf. If there is not enough room in the buffer, the method will throw an exception.

The Signature Class

The Signature class is designed to provide the functionality of a cryptographic digital signature algorithm such as DSA or RSAwithMD5.

The Signature class is an Engine Classes and Corresponding Service Provider Interface Classes designed to provide the functionality of a cryptographic digital signature algorithm such as DSA or RSAwithMD5. A cryptographically secure signature algorithm takes arbitrary-sized input and a private key and generates a relatively short (often fixed-size) string of bytes, called the signature, with the following properties:

  • Only the owner of a private/public key pair is able to create a signature. It should be computationally infeasible for anyone having a public key to recover the private key.
  • Given the public key corresponding to the private key used to generate the signature, it should be possible to verify the authenticity and integrity of the input.
  • The signature and the public key do not reveal anything about the private key.

It can also be used to verify whether or not an alleged signature is in fact the authentic signature of the data associated with it.

For an example for signing and verifying data, see Generating and Verifying a Signature Using Generated Keys.

Signature Object States

Signature objects are modal objects. This means that a Signature object is always in a given state, where it may only do one type of operation.

States are represented as final integer constants defined in their respective classes.

The three states a Signature object may have are:

  • UNINITIALIZED
  • SIGN
  • VERIFY

When it is first created, a Signature object is in the UNINITIALIZED state. The Signature class defines two initialization methods, initSign and initVerify, which change the state to SIGN and VERIFY , respectively.

Creating a Signature Object

The first step for signing or verifying a signature is to create a Signature instance.

Signature objects are obtained by using one of the Signature getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

Initializing a Signature Object

A Signature object must be initialized before it is used. The initialization method depends on whether the object is going to be used for signing or for verification.

If it is going to be used for signing, the object must first be initialized with the private key of the entity whose signature is going to be generated. This initialization is done by calling the method:

final void initSign(PrivateKey privateKey)

This method puts the Signature object in the SIGN state. If instead the Signature object is going to be used for verification, it must first be initialized with the public key of the entity whose signature is going to be verified. This initialization is done by calling either of these methods:

    final void initVerify(PublicKey publicKey)

    final void initVerify(Certificate certificate)

This method puts the Signature object in the VERIFY state.

Signing with a Signature Object

After initializing the Signature object for signing, the data to be signed can then be supplied to the object.

If the Signature object has been initialized for signing (if it is in the SIGN state), the data to be signed can then be supplied to the object. This is done by making one or more calls to one of the update methods:

final void update(byte b)
final void update(byte[] data)
final void update(byte[] data, int off, int len)

Calls to the update method(s) should be made until all the data to be signed has been supplied to the Signature object.

To generate the signature, simply call one of the sign methods:

final byte[] sign()
final int sign(byte[] outbuf, int offset, int len)

The first method returns the signature result in a byte array. The second stores the signature result in the provided buffer outbuf, starting at offset. len is the number of bytes in outbuf allotted for the signature. The method returns the number of bytes actually stored.

Signature encoding is algorithm specific. See Java Cryptography Architecture Standard Algorithm Name Documentation to know more about the use of ASN.1 encoding in the Java Cryptography Architecture.

A call to a sign method resets the signature object to the state it was in when previously initialized for signing via a call to initSign. That is, the object is reset and available to generate another signature with the same private key, if desired, via new calls to update and sign.

Alternatively, a new call can be made to initSign specifying a different private key, or to initVerify (to initialize the Signature object to verify a signature).

Verifying with a Signature Object

After initializing the Signature object for verification, it can then verify if an alleged signature is in fact the authentic signature of the data associated with it.

If the Signature object has been initialized for verification (if it is in the VERIFY state), it can then verify if an alleged signature is in fact the authentic signature of the data associated with it. To start the process, the data to be verified (as opposed to the signature itself) is supplied to the object. The data is passed to the object by calling one of the update methods:

final void update(byte b)
final void update(byte[] data)
final void update(byte[] data, int off, int len)

Calls to the update method(s) should be made until all the data to be verified has been supplied to the Signature object. The signature can now be verified by calling one of the verify methods:

final boolean verify(byte[] signature)

final boolean verify(byte[] signature, int offset, int length)

The argument must be a byte array containing the signature. This byte array would hold the signature bytes which were returned by a previous call to one of the sign methods.

The verify method returns a boolean indicating whether or not the encoded signature is the authentic signature of the data supplied to the update method(s).

A call to the verify method resets the signature object to its state when it was initialized for verification via a call to initVerify. That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

Alternatively, a new call can be made to initVerify specifying a different public key (to initialize the Signature object for verifying a signature from a different entity), or to initSign (to initialize the Signature object for generating a signature).

The Cipher Class

The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption.

Encryption is the process of taking data (called cleartext) and 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 key and producing cleartext.

Symmetric vs. Asymmetric Cryptography

There are two major types of encryption: symmetric (also known as secret key), and asymmetric (or public key cryptography). In symmetric cryptography, the same secret key to both encrypt and decrypt the data. Keeping the key private is critical to keeping the data confidential. On the other hand, asymmetric cryptography uses a public/private key pair to encrypt data. Data encrypted with one key is decrypted with the other. A user first generates a public/private key pair, and then publishes the public key in a trusted database that anyone can access. A user who wishes to communicate securely with that user encrypts the data using the retrieved public key. Only the holder of the private key will be able to decrypt. Keeping the private key confidential is critical to this scheme.

Asymmetric algorithms (such as RSA) are generally much slower than symmetric ones. These algorithms are not designed for efficiently protecting large amounts of data. In practice, asymmetric algorithms are used to exchange smaller secret keys which are used to initialize symmetric algorithms.

Stream vs. Block Ciphers

There are two major types of ciphers: block and stream. Block ciphers process entire blocks at a time, usually many bytes in length. If there is not enough data to make a complete input block, the data must be padded: that is, before encryption, dummy bytes must be added to make a multiple of the cipher's block size. These bytes are then stripped off during the decryption phase. The padding can either be done by the application, or by initializing a cipher to use a padding type such as "PKCS5PADDING". In contrast, stream ciphers process incoming data one small unit (typically a byte or even a bit) at a time. This allows for ciphers to process an arbitrary amount of data without padding.

Modes Of Operation

When encrypting using a simple block cipher, two identical blocks of plaintext will always produce an identical block of cipher text. Cryptanalysts trying to break the ciphertext will have an easier job if they note blocks of repeating text. In order to add more complexity to the text, feedback modes use the previous block of output to alter the input blocks before applying the encryption algorithm. The first block will need an initial value, and this value is called the initialization vector (IV). Since the IV simply alters the data before any encryption, the IV should be random but does not necessarily need to be kept secret. There are a variety of modes, such as CBC (Cipher Block Chaining), CFB (Cipher Feedback Mode), and OFB (Output Feedback Mode). ECB (Electronic Cookbook Mode) is a mode with no feedback.

Some algorithms such as AES and RSA allow for keys of different lengths, but others are fixed, such as DES and 3DES. Encryption using a longer key generally implies a stronger resistance to message recovery. As usual, there is a trade off between security and time, so choose the key length appropriately.

Most algorithms use binary keys. Most humans do not have the ability to remember long sequences of binary numbers, even when represented in hexadecimal. Character passwords are much easier to recall. Because character passwords are generally chosen from a small number of characters (for example, [a-zA-Z0-9]), protocols such as "Password-Based Encryption" (PBE) have been defined which take character passwords and generate strong binary keys. In order to make the task of getting from password to key very time-consuming for an attacker (via so-called "dictionary attacks" where common dictionary word->value mappings are precomputed), most PBE implementations will mix in a random number, known as a salt, to increase the key randomness.

Newer cipher modes such as Authenticated Encryption with Associated Data (AEAD) (for example, Galois/Counter Mode (GCM)) encrypt data and authenticate the resulting message simultaneously. Additional Associated Data (AAD) can be used during the calculation of the resulting AEAD tag (Mac), but this AAD data is not output as ciphertext. (For example, some data might not need to be kept confidential, but should figure into the tag calculation to detect modifications.) The Cipher.updateAAD() methods can be used to include AAD in the tag calculations.

Using an AES Cipher with GCM Mode

AES Cipher with GCM is an AEAD Cipher which has different usage patterns than the non-AEAD ciphers. Apart from the regular data, it also takes AAD which is optional for encryption/decryption but AAD must be supplied before data for encryption/decryption. In addition, in order to use GCM securely, callers should not re-use key and IV combinations for encryption. This means that the cipher object should be explicitly re-initialized with a different set of parameters every time for each encryption operation.

Example 5-2 Sample Code for Using an AES Cipher with GCM Mode

        SecretKey myKey = ...
        byte[] myAAD = ...
        byte[] plainText = ...
        int myTLen = ... 
        byte[] myIv = ...

        GCMParameterSpec myParams = new GCMParameterSpec(myTLen, myIv);
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, myKey, myParams);

        // AAD is optional, if present, it must be supplied before any update/doFinal calls.
        c.updateAAD(myAAD);  // if AAD is non-null
        byte[] cipherText = new byte[c.getOutputSize(plainText.length)];
        c.doFinal(plainText, 0, plainText.length, cipherText);    // conclusion of encryption operation

        // To decrypt, same AAD and GCM parameters must be supplied
        c.init(Cipher.DECRYPT_MODE, myKey, myParams);
        c.updateAAD(myAAD);
        byte[] recoveredText = c.doFinal(cipherText);

        // MUST CHANGE IV VALUE if the same key were to be used again for encryption
        byte[] newIv = ...;
        myParams = new GCMParameterSpec(myTLen, newIv);

Creating a Cipher Object

Cipher objects are obtained by using one of the Cipher getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied. Here, the algorithm name is slightly different than with other engine classes, in that it specifies not just an algorithm name, but a "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 mode and padding scheme.

A transformation is of the form:

  • "algorithm/mode/padding" or
  • "algorithm"

For example, the following are valid transformations:

    "DES/CBC/PKCS5Padding"

    "DES"

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, returns 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.

It is recommended to use a transformation that fully specifies the algorithm, mode, and padding. By not doing so, the provider will use a default. For example, the SunJCE and SunPKCS11 providers use ECB as the default mode, and PKCS5Padding as the default padding for many symmetric ciphers.

This means that in the case of the SunJCE provider:

    Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");

and

    Cipher c1 = Cipher.getInstance("DES");

are equivalent statements.

Note:

ECB mode is the easiest block cipher mode to use and is the default in the JDK/JRE. ECB works well for single blocks of data, but absolutely should not be used for multiple data blocks.

Using modes such as CFB and OFB, block ciphers can encrypt data in units smaller than the cipher's actual block size. When requesting such a 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 SunJCE provider uses a default of 64 bits for DES.) Thus, block ciphers can be turned into byte-oriented stream ciphers by using an 8 bit mode such as CFB8 or OFB8.

Appendix A: Standard Names of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation.

The objects returned by factory methods are uninitialized, and must be initialized before they become usable.

Initializing a Cipher Object

A Cipher object obtained via getInstance must be initialized for one of four modes, which are defined as final integer constants in the Cipher class. The modes can be referenced by their symbolic names, which are shown below along with a description of the purpose of each mode:

ENCRYPT_MODE
Encryption of data.
DECRYPT_MODE
Decryption of data.
WRAP_MODE
Wrapping a java.security.Key into bytes so that the key can be securely transported.
UNWRAP_MODE
Unwrapping of a previously wrapped key into a java.security.Key object.

Each of the Cipher initialization methods takes an operational mode parameter (opmode), and initializes the Cipher object for that mode. Other parameters include the key (key) or certificate containing the key (certificate), algorithm parameters (params), and a source of randomness (random).

To initialize a Cipher object, call one of the following init methods:

    public void init(int opmode, Key key);

    public void init(int opmode, Certificate certificate);

    public void init(int opmode, Key key, SecureRandom random);

    public void init(int opmode, Certificate certificate,
                     SecureRandom random);

    public void init(int opmode, Key key,
                     AlgorithmParameterSpec params);

    public void init(int opmode, Key key,
                     AlgorithmParameterSpec params, SecureRandom random);

    public void init(int opmode, Key key,
                     AlgorithmParameters params);

    public void init(int opmode, Key key,
                     AlgorithmParameters params, SecureRandom random);

If a Cipher object that requires parameters (e.g., an initialization vector) is initialized for encryption, and no parameters are supplied to the init method, the underlying cipher implementation is supposed to supply the required parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters.

However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the init method, an InvalidKeyException or InvalidAlgorithmParameterException exception will be raised, depending on the init method that has been used.

See Managing Algorithm Parameters.

The same parameters that were used for encryption must be used for decryption.

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 or 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 following doFinal 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.

A call to doFinal resets the Cipher object to the state it was in when initialized via a call to init. That is, the Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call to init) more data.

Wrapping and Unwrapping Keys

Wrapping a key enables secure transfer of the key from one place to another.

The wrap/unwrap API makes it more convenient to write code since it works with key objects directly. These methods also enable the possibility of secure transfer of hardware-based keys.

To wrap a Key, first initialize the Cipher object for WRAP_MODE, and then call the following:

    public final byte[] wrap(Key key);

If you are supplying the wrapped key bytes (the result of calling wrap) to someone else who will unwrap them, be sure to also send additional information the recipient will need in order to do the unwrap:

  • The name of the key algorithm.
  • The type of the wrapped key (one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY).

The key algorithm name can be determined by calling the getAlgorithm method from the Key interface:

    public String getAlgorithm();

To unwrap the bytes returned by a previous call to wrap, first initialize a Cipher object for UNWRAP_MODE, then call the following:

    public final Key unwrap(byte[] wrappedKey,
                            String wrappedKeyAlgorithm,
                            int wrappedKeyType));

Here, wrappedKey is the bytes returned from the previous call to wrap, wrappedKeyAlgorithm is the algorithm associated with the wrapped key, and wrappedKeyType is the type of the wrapped key. This must be one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY.

Managing Algorithm Parameters

The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the init method by the application or generated by the underlying implementation itself, can be retrieved from the Cipher object by calling its getParameters method, which returns the parameters as a java.security.AlgorithmParameters object (or null if no parameters are being used). If the parameter is an initialization vector (IV), it can also be retrieved by calling the getIV method.

In the following example, a Cipher object implementing password-based encryption (PBE) is initialized with just a key and no parameters. However, the selected algorithm for password-based encryption requires two parameters - a salt and an iteration count. Those will be generated by the underlying algorithm implementation itself. The application can retrieve the generated parameters from the Cipher object, see Example 5-3.

The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption, see Example 5-4.

If you did not specify any parameters when you initialized a Cipher object, and you are not sure whether or not the underlying implementation uses any parameters, you can find out by simply calling the getParameters method of your Cipher object and checking the value returned. A return value of null indicates that no parameters were used.

The following cipher algorithms implemented by the SunJCE provider use parameters:

  • DES, DES-EDE, and Blowfish, when used in feedback (i.e., CBC, CFB, OFB, or PCBC) mode, use an initialization vector (IV). The javax.crypto.spec.IvParameterSpec class can be used to initialize a Cipher object with a given IV.
  • PBE Cipher algorithms use a set of parameters, comprising of a salt and an iteration count. The javax.crypto.spec.PBEParameterSpec class can be used to initialize a Cipher object implementing a PBE algorithm (for example: PBEWithHmacSHA256AndAES_256) with a given salt and iteration count.

Note that you do not have to worry about storing or transferring any algorithm parameters for use by the decryption operation if you use the The SealedObject Class class. This class attaches the parameters used for sealing (encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).

Example 5-3 Sample Code for Retrieving Parameters from the Cipher Object

The application can retrieve the generated parameters for encryption from the Cipher object as follows:

    import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");

    // initialize cipher for encryption, without supplying
    // any parameters. Here, "myKey" is assumed to refer
    // to an already-generated key.
    c.init(Cipher.ENCRYPT_MODE, myKey);

    // encrypt some data and store away ciphertext
    // for later decryption
    byte[] cipherText = c.doFinal("This is just an example".getBytes());

    // retrieve parameters generated by underlying cipher
    // implementation
    AlgorithmParameters algParams = c.getParameters();

    // get parameter encoding and store it away
    byte[] encodedAlgParams = algParams.getEncoded();

Example 5-4 Sample Code for Initializing the Cipher Object for Decryption

The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption as follows:

    import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get parameter object for password-based encryption
    AlgorithmParameters algParams;
    algParams = AlgorithmParameters.getInstance("PBEWithHmacSHA256AndAES_256");

    // initialize with parameter encoding from above
    algParams.init(encodedAlgParams);

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");

    // initialize cipher for decryption, using one of the
    // init() methods that takes an AlgorithmParameters
    // object, and pass it the algParams object from above
    c.init(Cipher.DECRYPT_MODE, myKey, algParams);

Cipher Output Considerations

Some of the update and doFinal 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 getOutputSize(int inputLen)

Other Cipher-based Classes

There are some helper classes which internally use Ciphers to provide easy access to common cipher uses.

The Cipher Stream Classes

The CipherInputStream and CipherOutputStream classes are Cipher stream classes.

The CipherInputStream Class

This class is a FilterInputStream that encrypts or decrypts the data passing through it. It is composed of an InputStream CipherInputStream represents a secure input stream into which a Cipher object has been interposed. The read 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 and java.io.InputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that the data are additionally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, the skip(long) method skips only data that has been processed by the Cipher.

It is crucial for a programmer using this class not to use methods that are not defined or overridden 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. See Example 5-5 for its usage, suppose cipher1 has been initialized for encryption. The program reads and encrypts the content from the file /tmp/a.txt and then stores the result (the encrypted bytes) in /tmp/b.txt.

Example 5-6 demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that cipher1 and cipher2 have been initialized for encryption and decryption (with corresponding keys), respectively. The 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. Of course since this program simply encrypts text and decrypts it back right away, it's actually not very useful except as a simple way of illustrating chaining of CipherInputStreams.

Note that the read methods of the CipherInputStream will block until data is returned from the underlying cipher. If a block cipher is used, a full block of cipher text will have to be obtained from the underlying InputStream.

Example 5-5 Sample Code for Using CipherInputStream and FileInputStream

The code below demonstrates how to use a CipherInputStream containing that cipher and a FileInputStream in order to encrypt input stream data:

    FileInputStream fis;
    FileOutputStream fos;
    CipherInputStream cis;

    fis = new FileInputStream("/tmp/a.txt");
    cis = new CipherInputStream(fis, cipher1);
    fos = new FileOutputStream("/tmp/b.txt");
    byte[] b = new byte[8];
    int i = cis.read(b);
    while (i != -1) {
        fos.write(b, 0, i);
        i = cis.read(b);
    }
    fos.close();

Example 5-6 Sample Code for Connecting CipherInputStream and FileInputStream

The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that cipher1 and cipher2 have been initialized for encryption and decryption (with corresponding keys), respectively:

    FileInputStream fis;
    FileOutputStream fos;
    CipherInputStream cis1, cis2;

    fis = new FileInputStream("/tmp/a.txt");
    cis1 = new CipherInputStream(fis, cipher1);
    cis2 = new CipherInputStream(cis1, cipher2);
    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);
    }
    fos.close();

The CipherOutputStream Class

This class is a FilterOutputStream that encrypts or decrypts the data passing through it. It is composed of an OutputStream, or one of its subclasses, and a Cipher. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. The write 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 overridden 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.

See Example 5-7 , for its usage, suppose cipher1 has been initialized for encryption. The program reads the content from the file /tmp/a.txt, then encrypts and stores the result (the encrypted bytes) in /tmp/b.txt.

Example 5-7 demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that cipher1 and cipher2 have been initialized for decryption and encryption (with corresponding keys), respectively. The 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.

One thing to keep in mind when using block cipher algorithms is that a full block of plaintext data must be given to the CipherOutputStream before the data will be encrypted and sent to the underlying output stream.

There is one other important difference between the flush and close methods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:

  • flush flushes the underlying OutputStream by forcing any buffered output bytes that have already been processed by the encapsulated Cipher object to be written out. Any bytes buffered by the encapsulated Cipher object and waiting to be processed by it will not be written out.
  • close closes the underlying OutputStream and releases any system resources associated with it. It invokes the doFinal method of the encapsulated Cipher object, causing any bytes buffered by it to be processed and written out to the underlying stream by calling its flush method.

Example 5-7 Sample Code for Using CipherOutputStream and FileOutputStream

The code demonstrates how to use a CipherOutputStream containing that cipher and a FileOutputStream in order to encrypt data to be written to an output stream:
    FileInputStream fis;
    FileOutputStream fos;
    CipherOutputStream cos;

    fis = new FileInputStream("/tmp/a.txt");
    fos = new FileOutputStream("/tmp/b.txt");
    cos = new CipherOutputStream(fos, cipher1);
    byte[] b = new byte[8];
    int i = fis.read(b);
    while (i != -1) {
        cos.write(b, 0, i);
        i = fis.read(b);
    }
    cos.flush();

Example 5-8 Sample Code for Connecting CipherOutputStream and FileOutputStream

The code demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that cipher1 and cipher2 have been initialized for decryption and encryption (with corresponding keys), respectively:
    FileInputStream fis;
    FileOutputStream fos;
    CipherOutputStream cos1, cos2;

    fis = new FileInputStream("/tmp/a.txt");
    fos = new FileOutputStream("/tmp/b.txt");
    cos1 = new CipherOutputStream(fos, cipher1);
    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 SealedObject Class

This class enables a programmer to create an object and protect its confidentiality with a cryptographic algorithm.

Given any object that implements the java.io.Serializable interface, 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: In order to seal an object, you create a SealedObject from the object to be sealed and a fully initialized Cipher object that will encrypt the serialized object contents. In this example, the String "This is a secret" is sealed using the DES algorithm. Note that any algorithm parameters that may be used in the sealing operation are stored inside of SealedObject:

    // create Cipher object
    // NOTE: sKey is assumed to refer to an already-generated
    // secret DES key.
    Cipher c = Cipher.getInstance("DES");
    c.init(Cipher.ENCRYPT_MODE, sKey);

    // do the sealing
    SealedObject so = new SealedObject("This is a secret", c);

The original object that was sealed can be recovered in two different ways:

  • by using a Cipher object that has been initialized with the exact same algorithm, key, padding scheme, etc., that were used to seal the object:
        c.init(Cipher.DECRYPT_MODE, sKey);
        try {
            String s = (String)so.getObject(c);
        } catch (Exception e) {
            // do something
        };
    

    This approach has the advantage that the party who unseals the sealed object does not require knowledge of the decryption key. For example, after one party has initialized the cipher object with the required decryption key, it could hand over the cipher object to another party who then unseals the sealed object.

  • by using the appropriate decryption key (since DES is a symmetric encryption algorithm, we use the same key for sealing and unsealing):
        try {
            String s = (String)so.getObject(sKey);
        } catch (Exception e) {
            // do something
        };
    

    In this approach, the getObject method creates a cipher object for the appropriate decryption algorithm and initializes it with the given decryption key and the algorithm parameters (if any) that were stored in the sealed object. This approach has the advantage that the party who unseals the object does not need to keep track of the parameters (e.g., the IV) that were used to seal the object.

The Mac Class

Similar to a MessageDigest, a Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, but includes a secret key in the calculation.

Only someone with the proper key will be able to verify the received message. 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.

The Mac class provides the functionality of a Message Authentication Code (MAC). See HMAC-MD5 Example.

Creating a Mac Object

Mac objects are obtained by using one of the Mac getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

Initializing a Mac Object

A Mac object is always initialized with a (secret) key and may optionally be initialized with a set of parameters, depending on the underlying MAC algorithm.

To initialize a Mac object, call one of its init methods:

    public void init(Key key);

    public void init(Key key, AlgorithmParameterSpec params);

You can initialize your Mac object with any (secret-)key object that implements the javax.crypto.SecretKey interface. This could be an object returned by javax.crypto.KeyGenerator.generateKey(), or one that is the result of a key agreement protocol, as returned by javax.crypto.KeyAgreement.generateSecret(), or an instance of javax.crypto.spec.SecretKeySpec.

With some MAC algorithms, the (secret-)key algorithm associated with the (secret-)key object used to initialize the Mac object does not matter (this is the case with the HMAC-MD5 and HMAC-SHA1 implementations of the SunJCE provider). With others, however, the (secret-)key algorithm does matter, and an InvalidKeyException is thrown if a (secret-)key object with an inappropriate (secret-)key algorithm is used.

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 the following doFinal method:

    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 the above doFinal method (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

    public byte[] doFinal();

    public void doFinal(byte[] output, int outOffset);

Key Interfaces

The java.security.Key interface is the top-level interface for all opaque keys. It defines the functionality shared by all opaque key objects.

To this point, we have focused the high-level uses of the JCA without getting lost in the details of what keys are and how they are generated/represented. It is now time to turn our attention to keys.

An opaque key representation is one in which you have no direct access to the key material that constitutes a key. In other words: "opaque" gives you limited access to the key--just the three methods defined by the Key interface (see below): getAlgorithm, getFormat, and getEncoded.

This is in contrast to a transparent representation, in which you can access each key material value individually, through one of the get methods defined in the corresponding The KeySpec Interface.

All opaque keys have three characteristics:

An Algorithm
The key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as AES, DSA or RSA), which will work with those algorithms and with related algorithms (such as MD5withRSA, SHA1withRSA, etc.) The name of the algorithm of a key is obtained using this method:
String getAlgorithm()
An Encoded Form
The external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party. The key is encoded according to a standard format (such as X.509 or PKCS8), and is returned using the method:
byte[] getEncoded()
A Format
The name of the format of the encoded key. It is returned by the method:
String getFormat()

Keys are generally obtained through key generators such as The KeyGenerator Class and The KeyPairGenerator Class , certificates, The KeySpec Interface (using a The KeyFactory Class), or a The KeyStore Class implementation accessing a keystore database used to manage keys. It is possible to parse encoded keys, in an algorithm-dependent manner, using a The KeyFactory Class.

It is also possible to parse certificates, using a The CertificateFactory Class.

Here is a list of interfaces which extend the Key interface in the java.security.interfaces and javax.crypto.interfaces packages:

The PublicKey and PrivateKey Interfaces

The PublicKey and PrivateKey interfaces (which both extend the Key interface) are methodless interfaces, used for type-safety and type-identification.

The KeyPair Class

The KeyPair class is a simple holder for a key pair (a public key and a private key).

It has two public methods, one for returning the private key, and the other for returning the public key:

PrivateKey getPrivate()
PublicKey getPublic()

Key Specification Interfaces and Classes

Key objects and key specifications (KeySpecs) are two different representations of key data. Ciphers use Key objects to initialize their encryption algorithms, but keys may need to be converted into a more portable format for transmission or storage.

A transparent representation of keys means that you can access each key material value individually, through one of the get methods defined in the corresponding specification class. For example, DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.

This representation is contrasted with an opaque representation, as defined by the Key Interfaces interface, in which you have no direct access to the key material fields. In other words, an "opaque" representation gives you limited access to the key--just the three methods defined by the Key interface: getAlgorithm, getFormat, and getEncoded.

A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

The The KeyFactory Class and The SecretKeyFactory Class classes can be used to convert between opaque and transparent key representations (that is, between Keys and KeySpecs, assuming that the operation is possible. (For example, private keys on smart cards might not be able leave the card. Such Keys are not convertible.)

In the following sections, we discuss the key specification interfaces and classes in the java.security.spec package.

The KeySpec Interface

This interface contains no methods or constants. Its only purpose is to group and provide type safety for all key specifications. All key specifications must implement this interface.

The EncodedKeySpec Class

The EncodedKeySpec abstract class represents a public or private key in encoded format.

This abstract class (which implements the The KeySpec Interface interface) represents a public or private key in encoded format. Its getEncoded method returns the encoded key:

abstract byte[] getEncoded();

and its getFormat method returns the name of the encoding format:

abstract String getFormat();

See the next sections for the concrete implementations PKCS8EncodedKeySpec and X509EncodedKeySpec.

The PKCS8EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS8 standard.

Its getEncoded method returns the key bytes, encoded according to the PKCS8 standard. Its getFormat method returns the string "PKCS#8".

The X509EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a public key, according to the format specified in the X.509 standard.

Its getEncoded method returns the key bytes, encoded according to the X.509 standard. Its getFormat method returns the string "X.509".

Generators and Factories

Generators are used to generate brand new objects and factories are used to convert data from one existing object type to another.

Newcomers to Java and the JCA APIs in particular sometimes do not grasp the distinction between generators and factories.

Figure 5-10 Generators and Factories

Description of Figure 5-10 follows
Description of "Figure 5-10 Generators and Factories"

Generators are used to generate brand new objects. Generators can be initialized in either an algorithm-dependent or algorithm-independent way. For example, to create a Diffie-Hellman (DH) keypair, an application could specify the necessary P and G values, or the generator could simply be initialized with the appropriate key length, and the generator will select appropriate P and G values. In both cases, the generator will produce brand new keys based on the parameters.

On the other hand, factories are used to convert data from one existing object type to another. For example, an application might have available the components of a DH private key and can package them as a The KeySpec Interface, but needs to convert them into a PrivateKey object that can be used by a KeyAgreement object, or vice-versa. Or they might have the byte array of a certificate, but need to use a CertificateFactory to convert it into a X509Certificate object. Applications use factory objects to do the conversion.

The KeyFactory Class

The KeyFactory class is designed to perform conversions between opaque cryptographic Keys and Key specifications.

The KeyFactory class is an Engine Classes and Corresponding Service Provider Interface Classes designed to perform conversions between opaque cryptographic Key Interfaces and Key Specification Interfaces and Classes (transparent representations of the underlying key material).

Figure 5-11 KeyFactory Class

Description of Figure 5-11 follows
Description of "Figure 5-11 KeyFactory Class"

Key factories are bi-directional. They allow you 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.

Multiple compatible key specifications can exist for the same key. For example, a DSA public key may be specified by its components y, p, q, and g (see java.security.spec.DSAPublicKeySpec), or it may be specified using its DER encoding according to the X.509 standard (see The X509EncodedKeySpec Class).

A key factory can be used to translate between compatible key specifications. Key parsing can be achieved through translation between compatible key specifications, e.g., when you translate from X509EncodedKeySpec to DSAPublicKeySpec, you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications and KeyFactory section.

Creating a KeyFactory Object

KeyFactory objects are obtained by using one of the KeyFactorygetInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

Converting Between a Key Specification and a Key Object

If you have a key specification for a public key, you can obtain an opaque PublicKey object from the specification by using the generatePublic method:

PublicKey generatePublic(KeySpec keySpec)

Similarly, if you have a key specification for a private key, you can obtain an opaque PrivateKey object from the specification by using the generatePrivate method:

PrivateKey generatePrivate(KeySpec keySpec)

Converting Between a Key Object and a Key Specification

If you have a Key object, you can get a corresponding key specification object by calling the getKeySpec method:

KeySpec getKeySpec(Key key, Class keySpec)

keySpec identifies the specification class in which the key material should be returned. It could, for example, be DSAPublicKeySpec.class , to indicate that the key material should be returned in an instance of the DSAPublicKeySpec class. See Generating/Verifying Signatures Using Key Specifications and KeyFactory.

The SecretKeyFactory Class

The SecretKeyFactory class represents a factory for secret keys.

Unlike The KeyFactory Class, a javax.crypto.SecretKeyFactory object operates only on secret (symmetric) keys, whereas a java.security.KeyFactory object processes the public and private key components of a key pair.

Figure 5-12 SecretKeyFactory Class

Description of Figure 5-12 follows
Description of "Figure 5-12 SecretKeyFactory Class"

Key factories are used to convert Key Interfaces (opaque cryptographic keys of type java.security.Key) into Key Specification Interfaces and Classes (transparent representations of the underlying key material in a suitable format), and vice versa.

Objects of type java.security.Key, of which java.security.PublicKey, java.security.PrivateKey, and javax.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 modulus p, and the base g, and you feed the same specification to Diffie-Hellman key factories from different providers, the resulting PublicKey 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 supports DESKeySpec as a transparent representation of DES keys, the SecretKeyFactory for DES-EDE keys supports DESedeKeySpec as a transparent representation of DES-EDE keys, and the SecretKeyFactory for PBE supports PBEKeySpec 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 a SecretKey object, which can be used for a subsequent Cipher operation:

    // Note the following bytes are not realistic secret key data
    // bytes but are simply supplied as an illustration of using data
    // bytes (key material) you already have to build a DESKeySpec.
    byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03,
    (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };
    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 of KeyFactory.

An alternative, provider-independent way of creating a functionally equivalent SecretKey object from the same key material is to use the javax.crypto.spec.SecretKeySpec class, which implements the javax.crypto.SecretKey interface:

    byte[] desKeyData = { (byte)0x01, (byte)0x02, ...};
    SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");

The KeyPairGenerator Class

The KeyPairGenerator class is used to generate pairs of public and private keys.

The KeyPairGenerator class is an Engine Classes and Corresponding Service Provider Interface Classes.

Figure 5-13 KeyPairGenerator Class

Description of Figure 5-13 follows
Description of "Figure 5-13 KeyPairGenerator Class"

There are two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object.

See Generating a Pair of Keys for examples of calls to the methods documented below.

Creating a KeyPairGenerator

All key pair generation starts with a KeyPairGenerator. KeyPairGenerator objects are obtained by using one of the KeyPairGenerator getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

Initializing a KeyPairGenerator

A key pair generator for a particular algorithm creates a public/private key pair that can be used with this algorithm. It also associates algorithm-specific parameters with each of the generated keys.

A key pair generator needs to be initialized before it can generate keys. In most cases, algorithm-independent initialization is sufficient. But in other cases, algorithm-specific initialization can be used.

Algorithm-Independent Initialization

All key pair generators share the concepts of a keysize and a source of randomness. The keysize is interpreted differently for different algorithms. For example, in the case of the DSA algorithm, the keysize corresponds to the length of the modulus. (See Java Cryptography Architecture Standard Algorithm Name Documentation for information about the keysizes for specific algorithms.)

An initialize method takes two universally shared types of arguments:

void initialize(int keysize, SecureRandom random)

Another initialize method takes only a keysize argument; it uses a system-provided source of randomness:

void initialize(int keysize)

Since no other parameters are specified when you call the above algorithm-independent initialize methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys.

If the algorithm is a "DSA" algorithm, and the modulus size (keysize) is 512, 768, or 1024, then the SUN provider uses a set of precomputed values for the p, q, and g parameters. If the modulus size is not one of the above values, the SUN provider creates a new set of parameters. Other providers might have precomputed parameter sets for more than just the three modulus sizes mentioned above. Still others might not have a list of precomputed parameters at all and instead always create new parameter sets.

Algorithm-Specific Initialization

For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two initialize methods that have an Algorithm Parameters Classes argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:

void initialize(AlgorithmParameterSpec params,
                SecureRandom random)

void initialize(AlgorithmParameterSpec params)

See Generating a Pair of Keys.

Generating a Key Pair

The procedure for generating a key pair is always the same, regardless of initialization (and of the algorithm). You always call the following method from KeyPairGenerator:

KeyPair generateKeyPair()

Multiple calls to generateKeyPair will yield different key pairs.

The KeyGenerator Class

A key generator is used to generate secret keys for symmetric algorithms.

Figure 5-14 The KeyGenerator Class

Description of Figure 5-14 follows
Description of "Figure 5-14 The KeyGenerator Class"

Creating a KeyGenerator

KeyGenerator objects are obtained by using one of the KeyGenerator getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

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 keysize and a source of randomness. There is an init method that takes these two universally shared types of arguments. There is also one that takes just a keysize 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 keysize);
    
        public void init(int keysize, 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 an AlgorithmParameterSpec argument. One also has a SecureRandom 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 KeyAgreement Class

Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.

Figure 5-15 The KeyAgreement Class

Description of Figure 5-15 follows
Description of "Figure 5-15 The KeyAgreement Class"

Each party initializes their key agreement object with their private key, and then enters the public keys for each party that will participate in the communication. In most cases, there are just two parties, but algorithms such as Diffie-Hellman allow for multiple parties (3 or more) to participate. When all the public keys have been entered, each KeyAgreement object will generate (agree upon) the same key.

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 or KeyGenerator), a KeyFactory, 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. KeyAgreement objects are obtained by using one of the KeyAgreement getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

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 generator g as its parameters.)

To initialize a KeyAgreement object, call one of its 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 agreement: A value of FALSE indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value of TRUE 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 Key Exchange between 2 Parties , you call doPhase once, with lastPhase set to TRUE. In the example of Diffie-Hellman between three parties, you call doPhase twice: the first time with lastPhase set to FALSE, the 2nd time with lastPhase set to TRUE.

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

Key Management

A database called a "keystore" can be used to manage a repository of keys and certificates. (A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.)

The KeyStore Class

The KeyStore class supplies well-defined interfaces to access and modify the information in a keystore.

The KeyStore class is an Engine Classes and Corresponding Service Provider Interface Classes.

This class represents an in-memory collection of keys and certificates. KeyStore manages two types of entries:

  • Key Entry: This type of keystore entry holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain authenticating the corresponding public key.

    Private keys and certificate chains are used by a given entity for self-authentication using digital signatures. For example, software distribution organizations digitally sign JAR files as part of releasing and/or licensing software.

  • Trusted Certificate Entry: This type of entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate.

    This type of entry can be used to authenticate other parties.

Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This convention allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

The main KeyStore methods are described below.

Loading a Particular Keystore into Memory

Before a KeyStore object can be used, the actual keystore data must be loaded into memory via the load method:

final void load(InputStream stream, char[] password)

The optional password is used to check the integrity of the keystore data. If no password is supplied, no integrity check is performed.

To create an empty keystore, you pass null as the InputStream argument to the load method.

A DKS keystore is loaded by passing a DomainLoadStoreParameter to the alternative load method:

final void load(KeyStore.LoadStoreParameter param)

Loading a Particular Keystore into Memory

Before a KeyStore object can be used, the actual keystore data must be loaded into memory via the load method:

final void load(InputStream stream, char[] password)

The optional password is used to check the integrity of the keystore data. If no password is supplied, no integrity check is performed.

To create an empty keystore, you pass null as the InputStream argument to the load method.

A DKS keystore is loaded by passing a DomainLoadStoreParameter to the alternative load method:

final void load(KeyStore.LoadStoreParameter param)

Getting a List of the Keystore Aliases

All keystore entries are accessed via unique aliases. The aliases method returns an enumeration of the alias names in the keystore:

final Enumeration aliases()

Determining Keystore Entry Types

As stated in the KeyStore class, there are two different types of entries in a keystore. The following methods determine whether the entry specified by the given alias is a key/certificate or a trusted certificate entry, respectively:

final boolean isKeyEntry(String alias)
final boolean isCertificateEntry(String alias)

Adding/Setting/Deleting Keystore Entries

The setCertificateEntry method assigns a certificate to a specified alias:

final void setCertificateEntry(String alias, Certificate cert)

If alias doesn't exist, a trusted certificate entry with that alias is created. If alias exists and identifies a trusted certificate entry, the certificate associated with it is replaced by cert.

The setKeyEntry methods add (if alias doesn't yet exist) or set key entries:

final void setKeyEntry(String alias,
                       Key key,
                       char[] password,
                       Certificate[] chain)

final void setKeyEntry(String alias,
                       byte[] key,
                       Certificate[] chain)

In the method with key as a byte array, it is the bytes for a key in protected format. For example, in the keystore implementation supplied by the SUN provider, the key byte array is expected to contain a protected private key, encoded as an EncryptedPrivateKeyInfo as defined in the PKCS8 standard. In the other method, the password is the password used to protect the key.

The deleteEntry method deletes an entry:

final void deleteEntry(String alias)

PKCS #12 keystores support entries containing arbitrary attributes. Use the PKCS12Attribute class to create the attributes. When creating the new keystore entry use a constructor method that accepts attributes. Finally, use the following method to add the entry to the keystore:

final void setEntry(String alias, Entry entry, 
                    ProtectionParameter protParam)

Getting Information from the Keystore

The getKey method returns the key associated with the given alias. The key is recovered using the given password:

final Key getKey(String alias, char[] password)

The following methods return the certificate, or certificate chain, respectively, associated with the given alias:

final Certificate getCertificate(String alias)
final Certificate[] getCertificateChain(String alias)

You can determine the name (alias) of the first entry whose certificate matches a given certificate via the following:

final String getCertificateAlias(Certificate cert)

PKCS #12 keystores support entries containing arbitrary attributes. Use the following method to retrieve an entry that may contain attributes:

final Entry getEntry(String alias, ProtectionParameter protParam)

and then use the KeyStore.Entry.getAttributes method to extract such attributes and use the methods of the KeyStore.Entry.Attribute interface to examine them.

Saving the KeyStore

The in-memory keystore can be saved via the store method:

final void store(OutputStream stream, char[] password)

The password is used to calculate an integrity checksum of the keystore data, which is appended to the keystore data.

A DKS keystore is stored by passing a DomainLoadStoreParameter to the alternative store method:

final void store(KeyStore.LoadStoreParameter param)

Algorithm Parameters Classes

Like Keys and Keyspecs, an algorithm's initialization parameters are represented by either AlgorithmParameters or AlgorithmParameterSpecs.

Depending on the use situation, algorithms can use the parameters directly, or the parameters might need to be converted into a more portable format for transmission or storage.

A transparent representation of a set of parameters (via AlgorithmParameterSpec) means that you can access each parameter value in the set individually. You can access these values through one of the get methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access p, q, and g, respectively).

In contrast, the The AlgorithmParameters Class class supplies an opaque representation, in which you have no direct access to the parameter fields. You can only get the name of the algorithm associated with the parameter set (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

Algorithm Parameters Classes

AlgorithmParameterSpec is an interface to a transparent specification of cryptographic parameters. This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.

The AlgorithmParameters Class

The AlgorithmParameters class provides an opaque representation of cryptographic parameters.

The AlgorithmParameters Class

The AlgorithmParameters class is an Engine Classes and Corresponding Service Provider Interface Classes .You can initialize the AlgorithmParameters class using a specific AlgorithmParameterSpec object, or by encoding the parameters in a recognized format. You can retrieve the resulting specification with the getParameterSpec method (see the following section).

Creating an AlgorithmParameters Object

AlgorithmParameters objects are obtained by using one of the AlgorithmParameters getInstance() static factory methods. For more information, see How Provider Implementations Are Requested and Supplied.

Initializing an AlgorithmParameters Object

Once an AlgorithmParameters object is instantiated, it must be initialized via a call to init, using an appropriate parameter specification or parameter encoding:

void init(AlgorithmParameterSpec paramSpec)
void init(byte[] params)
void init(byte[] params, String format)

In these init methods, params is an array containing the encoded parameters, and format is the name of the decoding format. In the init method with a params argument but no format argument, the primary decoding format for parameters is used. The primary decoding format is ASN.1, if an ASN.1 specification for the parameters exists.

Obtaining the Encoded Parameters

A byte encoding of the parameters represented in an AlgorithmParameters object may be obtained via a call to getEncoded:

byte[] getEncoded()

This method returns the parameters in their primary encoding format. The primary encoding format for parameters is ASN.1, if an ASN.1 specification for this type of parameters exists.

If you want the parameters returned in a specified encoding format, use

byte[] getEncoded(String format)

If format is null, the primary encoding format for parameters is used, as in the other getEncoded method.

Converting an AlgorithmParameters Object to a Transparent Specification

A transparent parameter specification for the algorithm parameters may be obtained from an AlgorithmParameters object via a call to getParameterSpec:

AlgorithmParameterSpec getParameterSpec(Class paramSpec)

paramSpec identifies the specification class in which the parameters should be returned. The specification class could be, for example, DSAParameterSpec.class to indicate that the parameters should be returned in an instance of the DSAParameterSpec class. (This class is in the java.security.spec package.)

The AlgorithmParameterGenerator Class

The AlgorithmParameterGenerator class is used to generate a set of brand-new parameters suitable for a certain algorithm (the algorithm is specified when an AlgorithmParameterGenerator instance is created).

The AlgorithmParameterGenerator Class

The AlgorithmParameterGenerator class is an Engine Classes and Corresponding Service Provider Interface Classes. This object is used when you do not have an existing set of algorithm parameters, and want to generate one from scratch.

Creating an AlgorithmParameterGenerator Object

AlgorithmParameterGenerator objects are obtained by using one of the AlgorithmParameterGenerator getInstance() static factory methods. See How Provider Implementations Are Requested and Supplied.

Initializing an AlgorithmParameterGenerator Object

The AlgorithmParameterGenerator object can be initialized in two different ways: an algorithm-independent manner or an algorithm-specific manner.

The algorithm-independent approach uses the fact that all parameter generators share the concept of a "size" and a source of randomness. The measure of size is universally shared by all algorithm parameters, though it is interpreted differently for different algorithms. For example, in the case of parameters for the DSA algorithm, "size" corresponds to the size of the prime modulus, in bits. (See Java Cryptography Architecture Standard Algorithm Name Documentation to know more about the sizes for specific algorithms.) When using this approach, algorithm-specific parameter generation values--if any--default to some standard values. One init method that takes these two universally shared types of arguments:

void init(int size, SecureRandom random);

Another init method takes only a size argument and uses a system-provided source of randomness:

void init(int size)

A third approach initializes a parameter generator object using algorithm-specific semantics, which are represented by a set of algorithm-specific parameter generation values supplied in an AlgorithmParameterSpec object:

void init(AlgorithmParameterSpec genParamSpec,
                          SecureRandom random)

void init(AlgorithmParameterSpec genParamSpec)

To generate Diffie-Hellman system parameters, for example, the parameter generation values usually consist of the size of the prime modulus and the size of the random exponent, both specified in number of bits.

The CertificateFactory Class

The CertificateFactory class defines the functionality of a certificate factory, which is used to generate certificate and certificate revocation list (CRL) objects from their encoding.

The CertificateFactory class is an Engine Classes and Corresponding Service Provider Interface Classes.

A certificate factory for X.509 must return certificates that are an instance of java.security.cert.X509Certificate, and CRLs that are an instance of java.security.cert.X509CRL.

Creating a CertificateFactory Object

CertificateFactory objects are obtained by using one of the getInstance() static factory methods. For more information, see How Provider Implementations Are Requested and Supplied.

Generating Certificate Objects

To generate a certificate object and initialize it with the data read from an input stream, use the generateCertificate method:

final Certificate generateCertificate(InputStream inStream)

To return a (possibly empty) collection view of the certificates read from a given input stream, use the generateCertificates method:

final Collection generateCertificates(InputStream inStream)

Generating CRL Objects

To generate a certificate revocation list (CRL) object and initialize it with the data read from an input stream, use the generateCRL method:

final CRL generateCRL(InputStream inStream)

To return a (possibly empty) collection view of the CRLs read from a given input stream, use the generateCRLs method:

final Collection generateCRLs(InputStream inStream)

Generating CertPath Objects

The certificate path builder and validator for PKIX is defined by the Internet X.509 Public Key Infrastructure Certificate and CRL Profile, RFC 3280.

A certificate store implementation for retrieving certificates and CRLs from Collection and LDAP directories, using the PKIX LDAP V2 Schema is also available from the IETF as RFC 2587.

To generate a CertPath object and initialize it with data read from an input stream, use one of the following generateCertPath methods (with or without specifying the encoding to be used for the data):

final CertPath generateCertPath(InputStream inStream)

final CertPath generateCertPath(InputStream inStream,
                                String encoding)

To generate a CertPath object and initialize it with a list of certificates, use the following method:

final CertPath generateCertPath(List certificates)

To retrieve a list of the CertPath encoding supported by this certificate factory, you can call the getCertPathEncodings method:

final Iterator getCertPathEncodings()

The default encoding will be listed first.

How the JCA Might Be Used in a SSL/TLS Implementation

Understand how the JCA classes, consider how these classes might be combined to implement an advanced network protocol like SSL/TLS.

The SSL/TLS Overview section in the SSL, TLS, and DTLS Protocols describes at a high level how the protocols work. As asymmetric (public key) cipher operations are much slower than symmetric operations (secret key), public key cryptography is used to establish secret keys which are then used to protect the actual application data. Vastly simplified, the SSL/TLS handshake involves exchanging initialization data, performing some public key operations to arrive at a secret key, and then using that key to encrypt further traffic.

Note:

The details presented here simply show how some of the above classes might be employed. This section will not present sufficient information for building a SSL/TLS implementation. For more information, see Java Cryptography Architecture (JCA) Reference Guide and RFC 2246: The TLS Protocol.

Assume that this SSL/TLS implementation will be made available as a JSSE provider. A concrete implementation of the Provider class is first written that will eventually be registered in the Security class' list of providers. This provider mainly provides a mapping from algorithm names to actual implementation classes. (that is: "SSLContext.TLS"->"com.foo.TLSImpl") When an application requests an "TLS" instance (via SSLContext.getInstance("TLS"), the provider's list is consulted for the requested algorithm, and an appropriate instance is created.

Before discussing details of the actual handshake, a quick review of some of the JSSE's architecture is needed. The heart of the JSSE architecture is the SSLContext. The context eventually creates end objects (SSLSocket and SSLEngine) which actually implement the SSL/TLS protocol. SSLContexts are initialized with two callback classes, KeyManager and TrustManager, which allow applications to first select authentication material to send and second to verify credentials sent by a peer.

A JSSE KeyManager is responsible for choosing which credentials to present to a peer. Many algorithms are possible, but a common strategy is to maintain a RSA or DSA public/private key pair along with a X509Certificate in a KeyStore backed by a disk file. When a KeyStore object is initialized and loaded from the file, the file's raw bytes are converted into PublicKey and PrivateKey objects using a KeyFactory, and a certificate chain's bytes are converted using a CertificateFactory. When a credential is needed, the KeyManager simply consults this KeyStore object and determines which credentials to present.

A KeyStore's contents might have originally been created using a utility such as keytool. keytool creates a RSA or DSA KeyPairGenerator and initializes it with an appropriate keysize. This generator is then used to create a KeyPair which keytool would store along with the newly-created certificate in the KeyStore, which is eventually written to disk.

A JSSE TrustManager is responsible for verifying the credentials received from a peer. There are many ways to verify credentials: one of them is to create a CertPath object, and let the JDK's built-in Public Key Infrastructure (PKI) framework handle the validation. Internally, the CertPath implementation might create a Signature object, and use that to verify that the each of the signatures in the certificate chain.

With this basic understanding of the architecture, we can look at some of the steps in the SSL/TLS handshake. The client begins by sending a ClientHello message to the server. The server selects a ciphersuite to use, and sends that back in a ServerHello message, and begins creating JCA objects based on the suite selection. We'll use server-only authentication in the following examples.

Figure 5-17 SSL/TLS Messages

Description of Figure 5-17 follows
Description of "Figure 5-17 SSL/TLS Messages"

Server-only authentication is described in the following examples. The examples are vastly simplified, but gives an idea of how the JSSE classes might be combined to create a higher level protocol:

Example 5-9 SSL/TLS Server Uses a RSA-based ciphersuite Such as TLS_RSA_WITH_AES_128_CBC_SHA

The server's KeyManager is queried, and returns an appropriate RSA entry. The server's credentials (that is: certificate/public key) are sent in the server's Certificate message. The client's TrustManager verifies the server's certificate, and if accepted, the client generates some random bytes using a SecureRandom object. This is then encrypted using an encrypting asymmetric RSA Cipher object that has been initialized with the PublicKey found in the server's certificate. This encrypted data is sent in a Client Key Exchange message. The server would use its corresponding PrivateKey to recover the bytes using a similar Cipher in decrypt mode. These bytes are then used to establish the actual encryption keys.

Example 5-10 Choose an Ephemeral Diffie-Hellman Key Agreement Algorithm Along with the DSA Signature Algorithm such as TLS_DHE_DSS_WITH_AES_128_CBC_SHA

The two sides must each establish a new temporary DH public/private keypair using a KeyPairGenerator. Each generator creates DH keys which can then be further converted into pieces using the KeyFactory and DHPublicKeySpec classes. Each side then creates a KeyAgreement object and initializes it with their respective DH PrivateKeys. The server sends its public key pieces in a ServerKeyExchange message (protected by the DSA signature algorithm, and the client sends its public key in a ClientKeyExchange message. When the public keys are reassembled using another KeyFactory, they are fed into the agreement objects. The KeyAgreement objects then generate agreed-upon bytes that are then used to establish the actual encryption keys.

Once the actual encryption keys have been established, the secret key is used to initialize a symmetric Cipher object, and this cipher is used to protect all data in transit. To help determine if the data has been modified, a MessageDigest is created and receives a copy of the data destined for the network. When the packet is complete, the digest (hash) is appended to data, and the entire packet is encrypted by the Cipher. If a block cipher such as AES is used, the data must be padded to make a complete block. On the remote side, the steps are simply reversed.

How the JCA Might Be Used in a DTLS Implementation

Understand how the JCA classes are used in a DTLS implementation, consider how these classes might be combined to implement an advanced network protocol like DTLS.

Datagram Transport Layer Security (DTLS) describes at a high level how the protocol works. As asymmetric (public key) cipher operations are much slower than symmetric operations (secret key), public key cryptography is used to establish secret keys which are then used to protect the actual application data. Vastly simplified, the DTLS handshake involves exchanging initialization data, performing some public key operations to arrive at a secret key, and then using that key to encrypt further traffic.

Note:

The details presented here simply show how some of the above classes might be employed. This section will not present sufficient information for building a DTLS implementation. See Java Cryptography Architecture (JCA) Reference Guide, DTLS Version 1.0, and DTLS Version 1.2.

Assume that DTLS implementation will be made available as a JSSE provider. A concrete implementation of the Provider class is first written that will eventually be registered in the Security class' list of providers. This provider mainly provides a mapping from algorithm names to actual implementation classes. When an application requests an "DTLS" instance (via SSLContext.getInstance("DTLS"), the provider's list is consulted for the requested algorithm, and an appropriate instance is created.

Before discussing details of the actual handshake, a quick review of some of the JSSE's architecture is needed. The heart of the JSSE architecture is the SSLContext. The context eventually creates end objects (SSLSocket and SSLEngine) which actually implement the DTLS protocol. SSLContexts are initialized with two callback classes, KeyManager and TrustManager, which allow applications to first select authentication material to send and second to verify credentials sent by a peer.

A JSSE KeyManager is responsible for choosing which credentials to present to a peer. Many algorithms are possible, but a common strategy is to maintain a RSA or DSA public/private key pair along with a X509Certificate in a KeyStore backed by a disk file. When a KeyStore object is initialized and loaded from the file, the file's raw bytes are converted into PublicKey and PrivateKey objects using a KeyFactory, and a certificate chain's bytes are converted using a CertificateFactory. When a credential is needed, the KeyManager simply consults this KeyStore object and determines which credentials to present.

A KeyStore's contents might have originally been created using a utility such as keytool. keytool creates a RSA or DSA KeyPairGenerator and initializes it with an appropriate keysize. This generator is then used to create a KeyPair which keytool would store along with the newly-created certificate in the KeyStore, which is eventually written to disk.

A JSSE TrustManager is responsible for verifying the credentials received from a peer. There are many ways to verify credentials: one of them is to create a CertPath object, and let the JDK's built-in Public Key Infrastructure (PKI) framework handle the validation. Internally, the CertPath implementation might create a Signature object, and use that to verify that the each of the signatures in the certificate chain.

The following example describes the procedure to get a DTLS context:

Example 5-11 Sample Code to Get DTLS Context

// Get DTLS context

    SSLContext getDTLSContext() throws Exception {

        KeyStore ks = KeyStore.getInstance("JKS");

        KeyStore ts = KeyStore.getInstance("JKS");

        char[] passphrase = "passphrase".toCharArray();

        ks.load(new FileInputStream(keyFilename), passphrase);

        ts.load(new FileInputStream(trustFilename), passphrase);

        /*KeyManagerFactory.getInstance() traverses the list of registered security Providers,
          starting with the most preferred Provider.*/

        /*A new KeyManagerFactory object encapsulating the KeyManagerFactorySpi implementation
          from the first Provider that supports the specified algorithm is returned.*/

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

        kmf.init(ks, passphrase);

        /*The TrustManagerFactory.getInstance() method traverses the list of registered
          security Providers, starting with the most preferred Provider.*/
       
        /*A new TrustManagerFactory object encapsulating the TrustManagerFactorySpi
         implementation from the first Provider that supports the specified algorithm is returned.*/

              TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

        tmf.init(ts);

        //Get the DTLS instance
        SSLContext sslCtx = SSLContext.getInstance("DTLS");

        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslCtx;

    }

With this basic understanding of the architecture, we can look at some of the steps in the DTLS handshake. The client begins by sending a ClientHello message to the server. The server selects a ciphersuite to use, and sends that back in a ServerHello message, and begins creating JCA objects based on the suite selection.

Server-only authentication is described in the following examples. The examples are vastly simplified, but gives an idea of how the JSSE classes might be combined to create a higher level protocol:

Example 5-12 DTLS Server Uses a RSA-Based Ciphersuite

The server's KeyManager is queried, and returns an appropriate RSA entry. The server's credentials (that is: certificate/public key) are sent in the server's Certificate message. The client's TrustManager verifies the server's certificate, and if accepted, the client generates some random bytes using a SecureRandom object. This is then encrypted using an encrypting asymmetric RSA Cipher object that has been initialized with the PublicKey found in the server's certificate. This encrypted data is sent in a Client Key Exchange message. The server would use its corresponding PrivateKey to recover the bytes using a similar Cipher in decrypt mode. These bytes are then used to establish the actual encryption keys.

Example 5-13 Choose an Ephemeral Diffie-Hellman Key Agreement Algorithm

The two sides must each establish a new temporary DH public/private keypair using a KeyPairGenerator. Each generator creates DH keys which can then be further converted into pieces using the KeyFactory and DHPublicKeySpec classes. Each side then creates a KeyAgreement object and initializes it with their respective DH PrivateKeys. The server sends its public key pieces in a ServerKeyExchange message (protected by the DSA signature algorithm, and the client sends its public key in a ClientKeyExchange message. When the public keys are reassembled using another KeyFactory, they are fed into the agreement objects. The KeyAgreement objects then generate agreed-upon bytes that are then used to establish the actual encryption keys.

Once the actual encryption keys have been established, the secret key is used to initialize a symmetric Cipher object, and this cipher is used to protect all data in transit. To help determine if the data has been modified, a MessageDigest is created and receives a copy of the data destined for the network. When the packet is complete, the digest (hash) is appended to data, and the entire packet is encrypted by the Cipher. If a block cipher such as AES is used, the data must be padded to make a complete block. On the remote side, the steps are simply reversed.

How to Make Applications Exempt from Cryptographic Restrictions

The Java SE Development Kit 9 is shipped with unlimited strength policy files indicating no restrictions on cryptographic strengths is available by default. However the JCA framework 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".

Attention:

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 is desired that such applications have fewer cryptographic restrictions than those mandated.

Note:

Throughout this section, the term "application" is meant to encompass both applications and applets.

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files "strong" but limited cryptography version can be imported and used. The "strong" version can be imported into those countries whose governments mandate restrictions. The JCA 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:

  • 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).
  • The JAR file containing the application and the permission policy file must have been signed using a code-signing certificate issued after the application was accepted as exempt.

Below are sample steps required in order to make an application exempt from some cryptographic restrictions. This is a basic outline that includes information about what is required by JCA 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 JCA 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
  1. Write and Compile Your Application Code
  2. Create a Permission Policy File Granting Appropriate Cryptographic Permissions
  3. Prepare for Testing
    1. Apply for Government Approval From the Government Mandating Restrictions.
    2. Get a Code-Signing Certificate
    3. Bundle the Application and Permission Policy File into a JAR file
    4. Step 6.1: Get a Code-Signing Certificate
    5. Set Up Your Environment Like That of a User in a Restricted Country
    6. (only for applications using exemption mechanisms) Install a Provider Implementing the Exemption Mechanism Specified by the entry in the Permission Policy File
  4. Test Your Application
  5. Apply for U.S. Government Export Approval If Required
  6. Deploy Your Application

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 JCA code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCA 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).

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, which is:

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

See Appendix B: 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, JCA 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.

Steps to Implement and Integrate a Provider

Follow the steps to implement a provider and integrate it into the JCA framework:

Step 1: Write your Service Implementation Code

The first thing you need to do is to write the code that provides algorithm-specific implementations of the cryptographic services you want to support.

Note:

Your provider may supply implementations of cryptographic services already available in one or more of the security components of the JDK.

For cryptographic services not defined in JCA (For example; signatures and message digests), refer to Engine Classes and Corresponding Service Provider Interface Classes.

For each cryptographic service you wish to implement, create a subclass of the appropriate SPI class. JCA defines the following engine classes:

  • SignatureSpi
  • MessageDigestSpi
  • KeyPairGeneratorSpi
  • SecureRandomSpi
  • AlgorithmParameterGeneratorSpi
  • AlgorithmParametersSpi
  • KeyFactorySpi
  • CertificateFactorySpi
  • KeyStoreSpi
  • CipherSpi
  • KeyAgreementSpi
  • KeyGeneratorSpi
  • MacSpi
  • SecretKeyFactorySpi
  • ExemptionMechanismSpi

To know more about the JCA and other cryptographic classes, see Engine Classes and Corresponding Service Provider Interface Classes.

In the subclass, you need to:

  1. Supply implementations for the abstract methods, whose names usually begin with engine. See Further Implementation Details and Requirements.
  2. Ensure there is a public constructor without any arguments. Here's why: When one of your services is requested, Java Security looks up the subclass implementing that service, as specified by a property in your "master class" (see Step 3: Write your Master Class, a subclass of Provider). Java Security then creates the Class object associated with your subclass, and creates an instance of your subclass by calling the newInstance method on that Class object. newInstance requires your subclass to have a public constructor without any parameters.
  3. A default constructor without arguments will automatically be generated if your subclass doesn't have any constructors. But if your subclass defines any constructors, you must explicitly define a public constructor without arguments.

Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations

When instantiating a provider's implementation (class) of a Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory, the framework will determine the provider's codebase (JAR file) and verify its signature. In this way, JCA authenticates the provider and ensures that only providers signed by a trusted entity can be plugged into JCA. Thus, one requirement for encryption providers is that they must be signed, as described in later steps.

In addition, each provider should perform self-integrity checking to ensure that the JAR file containing its code has not been manipulated in an attempt to invoke provider methods directly rather than through JCA. See How a Provider Can Do Self-Integrity Checking.

In order for provider classes to become unusable if instantiated by an application directly, bypassing JCA, providers should implement the following:

  • All SPI implementation classes in a provider package should be declared final (so that they cannot be subclassed), and their (SPI) implementation methods should be declared protected.
  • All crypto-related helper classes in a provider package should have package-private scope, so that they cannot be accessed from outside the provider package.

For providers that may be exported outside the U.S., CipherSpi implementations must include an implementation of the engineGetKeySize method which, given a Key, returns the key size. If there are restrictions on available cryptographic strength specified in jurisdiction policy files, each Cipher initialization method calls engineGetKeySize and then compares the result with the maximum allowable key size for the particular location and circumstances of the applet or application being run. If the key size is too large, the initialization method throws an exception.

Additional optional features that providers may implement are:

  • Optional: The engineWrap and engineUnwrap methods of CipherSpi. Wrapping a key enables secure transfer of the key from one place to another. Information about wrapping and unwrapping keys is provided in the wrap.
  • Optional: One or more exemption mechanisms. An exemption mechanism is something such as key recovery, key escrow, or key weakening which, if implemented and enforced, may enable reduced cryptographic restrictions for an application (or applet) that uses it. To know more about the requirements for apps that utilize exemption mechanisms, see How to Make Applications Exempt from Cryptographic Restrictions.

Step 2: Give your Provider a Name

Provide a name to be used by client applications.

Decide on a name for your provider. This is the name to be used by client applications to refer to your provider.

Step 3: Write your Master Class, a subclass of Provider

Create a subclass of the java.security.Provider class.

Your subclass should be a final class, and its constructor should perform the following:
  • Call super, specifying the provider name (see Step 2: Give your Provider a Name) version number, and a string of information about the provider and algorithms it supports.
        super("CryptoX", 1.0, "CryptoX provider v1.0, implementing " +
            "RSA encryption and key pair generation, and DES encryption.");
    
  • Set the values of various properties that are required for the Java Security API to look up the cryptographic services implemented by the provider.
    For each service implemented by the provider, there must be a property whose name is the type of service followed by a period and the name of the algorithm to which the service applies. The property value must specify the fully qualified name of the class implementing the service.
    For example, Signature, MessageDigest, Cipher, KeyAgreement) Signature, MessageDigest, KeyPairGenerator, SecureRandom, KeyFactory, KeyStore, CertificateFactory, AlgorithmParameterGenerator, AlgorithmParameters, Cipher, KeyAgreement, KeyGenerator, Mac, SecretKeyFactory, or ExemptionMechanism)
  • The list below shows the various types of JCA services, where the actual algorithm name is substituted for algName:

    The value of each property must be the fully qualified name of the class implementing the specified algorithm, certificate type, or keystore type. That is, it must be the package name followed by the class name, where the two are separated by a period.

    • Signature.algName
    • MessageDigest.algName
    • KeyPairGenerator.algName
    • SecureRandom.algName
    • AlgorithmParameterGenerator.algName
    • AlgorithmParameters.algName
    • KeyFactory.algName
    • CertificateFactory.algName
    • KeyStore.algName
    • Cipher.algName
    • KeyAgreement.algName
    • KeyGenerator.algName
    • Mac.algName
    • SecretKeyFactory.algName
    • ExemptionMechanism.algName
    • In all of these except ExemptionMechanism and Cipher, algName, certType , or storeType is the "standard" name of the algorithm, certificate type, or keystore type. See Java Cryptography Architecture Standard Algorithm Name Documentation for the standard names that should be used.)

    • In the case of ExemptionMechanism, algName refers to the name of the exemption mechanism, which can be one of the following: KeyRecovery, KeyEscrow, or KeyWeakening. Case does not matter.

    • In the case of Cipher, algName may actually represent a transformation, and may be composed of an algorithm name, a particular mode, and a padding scheme. See Java Cryptography Architecture Standard Algorithm Name Documentation.

    • The value of each property must be the fully qualified name of the class implementing the specified algorithm, certificate type, or keystore type. That is, it must be the package name followed by the class name, where the two are separated by a period.

    As an example, the default provider named SUN implements the Digital Signature Algorithm (whose standard name is SHA1withDSA) in a class named DSA in the sun.security.provider package. Its subclass of Provider (which is the Sun class in the sun.security.provider package) sets the Signature.SHA1withDSA property to have the value sun.security.provider.DSA via the following:

        put("Signature.SHA1withDSA", "sun.security.provider.DSA")
    
  • The list below shows more properties that can be defined for the various types of services, where the actual algorithm name is substituted for algName, certificate type for certType, keystore type for storeType, and attribute name for attrName:
    • Signature.algName [one or more spaces] attrName
    • MessageDigest.algName [one or more spaces] attrName
    • KeyPairGenerator.algName [one or more spaces] attrName
    • SecureRandom.algName [one or more spaces] attrName
    • KeyFactory.algName [one or more spaces] attrName
    • CertificateFactory.certType [one or more spaces] attrName
    • KeyStore.storeType [one or more spaces] attrName
    • AlgorithmParameterGenerator.algName [one or more spaces] attrName
    • AlgorithmParameters.algName [one or more spaces] attrName
    • Cipher.algName [one or more spaces] attrName
    • KeyAgreement.algName [one or more spaces] attrName
    • KeyGenerator.algName [one or more spaces] attrName
    • Mac.algName [one or more spaces] attrName
    • SecretKeyFactory.algName [one or more spaces] attrName
    • ExemptionMechanism.algName [one or more spaces] attrName

    In each of these, algName, certType, storeType, or attrName is the "standard" name of the algorithm, certificate type, keystore type, or attribute. (See Java Cryptography Architecture Standard Algorithm Name Documentation for the standard names that should be used.)

    For a property in the above format, the value of the property must be the value for the corresponding attribute. (See Java Cryptography Architecture Standard Algorithm Name Documentation for the definition of each standard attribute.)

    For further master class property setting examples, see Appendix D: The Sun Provider Master Class to view the current Sun.java source file or Appendix E: The SunJCE Provider Master Class to see the SunJCE provider. These files show how the Sun and SunJCE providers set properties.

    As an example, the default provider named "SUN" implements the SHA1withDSA Digital Signature Algorithm in software. In the master class for the provider "SUN", it sets the Signature.SHA1withDSA ImplementedIn to have the value Software via the following:

        put("Signature.SHA1withDSA ImplementedIn", "Software")
    

Step 3.1: Additional Steps for Cipher Implementations

As mentioned above, in the case of a Cipher property, algName may actually represent a transformation. A transformation is a string that describes the operation (or set of operations) to be performed by a Cipher object on some given input. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a mode and a padding scheme.

A transformation is of the form:

  • algorithm/mode/padding, or
  • algorithm

(In the latter case, provider-specific default values for the mode and padding scheme are used). For example, the following is a valid transformation:

    Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
When requesting a block cipher in stream cipher mode (for example; DES in CFB or OFB mode), a client 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 following sample transformations:
    Cipher c1 = Cipher.getInstance("DES/CFB8/NoPadding");
    Cipher c2 = Cipher.getInstance("DES/OFB32/PKCS5Padding");

If a number does not follow a stream cipher mode, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits.)

A provider may supply a separate class for each combination of algorithm/mode/padding. Alternatively, a provider may decide to provide more generic classes representing sub-transformations corresponding to algorithm or algorithm/mode or algorithm//padding (note the double slashes); in this case the requested mode and/or padding are set automatically by the getInstance methods of Cipher, which invoke the engineSetMode and engineSetPadding methods of the provider's subclass of CipherSpi.

That is, a Cipher property in a provider master class may have one of the formats shown in the table below.

Table 5-1 Cipher Property Format

Cipher Property Format Description
Cipher.algName A provider's subclass of CipherSpi implements algName with pluggable mode and padding
Cipher.algName/mode A provider's subclass of CipherSpi implements algName in the specified mode, with pluggable padding
Cipher.algName//padding A provider's subclass of CipherSpi implements algName with the specified padding, with pluggable mode
Cipher.algName/mode/padding A provider's subclass of CipherSpi implements algName with the specified mode and padding

(See Java Cryptography Architecture Standard Algorithm Name Documentation for the standard algorithm names, modes, and padding schemes that should be used.)

For example, a provider may supply a subclass of CipherSpi that implements DES/ECB/PKCS5Padding, one that implements DES/CBC/PKCS5Padding, one that implements DES/CFB/PKCS5Padding, and yet another one that implements DES/OFB/PKCS5Padding. That provider would have the following Cipher properties in its master class:

  • Cipher.DES/ECB/PKCS5Padding
  • Cipher.DES/CBC/PKCS5Padding
  • Cipher.DES/CFB/PKCS5Padding
  • Cipher.DES/OFB/PKCS5Padding

Another provider may implement a class for each of the above modes (i.e., one class for ECB, one for CBC, one for CFB, and one for OFB), one class for PKCS5Padding, and a generic DES class that subclasses from CipherSpi. That provider would have the following Cipher properties in its master class:

  • Cipher.DES
  • Cipher.DES SupportedModes Example: "ECB|CBC|CFB|OFB"
  • Cipher.DES SupportedPaddings Example: "NOPADDING|PKCS5Padding"
The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm":
  1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm".
    • If the answer is YES, instantiate this class, for whose mode and padding scheme default values (as supplied by the provider) are used.
    • If the answer is NO, throw a NoSuchAlgorithmException exception.
  2. The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm/mode/padding":
    1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm/mode/padding" transformation.
      • If the answer is YES, instantiate it.

      • If the answer is NO, go to the next step.

    2. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm/mode".
      • If the answer is YES, instantiate it, and call engineSetPadding(padding) on the new instance.

      • If the answer is NO, go to the next step.

    3. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm//padding" (note the double slashes)
      • If the answer is YES, instantiate it, and call engineSetMode(mode) on the new instance.

      • If the answer is NO, go to the next step.

    4. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm".
      • If the answer is YES, instantiate it, and call engineSetMode(mode) and engineSetPadding(padding) on the new instance.

      • If the answer is NO, throw a NoSuchAlgorithmException exception.

Step 4: Compile your Code

Compile your files using the Java compiler.

After you have created your implementation code (Step 1: Write your Service Implementation Code), given your provider a name (Step 2: Give your Provider a Name), and created the master class (Step 3: Write your Master Class, a subclass of Provider), use the Java compiler to compile your files.

Step 5: Place Your Provider in a JAR File

Place your provider code in a JAR file, in preparation for signing it in the next step.

See jar in the Java Platform, Standard Edition Tools Reference for Oracle JDK.

    jar cvf <JAR file name> <list of classes, separated by spaces>

This command creates a JAR file with the specified name containing the specified classes.

Step 6: Sign your JAR File

If your provider is supplying encryption algorithms through the Cipher KeyAgreement, KeyGenerator, Mac, or SecretKeyFactory classes, you will need to sign your JAR file so that the JCA can authenticate the code at runtime.

See Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations. If you are NOT providing an implementation of this type you can skip this step.

Step 6.1: Get a Code-Signing Certificate

The next step is to request a code-signing certificate so that you can use it to sign your provider prior to testing. The certificate will be good for both testing and production. It will be valid for 5 years.

Below are the steps you should use to get a code-signing certificate. See keytoolin the Java Platform, Standard Edition Tools Reference for Oracle JDK.

  1. Use keytool to generate a DSA keypair, using DSA algorithm as an example:
        keytool -genkeypair -alias <alias> \
            -keyalg DSA -keysize 1024 \
            -dname "cn=<Company Name>, \
            ou=Java Software Code Signing,\
            o=Sun Microsystems Inc" \
            -keystore <keystore file name>\
            -storepass <keystore password>
            
    

    This will generate a DSA keypair (a public key and an associated private key) and store it in an entry in the specified keystore. The public key is stored in a self-signed certificate. The keystore entry can subsequently be accessed using the specified alias.

    The option values in angle brackets ("<" and ">") represent the actual values that must be supplied. For example, <alias> must be replaced with whatever alias name you wish to be used to refer to the newly-generated keystore entry in the future, and <keystore file name> must be replaced with the name of the keystore to be used.

    Tip:

    Do not surround actual values with angle brackets. For example, if you want your alias to be myTestAlias, specify the -alias option as follows:
        -alias myTestAlias
    
    If you specify a keystore that doesn't yet exist, it will be created.

    Note:

    If command lines you type are not allowed to be as long as the keytool -genkeypair command you want to execute (for example, if you are typing to a Microsoft Windows DOS prompt), you can create and execute a plain-text batch file containing the command. That is, create a new text file that contains nothing but the full keytool -genkeypair command. (Remember to type it all on one line.) Save the file with a .bat extension. Then in your DOS window, type the file name (with its path, if necessary). This will cause the command in the batch file to be executed.
  2. Use keytool to generate a certificate signing request.
        keytool -certreq -alias <alias> \
            -file <csr file name> \
            -keystore <keystore file name> \
            -storepass <keystore password> 
    
    Here, <alias> is the alias for the DSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in <csr file name>.
  3. Send the CSR, contact information, and other required documentation to the JCA Code Signing Certification Authority. See JCA Code Signing Certification Authority for contact information.
  4. After the JCA Code Signing Certification Authority has received your email message, they will send you a request number via email. Once you receive this request number, you should print, fill out and send the Certification Form for CSPs. See Sending Certification Form for CSPs for contact information.
  5. Use keytool to import the certificates received from the CA.
    Once you have received the two certificates from the JCA Code Signing Certification Authority, you can use keytool to import them into your keystore. First import the CA's certificate as a "trusted certificate":
        keytool -import -alias <alias for the CA cert> \
            -file <CA cert file name> \
            -keystore <keystore file name> \
            -storepass <keystore password>
    
    Then import the code-signing certificate:
        keytool -import -alias <alias> \
            -file <code-signing cert file name> \
            -keystore <keystore file name> \
            -storepass <keystore password>
    
    <alias>
    Is the same alias as that which you created in Step 1: Write your Service Implementation Code where you generated a DSA keypair. This command replaces the self-signed certificate in the keystore entry specified by <alias> with the one signed by the JCA Code Signing Certification Authority.

    Now that you have in your keystore a certificate from an entity trusted by JCA (the JCA Code Signing Certification Authority), you can place your provider code in a JAR file (Step 5: Place Your Provider in a JAR File) and then use that certificate to sign the JAR file (Step 6.2: Sign Your Provider).

Step 6.2: Sign Your Provider

Sign the JAR file created with the code-signing certificate.

Sign the JAR file created in Step 5: Place Your Provider in a JAR File and Step 6: Sign your JAR File with the code-signing certificate obtained in Step 6: Sign your JAR File. See jarsigner in the Java Platform, Standard Edition Tools Reference for Oracle JDK.

    jarsigner -keystore <keystore file name> \
        -storepass <keystore password> \
        <JAR file name> <alias>

Here, <alias> is the alias into the keystore for the entry containing the code-signing certificate received from the JCA Code Signing Certification Authority (the same alias as that specified in the commands in Step 6.1: Get a Code-Signing Certificate).

You can test verification of the signature via the following:

    jarsigner -verify <JAR file name> 

The text "jar verified" will be displayed if the verification was successful.

Note:

If you bundle a signed JCE provider as part of an RIA (applet or webstart application), for the best user experience, you should apply a second signature to the JCE provider JAR with the same certificate/key that you used to sign the applet or webstart application. See Deployment Configuration File and Properties to know about deploying RIAs, and jarsigner in the Java Platform, Standard Edition Tools Reference for Oracle JDK for applying multiple signatures to a JAR file.

Step 7: Prepare for Testing

The next steps describe how to install and configure your new provider so that it is available via the JCA.

Step 7.1: Install the Provider

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider.

In order to prepare for testing your provider, you must install it in the same manner as will be done by clients wishing to use it. The installation enables Java Security to find your algorithm implementations when clients request them.

The first thing you must do is make your classes available so that they can be found when requested. To do this ship your provider classes as a JAR (Java ARchive) file and place the JAR file containing the provider classes in your CLASSPATH.

Configuring the Provider

Add the provider to your list of approved providers.

  1. Edit the security properties file statically.
    1. Solaris, Linux, or macOS: <java-home>/conf/security/java.security
    2. Windows: <java-home>\conf\security\java.security
    <java-home>
    Refers to the directory where the JRE was installed.
    For example, if you have the JDK installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jdk, or on Microsoft Windows in a directory named C:\jdk, then you need to edit the following file:
    • Solaris, Linux, or macOS: /home/user1/jdk/conf/security/java.security
    • Windows: C:\jdk\conf\security\java.security

    Similarly, if you have the JDK is installed on Solaris, Linux, or Mac OS X in a directory named /home/user1/jdk, or on Windows in a directory named C:\jdk, then you need to edit this file:

    • Solaris, Linux, or macOS: /home/user1/jdk/conf/security/java.security
    • Windows: C:\jdk\conf\security\java.security
  2. 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
    Specify the fully qualified name of the provider's "master class", which you implemented in Step 3: Write your Master Class, a subclass of Provider. This class is always a subclass of the Provider class.
  3. Java comes standard with providers named SUN, SunRsaSign, and SunJCE which are automatically configured as a static provider in the java.security properties file, as follows:
        security.provider.2=sun.security.provider.Sun
        security.provider.3=sun.security.rsa.SunRsaSign
        security.provider.4=sun.security.provider.SunJCE
    

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

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

    To utilize another JCA provider, add a line registering the alternate provider, giving it a lower preference order than the SUN and SunRsaSign providers.

    Suppose that your master class is the CryptoX class in the com.cryptox.provider package, and that you would like to make your provider the fourth preferred provider. To do so, edit the java.security file as seen below:

        security.provider.2=sun.security.provider.Sun
        security.provider.3=sun.security.rsa.SunRsaSign
        security.provider.4=com.cryptox.provider.CryptoX
        security.provider.5=sun.security.provider.SunJCE
    

    Note:

    Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 8: Write and Compile your Test Programs) 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}"
    
    {name}
    Provide the actual provider name.

    For example, if the provider name is "MyJCE" and if the provider's code is in the myjce_provider.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:

        grant codeBase "file:/localWork/myjce_provider.jar" {
            permission java.security.SecurityPermission
                "insertProvider.MyJCE";
        };
    

Step 7.2: Set Provider Permissions

Providers are not installed extensions. Permissions do not need to be granted to installed extensions.

Whenever providers are not installed extensions, Permissions must be granted for when applets or applications 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 Default Policy Implementation and Policy File Syntax grants all permissions to installed extensions.

  1. Whenever a client does not install your provider as an installed extension, your provider may need the following permissions granted to it in the client environment:
    • java.lang.RuntimePermission to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
    • java.security.SecurityPermission to set provider properties.
  2. To ensure your provider works when a security manager is installed and the provider is not an installed extension, you need to test such an installation and execution environment. In addition, prior to testing your need to grant appropriate permissions to your provider and to any other providers it uses.

    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";
        };
    

Step 8: Write and Compile your Test Programs

Write and compile one or more test programs that test your provider's incorporation into the Security API as well as the correctness of its algorithm(s). Create any supporting files needed, such as those for test data to be encrypted.

  1. The first tests your program should perform are ones to ensure that your provider is found, and that its name, version number, and additional information is as expected.
    To do so, you could write code like the following, substituting your provider name for MyPro:
        import java.security.*;
    
        Provider p = Security.getProvider("MyPro");
    
        System.out.println("MyPro provider name is " + p.getName());
        System.out.println("MyPro provider version # is " + p.getVersion());
        System.out.println("MyPro provider info is " + p.getInfo());
    
  2. You should ensure that your services are found.
    For instance, if you implemented the DES encryption algorithm, you could check to ensure it's found when requested by using the following code (again substituting your provider name for "MyPro"):
        Cipher c = Cipher.getInstance("DES", "MyPro");
    
        System.out.println("My Cipher algorithm name is " + c.getAlgorithm());
    
  3. Optional: If you don't specify a provider name in the call to getInstance, all registered providers will be searched, in preference order (see Configuring the Provider), until one implementing the algorithm is found.
  4. Optional: If your provider implements an exemption mechanism, you should write a test applet or application that uses the exemption mechanism. Such an applet/application also needs to be signed, and needs to have a "permission policy file" bundled with it.
    See How to Make Applications Exempt from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide for complete information on creating and testing such an application.

Step 9: Run your Test Programs

Run your test program(s). Debug your code and continue testing as needed. If the Java Security API cannot seem to find one of your algorithms, review the steps above and ensure they are all completed.

Be sure to include testing of your programs using different installation options (e.g. making the provider an installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 7.1: Install the Provider.

In particular, you need to ensure your provider works when a security manager is installed and the provider is not an installed extension and thus the provider must have permissions granted to it; therefore, you need to test such an installation and execution environment, after granting required permissions to your provider and to any other providers it uses, as described in Step 7.2: Set Provider Permissions.

  1. Optional: If you find during testing that your code needs modification, make the changes, recompile Step 4: Compile your Code.
  2. Place the updated provider code in a JAR file (Step 6: Sign your JAR File).
  3. Sign the JAR file if necessary (Step 6.2: Sign Your Provider).
  4. Re-install the provider (Step 7.1: Install the Provider).
  5. Optional: If needed fix or add to the permissions (Step 7.2: Set Provider Permissions).
  6. Re-test your programs.
  7. Optional: If required repeat steps 1 to 6 .

Step 10: Apply for U.S. Government Export Approval If Required

All U.S. vendors whose providers may be exported outside the U.S. should apply to the Bureau of Industry and Security in the U.S. Department of Commerce for export approval.

Please consult your export counsel for more information.

Note:

If your provider calls Cipher.getInstance() and the returned Cipher object needs to perform strong cryptography regardless of what cryptographic strength is allowed by the user's downloaded jurisdiction policy files, you should include a copy of the cryptoPerms permission policy file which you intend to bundle in the JAR file for your provider and which specifies an appropriate permission for the required cryptographic strength. The necessity for this file is just like the requirement that applets and applications "exempt" from cryptographic restrictions must include a cryptoPerms permission policy file in their JAR file. See How to Make Applications Exempt from Cryptographic Restrictions.

Here are two URLs that may be useful:

Step 11: Document your Provider and its Supported Services

Procedure to documentation for your provider and supported services.

The next step is to write documentation for your clients. At the minimum, you need to specify:
  • The name programs should use to refer to your provider.

    Note:

    As of this writing, provider name searches are case-sensitive. That is, if your master class specifies your provider name as "CryptoX" but a user requests "CRYPTOx", your provider will not be found. This behavior may change in the future, but for now be sure to warn your clients to use the exact case you specify.
  • The types of algorithms and other services implemented by your provider.
  • Instructions for installing the provider, similar to those provided in Step 7.1: Install the Provider, except that the information and examples should be specific to your provider.
  • The permissions your provider will require if it is not installed as an installed extension and if a security manager is run, as described in Step 7.2: Set Provider Permissions.
In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.

Message Digests and MACs

For each Message Digest and MAC algorithm, indicate whether or not your implementation is cloneable. This is not technically necessary, but it may save clients some time and coding by telling them whether or not intermediate Message Digests or MACs may be possible through cloning.

Clients who do not know whether or not a MessageDigest or Mac implementation is cloneable can find out by attempting to clone the object and catching the potential exception, as illustrated by the following example:

    try {
        // try and clone it
        /* compute the MAC for i1 */
        mac.update(i1);
        byte[] i1Mac = mac.clone().doFinal();

        /* compute the MAC for i1 and i2 */
        mac.update(i2);
        byte[] i12Mac = mac.clone().doFinal();

        /* compute the MAC for i1, i2 and i3 */
        mac.update(i3);
        byte[] i123Mac = mac.doFinal();
    } catch (CloneNotSupportedException cnse) {
        // have to use an approach not involving cloning
    } 

Where,

mac
Indicates the MAC object they received when they requested one via a call to Mac.getInstance
i1, i2 and i3
Indicates input byte arrays, and they want to calculate separate hashes for:
  • i1
  • i1 and i2
  • i1, i2, and i3

Key Pair Generators

For a key pair generator algorithm, in case the client does not explicitly initialize the key pair generator (via a call to an initialize method), each provider must supply and document a default initialization.

For example, the Diffie-Hellman key pair generator supplied by the SunJCE provider uses a default prime modulus size (keysize) of 2048 bits.

Key Factories

A provider should document all the key specifications supported by its (secret-)key factory.

Algorithm Parameter Generators

In case the client does not explicitly initialize the algorithm parameter generator (via a call to an init method in the AlgorithmParameterGenerator engine class), each provider must supply and document a default initialization.

For example, the SunJCE provider uses a default prime modulus size (keysize) of 2048 bits for the generation of Diffie-Hellman parameters, the Sun provider a default modulus prime size of 1024 bits for the generation of DSA parameters.

Signature Algorithms

If you implement a signature algorithm, you should document the format in which the signature (generated by one of the sign methods) is encoded.

For example, the SHA1withDSA signature algorithm supplied by the "SUN" provider encodes the signature as a standard ASN.1 SEQUENCE of two integers, r and s.

Random Number Generation (SecureRandom) Algorithms

For a random number generation algorithm, provide information regarding how "random" the numbers generated are, and the quality of the seed when the random number generator is self-seeding. Also note what happens when a SecureRandom object (and its encapsulated SecureRandomSpi implementation object) is deserialized: If subsequent calls to the nextBytes method (which invokes the engineNextBytes method of the encapsulated SecureRandomSpi object) of the restored object yield the exact same (random) bytes as the original object would, then let users know that if this behavior is undesirable, they should seed the restored random object by calling its setSeed method.

Certificate Factories

A provider should document what types of certificates (and their version numbers, if relevant), can be created by the factory.

Keystores

A provider should document any relevant information regarding the keystore implementation, such as its underlying data format.

Step 12: Make your Class Files and Documentation Available to Clients

After writing, configuring, testing, installing and documenting your provider software, make documentation available to your customers.

How a Provider Can Do Self-Integrity Checking

Each provider should do self-integrity checking to ensure that the JAR file containing its code has not been tampered with, for example in an attempt to invoke provider methods directly rather than through JCA.

Providers that provide implementations for encryption services (Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory) must be digitally signed and should be signed with a certificate issued by "trusted" Certification Authorities. Currently, the following two Certification Authorities are considered "trusted":

  • Sun Microsystems' JCA Code Signing CA, and
  • IBM JCA Code Signing CA.

Please refer to Step 6.2: Sign Your Providerfor detailed information on how to get a code-signing certificate from Sun Microsystems' JCA Code Signing CA and the certificate of that CA.

After getting the signing certificate from above Certification Authority, provider packages should embed within themselves the bytes for its own signing certificate, for example in an array like the bytesOfProviderCert array referred to in the Identifying Each of the Signers and Determining If One is Trusted section below. At runtime, the embedded certificate will be used in determining whether or not the provider code is authentic.

The basic approach a provider can use to check its own integrity is:

  1. Determine the URL of the JAR file containing the provider code, and
  2. Verify the JAR file's digital signatures to ensure that at least one signer of each entry of the JAR file is trusted.

Each of these steps is described in the following sections:

Notes on the Sample Code

This section traces how these concepts are implemented in the sample code.

The sample code Appendix G: MyJCE.java is a complete code example that implements these steps.

Important:

In the unbundled version of JCE 1.2.x, (used with JDKs 1.2.x and 1.3.x), providers needed to include code to authenticate the JCA framework to assure themselves of the integrity and authenticity of the JCA that they plugged into. In JDK 6 and later, this is no longer necessary.

One implication is that a provider written just for JCE 1.2.2 will not work in JDK 6 because the provider's JCE framework authentication check will not work; the JCE framework code is no longer where the provider expects it to be. If you want your provider to work only with JDK 6, it should not have code to authenticate the JCE framework. On the other hand, if you want your provider to work both with JCE 1.2.2 and with JDK 6, then add a conditional statement. This way the provider code to authenticate the JCE framework is executed only when the provider is run with JCE 1.2.2. The following is sample code:

    Class cipherCls = Class.forName("javax.crypto.Cipher");

    CodeSource cs = cipherCls.getProtectionDomain().getCodeSource();
    if (cs != null) {
        // Authenticate JCE framework         . . .
    } 

Finding the Provider JAR File: Basics

Sample code to determine the provider JAR file URL and creating a JarFile.

Determining the Provider's JAR File URL

The URL for the provider's JAR file can be obtained by determining the provider's CodeSource and then calling the getLocation method on the CodeSource.

    URL providerURL = (URL) AccessController.doPrivileged(
        new PrivilegedAction) {
            public Object run() {
                CodeSource cs =
                    MyJCE.class.getProtectionDomain().getCodeSource();
                return cs.getLocation();
            }
        }); 

Creating a JarFile Referring to the JAR File

Once you have the URL for the provider's JAR file, you can create a java.util.jar.JarFile referring to the JAR file. This instance is needed in the step for Verifying the Provider JAR File: Basics.

To create the JAR file, first open a connection to the specified URL by calling its openConnection method. Since the URL is a JAR URL, the type is java.net.JarURLConnection. Here's the basic code:

    // Prep the url with the appropriate protocol.
    jarURL =
        url.getProtocol().equalsIgnoreCase("jar") ? url :
            new URL("jar:" + url.toString() + "!/");

    // Retrieve the jar file using JarURLConnection
    JarFile jf = (JarFile) AccessController.doPrivileged(
        new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                JarURLConnection conn =
                    (JarURLConnection) jarURL.openConnection();
        ...  

Now that you have a JarURLConnection, you can call its getJarFile method to get the JAR file:

    // Always get a fresh copy, so we don't have to
    // worry about the stale file handle when the
    // cached jar is closed by some other application.
    conn.setUseCaches(false);
    jf = conn.getJarFile(); 

Verifying the Provider JAR File: Basics

Once you have determined the URL for your provider JAR file and you have created a JarFile referring to the JAR file, as shown in the steps above, you can then verify the file.

The basic approach is:

  1. Ensure that at least one of each entry's signer's certificates is equal to the provider's own code signing certificate.
  2. Go through all the entries in the JAR file and ensure the signature on each one verifies correctly.
  3. Ensure that at least one of each entry's signer's certificates can be traced back to a trusted Certification Authority.

Verification Setup

Our approach is to define a class JarVerifier to handle the retrieval of a JAR file from a given URL and verify whether the JAR file is signed with the specified certificate.

The constructor of JarVerifier takes the provider URL as a parameter which will be used to retrieve the JAR file later.

The actual jar verification is implemented in the verify method which takes the provider code signing certificate as a parameter.

    public void verify(X509Certificate targetCert) throws IOException {
        // variable 'jarFile' is a JarFile object created
        // from the provider's Jar URL.
        ...
        Vector entriesVec = new Vector(); 

Basically the verify method will go through the JAR file entries twice: the first time checking the signature on each entry and the second time verifying the signer is trusted.

Note: In our code snippets the jarFile variable is the JarFile object of the provider's jar file.

JAR File Signature Check

An authentic provider JAR file is signed. So the JAR file has been tampered with if it isn't signed:

    // Ensure the jar file is signed.
    Manifest man = jarFile.getManifest();
    if (man == null) {
        throw new SecurityException("The provider is not signed");
    } 

Verifying Signatures

The next step is to go through all the entries in the JAR file and ensure the signature on each one verifies correctly. One possible way to verify the signature on a JAR file entry is to simply read the file. If a JAR file is signed, the read method itself automatically performs the signature verification. Here is sample code:

    // Ensure all the entries' signatures verify correctly
    byte[] buffer = new byte[8192];
    Enumeration entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry je = (JarEntry) entries.nextElement();

        // Skip directories.
        if (je.isDirectory())
            continue;

        entriesVec.addElement(je);
        InputStream is = jarFile.getInputStream(je);

        // Read in each jar entry. A security exception will
        // be thrown if a signature/digest check fails.
        int n;
        while ((n = is.read(buffer, 0, buffer.length)) != -1) {
            // Don't care
        }
        is.close();
    }
    

Ensuring Signers Are Trusted

The code in the previous section verified the signatures of all the provider JAR file entries. The fact that they all verify correctly is a requirement, but it is not sufficient to verify the authenticity of the JAR file. A final requirement is that the signatures were generated by the same entity as the one that developed this provider. To test that the signatures are trusted, we can again go through each entry in the JAR file (this time using the entriesVec built in the previous step), and for each entry that must be signed (that is, each entry that is not a directory and that is not in the META-INF directory):

  1. Get the list of signer certificates for the entry.
  2. Identify each of the certificate chains and determine whether any of the certificate chains are trusted. At least one of the certificate chains must be trusted.

The loop setup is the following:

    Enumeration e = entriesVec.elements();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        ...
    } 

Getting the List of Certificates

The certificates for the signers of a JAR file entry JarEntry can be obtained simply by calling the JarEntry getCertificates method:

    Certificate[] certs = je.getCertificates();

Adding this line of code to the previous loop setup code, and adding code to ignore directories and files in the META-INF directory gives us:

    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();

        // Every file must be signed except files in META-INF.
        Certificate[] certs = je.getCertificates();
        if ((certs == null) || (certs.length == 0)) {
            if (!je.getName().startsWith("META-INF"))
                throw new SecurityException(
                    "The provider has unsigned class files.");
            } else {
                // Check whether the file is signed by the expected
                // signer. The jar may be signed by multiple signers.
                // See if one of the signers is 'targetCert'.
                ...
            }
        ...  

Identifying Each of the Signers and Determining If One is Trusted

The certificate array returned by the JarEntry getCertificates method contains one or more certificate chains. There is one chain per signer of the entry. Each chain contains one or more certificates. Each certificate in a chain authenticates the public key in the previous certificate.

The first certificate in a chain is the signer's certificate which contains the public key corresponding to the private key actually used to sign the entry. Each subsequent certificate is a certificate for the issuer of the previous certificate. Since the self-integrity check is based on whether the JAR file is signed with the provider's signing cert, the trust decision will be made upon only the first certificate, the signer's certificate.

We need to go through the array of certificate chains and check each chain and the associated signers until we find a trusted entity. For each JAR file entry, at least one of the signers must be trusted. A signer is considered "trusted" if and only if its certificate is equals to the embedded provider signing certificate.

The following sample code loops through all the certificate chains, compares the first certificate in a chain to the embedded provider signing certificate, and only returns true if a match is found.

    int startIndex = 0;
    X509Certificate[] certChain;
    boolean signedAsExpected = false;

    while ((certChain = getAChain(certs, startIndex)) != null) {
        if (certChain[0].equals(targetCert)) {
            // Stop since one trusted signer is found.
            signedAsExpected = true;
            break;
        }

        // Proceed to the next chain.
        startIndex += certChain.length;
    }

    if (!signedAsExpected) {
        throw new SecurityException(
            "The provider is not signed by a trusted signer");
    }
    

The getAChain method is defined as follows:

    /**
     * Extracts ONE certificate chain from the specified certificate array
     * which may contain multiple certificate chains, starting from index
     * 'startIndex'.
     */
    private static X509Certificate[] getAChain(
            Certificate[] certs, int startIndex) {

        if (startIndex > certs.length - 1)
            return null;

        int i;
        // Keep going until the next certificate is not the
        // issuer of this certificate.
        for (i = startIndex; i < certs.length - 1; i++) {
            if (!((X509Certificate)certs[i + 1]).getSubjectDN().
                    equals(((X509Certificate)certs[i]).getIssuerDN())) {
                break;
            }
        }

        // Construct and return the found certificate chain.
        int certChainSize = (i-startIndex) + 1;
        X509Certificate[] ret = new X509Certificate[certChainSize];
        for (int j = 0; j < certChainSize; j++ ) {
            ret[j] = (X509Certificate) certs[startIndex + j];
        }
        return ret;
    }
    

Notes on the myJCE Code Sample

The sample code, Appendix G: MyJCE.java, is a sample provider which has a method selfIntegrityChecking which performs self-integrity checking. It first determines the URL of its own provider JAR file and then verifies that the provider JAR file is signed with the embedded code-signing certificate.

Note: The method selfIntegrityChecking should be called by all the constructors of its cryptographic engine classes to ensure that its integrity is not compromised.

Provider MyJCE performs self-integrity checking in the following steps:

  1. Determine the URL to access the provider JAR file using its own class, MyJCE.class.
  2. Instantiate a JarVerifier object with the provider URL in Step 1.
  3. Create a X509Certificate object from the embedded byte array bytesOfProviderCert.
  4. Call the JarVerifier.verify method to verify all entries in the provider JAR file are signed and are signed with the same certificate instantiated in Step 3.

Note: The class JarVerifier will retrieve the JAR file from the given URL, make sure the JAR file is signed, all entries have valid signatures, and that entries are signed with the specified X509Certificate.

A security exception is thrown by JarVerifier.verify in several cases:

  • The certificate passed to verify is null (invalid).
  • When unable to retrieve JAR file from the given URL.
  • The provider is not signed. (The jar has no manifest.)
  • The provider has unsigned class files.
  • The provider is not signed with the specified certificate.

The Appendix G: MyJCE.java sample code is comprised of the code snippets shown above. In addition, it includes error handling, sample code signing certificate bytes, and code for instantiating a X509Certificate object from the embedded sample code signing certificate bytes.

Regarding the use of AccessController.doPrivileged, see API for Privileged Blocks for information on the use of doPrivileged.

Verifying Signatures

View all the entries in the JAR file and ensure the signature on each one verifies correctly.

The next step is to go through all the entries in the JAR file and ensure the signature on each one verifies correctly. One possible way to verify the signature on a JAR file entry is to simply read the file. If a JAR file is signed, the read method itself automatically performs the signature verification. Here is sample code:

    // Ensure all the entries' signatures verify correctly
    byte[] buffer = new byte[8192];
    Enumeration entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry je = (JarEntry) entries.nextElement();

        // Skip directories.
        if (je.isDirectory())
            continue;

        entriesVec.addElement(je);
        InputStream is = jarFile.getInputStream(je);

        // Read in each jar entry. A security exception will
        // be thrown if a signature/digest check fails.
        int n;
        while ((n = is.read(buffer, 0, buffer.length)) != -1) {
            // Don't care
        }
        is.close();
    }
    

Ensuring Signers Are Trusted

The code in the previous section verified the signatures of all the provider JAR file entries.

The fact that they all verify correctly is a requirement, but it is not sufficient to verify the authenticity of the JAR file. A final requirement is that the signatures were generated by the same entity as the one that developed this provider. To test that the signatures are trusted, we can again go through each entry in the JAR file (this time using the entriesVec built in the previous step), and for each entry that must be signed (that is, each entry that is not a directory and that is not in the META-INF directory):

  1. Get the list of signer certificates for the entry.
  2. Identify each of the certificate chains and determine whether any of the certificate chains are trusted. At least one of the certificate chains must be trusted.

The loop setup is the following:

    Enumeration e = entriesVec.elements();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        ...
    } 

Getting the List of Certificates

The certificates for the signers of a JAR file entry JarEntry can be obtained simply by calling the JarEntry getCertificates method:

    Certificate[] certs = je.getCertificates();

Adding this line of code to the previous loop setup code, and adding code to ignore directories and files in the META-INF directory gives us:

    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();

        // Every file must be signed except files in META-INF.
        Certificate[] certs = je.getCertificates();
        if ((certs == null) || (certs.length == 0)) {
            if (!je.getName().startsWith("META-INF"))
                throw new SecurityException(
                    "The provider has unsigned class files.");
            } else {
                // Check whether the file is signed by the expected
                // signer. The jar may be signed by multiple signers.
                // See if one of the signers is 'targetCert'.
                ...
            }
        ...  

Identifying Each of the Signers and Determining If One is Trusted

The certificate array returned by the JarEntry getCertificates method contains one or more certificate chains. There is one chain per signer of the entry. Each chain contains one or more certificates. Each certificate in a chain authenticates the public key in the previous certificate.

The first certificate in a chain is the signer's certificate which contains the public key corresponding to the private key actually used to sign the entry. Each subsequent certificate is a certificate for the issuer of the previous certificate. Since the self-integrity check is based on whether the JAR file is signed with the provider's signing cert, the trust decision will be made upon only the first certificate, the signer's certificate.

We need to go through the array of certificate chains and check each chain and the associated signers until we find a trusted entity. For each JAR file entry, at least one of the signers must be trusted. A signer is considered "trusted" if and only if its certificate is equals to the embedded provider signing certificate.

The following sample code loops through all the certificate chains, compares the first certificate in a chain to the embedded provider signing certificate, and only returns true if a match is found.

    int startIndex = 0;
    X509Certificate[] certChain;
    boolean signedAsExpected = false;

    while ((certChain = getAChain(certs, startIndex)) != null) {
        if (certChain[0].equals(targetCert)) {
            // Stop since one trusted signer is found.
            signedAsExpected = true;
            break;
        }

        // Proceed to the next chain.
        startIndex += certChain.length;
    }

    if (!signedAsExpected) {
        throw new SecurityException(
            "The provider is not signed by a trusted signer");
    }
    

The getAChain method is defined as follows:

    /**
     * Extracts ONE certificate chain from the specified certificate array
     * which may contain multiple certificate chains, starting from index
     * 'startIndex'.
     */
    private static X509Certificate[] getAChain(
            Certificate[] certs, int startIndex) {

        if (startIndex > certs.length - 1)
            return null;

        int i;
        // Keep going until the next certificate is not the
        // issuer of this certificate.
        for (i = startIndex; i < certs.length - 1; i++) {
            if (!((X509Certificate)certs[i + 1]).getSubjectDN().
                    equals(((X509Certificate)certs[i]).getIssuerDN())) {
                break;
            }
        }

        // Construct and return the found certificate chain.
        int certChainSize = (i-startIndex) + 1;
        X509Certificate[] ret = new X509Certificate[certChainSize];
        for (int j = 0; j < certChainSize; j++ ) {
            ret[j] = (X509Certificate) certs[startIndex + j];
        }
        return ret;
    }
    

Notes on the myJCE Code Sample

The sample code, Appendix G: MyJCE.java, is a sample provider which has a method selfIntegrityChecking which performs self-integrity checking. It first determines the URL of its own provider JAR file and then verifies that the provider JAR file is signed with the embedded code-signing certificate.

Note:

The method selfIntegrityChecking should be called by all the constructors of its cryptographic engine classes to ensure that its integrity is not compromised.

Provider MyJCE performs self-integrity checking in the following steps:

  1. Determine the URL to access the provider JAR file using its own class, MyJCE.class.
  2. Instantiate a JarVerifier object with the provider URL in Step 1.
  3. Create a X509Certificate object from the embedded byte array bytesOfProviderCert.
  4. Call the JarVerifier.verify method to verify all entries in the provider JAR file are signed and are signed with the same certificate instantiated in Step 3.

Note:

The class JarVerifier will retrieve the JAR file from the given URL, make sure the JAR file is signed, all entries have valid signatures, and that entries are signed with the specified X509Certificate.

A security exception is thrown by JarVerifier.verify in several cases:

  • The certificate passed to verify is null (invalid).
  • When unable to retrieve JAR file from the given URL.
  • The provider is not signed. (The jar has no manifest.)
  • The provider has unsigned class files.
  • The provider is not signed with the specified certificate.

The Appendix G: MyJCE.java sample code is comprised of the code snippets shown above. In addition, it includes error handling, sample code signing certificate bytes, and code for instantiating a X509Certificate object from the embedded sample code signing certificate bytes.

Regarding the use of AccessController.doPrivileged, please see API for Privileged Blocks for information on the use of doPrivileged.

Further Implementation Details and Requirements

Information about alias names, service interdependencies, algorithm parameter generators and algorithm parameters.

Alias Names

In the JDK, the aliasing scheme enables clients to use aliases when referring to algorithms or types, rather than the standard names.

For many cryptographic algorithms and types, there is a single official "standard name" defined in the .

For example, "MD5" is the standard name for the RSA-MD5 Message Digest algorithm defined by RSA DSI in RFC 1321. DiffieHellman is the standard for the Diffie-Hellman key agreement algorithm defined in PKCS3.

In the JDK, there is an aliasing scheme that enables clients to use aliases when referring to algorithms or types, rather than their standard names.

For example, the "SUN" provider's master class (Sun.java) defines the alias "SHA1/DSA" for the algorithm whose standard name is "SHA1withDSA". Thus, the following statements are equivalent:

    Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

    Signature sig = Signature.getInstance("SHA1/DSA", "SUN");

Aliases can be defined in your "master class" (see Step 3: Write your Master Class, a subclass of Provider). To define an alias, create a property named

    Alg.Alias.engineClassName.aliasName

where engineClassName is the name of an engine class (e.g., Signature), and aliasName is your alias name. The value of the property must be the standard algorithm (or type) name for the algorithm (or type) being aliased.

As an example, the "SUN" provider defines the alias "SHA1/DSA" for the signature algorithm whose standard name is "SHA1withDSA" by setting a property named Alg.Alias.Signature.SHA1/DSA to have the value SHA1withDSA via the following:

    put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");

Note:

The aliases defined by one provider are available only to that provider and not to any other providers. Thus, aliases defined by the SunJCE provider are available only to the SunJCE provider.

Service Interdependencies

Some algorithms require the use of other types of algorithms. For example, a PBE algorithm usually needs to use a message digest algorithm in order to transform a password into a key.

If you are implementing one type of algorithm that requires another, you can do one of the following:

  1. Provide your own implementations for both.
  2. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by the default Sun provider that is included with every Java SE Platform installation. For example, if you are implementing a PBE algorithm that requires a message digest algorithm, you can obtain an instance of a class implementing the MD5 message digest algorithm by calling
        MessageDigest.getInstance("MD5", "SUN")
    
  3. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another specific provider. This is only appropriate if you are sure that all clients who will use your provider will also have the other provider installed.
  4. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another (unspecified) provider. That is, you can request an algorithm by name, but without specifying any particular provider, as in
        MessageDigest.getInstance("MD5")
    
    This is only appropriate if you are sure that there will be at least one implementation of the requested algorithm (in this case, MD5) installed on each Java platform where your provider will be used.

Default Initialization

In case the client does not explicitly initialize a key pair generator or an algorithm parameter generator, each provider of such a service must supply (and document) a default initialization.

For example, the Sun provider uses a default modulus size (strength) of 1024 bits for the generation of DSA parameters, and the "SunJCE" provider uses a default modulus size (keysize) of 2048 bits for the generation of Diffie-Hellman parameters.

Default Key Pair Generator Parameter Requirements

If you implement a key pair generator, your implementation should supply default parameters that are used when clients don't specify parameters.

The documentation you supply (Step 11: Document your Provider and its Supported Services) should state what the default parameters are.

For example, the DSA key pair generator in the Sun provider supplies a set of pre-computed p, q, and g default values for the generation of 512, 768, 1024, and 2048-bit key pairs. The following p, q, and g values are used as the default values for the generation of 1024-bit DSA key pairs:

p = fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
    b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
    801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
    1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675
    f3ae2b61 d72aeff2 2203199d d14801c7

q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5

g = f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
    3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613
    b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
    0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06
    928b665e 807b5525 64014c3b fecf492a

(The p and q values given here were generated by the prime generation standard, using the 160-bit

SEED:  8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd

With this seed, the algorithm found p and q when the counter was at 92.)

The Provider.Service Class

Provider.Service class offers an alternative way for providers to advertise their services and supports additional features.

Since its introduction, security providers have published their service information via appropriately formatted key-value String pairs they put in their Hashtable entries. While this mechanism is simple and convenient, it limits the amount customization possible. As a result, JDK 5.0 introduced a second option, the Provider.Service class. It offers an alternative way for providers to advertise their services and supports additional features as described below. Note that this addition is fully compatible with the older method of using String valued Hashtable entries. A provider on JDK 5.0 can choose either method as it prefers, or even use both at the same time.

A Provider.Service object encapsulates all information about a service. This is the provider that offers the service, its type (e.g. MessageDigest or Signature), the algorithm name, and the name of the class that implements the service. Optionally, it also includes a list of alternate algorithm names for this service (aliases) and attributes, which are a map of (name, value) String pairs. In addition, it defines the methods newInstance() and supportsParameter(). They have default implementations, but can be overridden by providers if needed, as may be the case with providers that interface with hardware security tokens.

The newInstance() method is used by the security framework when it needs to construct new implementation instances. The default implementation uses reflection to invoke the standard constructor for the respective type of service. For all standard services except CertStore, this is the no-args constructor. The constructorParameter to newInstance() must be null in theses cases. For services of type CertStore, the constructor that takes a CertStoreParameters object is invoked, and constructorParameter must be a non-null instance of CertStoreParameters. A security provider can override the newInstance() method to implement instantiation as appropriate for that implementation. It could use direct invocation or call a constructor that passes additional information specific to the Provider instance or token. For example, if multiple Smartcard readers are present on the system, it might pass information about which reader the newly created service is to be associated with. However, despite customization all implementations must follow the conventions about constructorParameter described above.

The supportsParameter() tests whether the Service can use the specified parameter. It returns false if this service cannot use the parameter. It returns true if this service can use the parameter, if a fast test is infeasible, or if the status is unknown. It is used by the security framework with some types of services to quickly exclude non-matching implementations from consideration. It is currently only defined for the following standard services: Signature, Cipher, Mac, and KeyAgreement. The parameter must be an instance of Key in these cases. For example, for Signature services, the framework tests whether the service can use the supplied Key before instantiating the service. The default implementation examines the attributes SupportedKeyFormats and SupportedKeyClasses as described below. Again, a provider may override this methods to implement additional tests.

The SupportedKeyFormats attribute is a list of the supported formats for encoded keys (as returned by key.getFormat()) separated by the "|" (pipe) character. For example, X.509|PKCS#8. The SupportedKeyClasses attribute is a list of the names of classes of interfaces separated by the "|" character. A key object is considered to be acceptable if it is assignable to at least one of those classes or interfaces named. In other words, if the class of the key object is a subclass of one of the listed classes (or the class itself) or if it implements the listed interface. An example value is "java.security.interfaces.RSAPrivateKey|java.security.interfaces.RSAPublicKey" .

Four methods have been added to the Provider class for adding and looking up Services. As mentioned earlier, the implementation of those methods and also of the existing Properties methods have been specifically designed to ensure compatibility with existing Provider subclasses. This is achieved as follows:

If legacy Properties methods are used to add entries, the Provider class makes sure that the property strings are parsed into equivalent Service objects prior to lookup via getService(). Similarly, if the putService() method is used, equivalent property strings are placed into the provider's hashtable at the same time. If a provider implementation overrides any of the methods in the Provider class, it has to ensure that its implementation does not interfere with this conversion. To avoid problems, we recommend that implementations do not override any of the methods in the Provider class.

Signature Formats

The signature algorithm should specify the format in which the signature is encoded.

If you implement a signature algorithm, the documentation you supply (Step 11: Document your Provider and its Supported Services) should specify the format in which the signature (generated by one of the sign methods) is encoded.

For example, the SHA1withDSA signature algorithm supplied by the Sun provider encodes the signature as a standard ASN.1 sequence of two ASN.1 INTEGER values: r and s, in that order:

SEQUENCE ::= {
        r INTEGER,
        s INTEGER }

DSA Interfaces and their Required Implementations

The Java Security API contains interfaces (in the java.security.interfaces package) for the convenience of programmers implementing DSA services.

The Java Security API contains the following interfaces:

The following sections discuss requirements for implementations of these interfaces.

DSAKeyPairGenerator

The interface Interface DSAKeyPairGenerator is obsolete. It used to be needed to enable clients to provide DSA-specific parameters to be used rather than the default parameters your implementation supplies. However, in Java it is no longer necessary; a new KeyPairGenerator initialize method that takes an AlgorithmParameterSpec parameter enables clients to indicate algorithm-specific parameters.

DSAParams Implementation

If you are implementing a DSA key pair generator, you need a class implementing Interface DSAParams for holding and returning the p, q, and g parameters.

A DSAParams implementation is also required if you implement the DSAPrivateKey and DSAPublicKey interfaces. DSAPublicKey and DSAPrivateKey both extend the DSAKey interface, which contains a getParams method that must return a DSAParams object.

Note:

There is a DSAParams implementation built into the JDK: the java.security.spec.DSAParameterSpec class.

DSAPrivateKey and DSAPublicKey Implementations

If you implement a DSA key pair generator or key factory, you need to create classes implementing the Interface DSAPrivateKey and Interface DSAPublicKey interfaces.

If you implement a DSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a DSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DSAPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DSAPrivateKey or DSAPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys and then using the parameters, for example as parameters to the DSAParameterSpec constructor called to create a parameter specification from parameter values that could be used to initialize a KeyPairGenerator object for DSA.

If you implement a DSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed a DSAPrivateKey and your engineInitVerify method will expect to be passed a DSAPublicKey.

Please note: The DSAPublicKey and DSAPrivateKey interfaces define a very generic, provider-independent interface to DSA public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DSAPrivateKey or DSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the DSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the DSAPublicKey and DSAPrivateKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

   public interface DSAPrivateKey extends DSAKey,
                java.security.PrivateKey

   public interface DSAPublicKey extends DSAKey,
                java.security.PublicKey

   public interface DSAKey 

In the java.security package:

   public interface PrivateKey extends Key

   public interface PublicKey extends Key

   public interface Key extends java.io.Serializable 

In order to implement the DSAPrivateKey and DSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements

  • The getX method from the Interface DSAPrivateKey interface.
  • The getParams method from the Interface DSAKey interface, since DSAPrivateKey extends DSAKey. Note: The getParams method returns a DSAParams object, so you must also have a DSAParams implementation.
  • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key interface, since DSAPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

    Similarly, for public DSA keys, you need to supply a class that implements:

    • The getY method from the Interface DSAPublicKey interface.
    • The getParams method from the Interface DSAKey interface, since DSAPublicKey extends DSAKey.

      Note:

      The getParams method returns a DSAParams object, so you must also have a DSAParams Implementation.
    • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key, since DSAPublicKey extends java.security.PublicKey, and PublicKey extends Key.

RSA Interfaces and their Required Implementations

The Java Security API contains the interfaces (in the java.security.interfaces package) for the convenience of programmers implementing RSA services.

The following sections discuss requirements for implementations of these interfaces.

RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey Implementations

If you implement an RSA key pair generator or key factory, you need to create classes implementing the Interface RSAPublicKey (and/or Interface RSAPrivateCrtKey) and Interface RSAPublicKey interfaces. (RSAPrivateCrtKey is the interface to an RSA private key, using the Chinese Remainder Theorem (CRT) representation.)

If you implement an RSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement an RSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your RSAPrivateKey (or RSAPrivateCrtKey) implementation, and your engineGeneratePublic method will return an instance of your RSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of an RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey implementation.

If you implement an RSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed either an RSAPrivateKey or an RSAPrivateCrtKey, and your engineInitVerify method will expect to be passed an RSAPublicKey.

Please note: The RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces define a very generic, provider-independent interface to RSA public and private keys. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the RSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

    public interface RSAPrivateKey extends java.security.PrivateKey

    public interface RSAPrivateCrtKey extends RSAPrivateKey

    public interface RSAPublicKey extends java.security.PublicKey

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable

In order to implement the RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for RSA private keys, you need to supply a class that implements:

  • The getModulus and getPrivateExponent methods from the Interface RSAPrivateKey interface.
  • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key interface, since RSAPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

Similarly, for RSA private keys using the Chinese Remainder Theorem (CRT) representation, you need to supply a class that implements:

  • All the methods listed above for RSA private keys, since RSAPrivateCrtKey extends java.security.interfaces.RSAPrivateKey.
  • The getPublicExponent, getPrimeP, getPrimeQ, getPrimeExponentP, getPrimeExponentQ, and getCrtCoefficient methods from the Interface RSAPrivateKey interface.

For public RSA keys, you need to supply a class that implements:

  • The getModulus and getPublicExponent methods from the Interface RSAPublicKey interface.
  • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key interface, since RSAPublicKey extends java.security.PublicKey, and PublicKey extends Key.

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Diffie-Hellman Interfaces and their Required Implementations

JCA contains interfaces (in the javax.crypto.interfaces package) for the convenience of programmers implementing Diffie-Hellman services.

The following sections discuss requirements for implementations of these interfaces.

DHPrivateKey and DHPublicKey Implementations

If you implement a Diffie-Hellman key pair generator or key factory, you need to create classes implementing the Interface DHPrivateKey and Interface DHPublicKey interfaces.

If you implement a Diffie-Hellman key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a Diffie-Hellman key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DHPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DHPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DHPrivateKey or DHPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys. You can then use the parameters, for example, as parameters to the DHParameterSpec constructor called to create a parameter specification from parameter values used to initialize a KeyPairGenerator object for Diffie-Hellman.

If you implement the Diffie-Hellman key agreement algorithm, your engineInit method (in your KeyAgreementSpi subclass) will expect to be passed a DHPrivateKey and your engineDoPhase method will expect to be passed a DHPublicKey.

Note:

The DHPublicKey and DHPrivateKey interfaces define a very generic, provider-independent interface to Diffie-Hellman public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DHPrivateKey or DHPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the Diffie-Hellman algorithm engineInit and engineDoPhase methods (in your KeyAgreementSpi subclass).

To see what methods need to be implemented by classes that implement the DHPublicKey and DHPrivateKey interfaces, first note the following interface signatures:

In the javax.crypto.interfaces package:

    public interface DHPrivateKey extends DHKey, java.security.PrivateKey

    public interface DHPublicKey extends DHKey, java.security.PublicKey

    public interface DHKey 

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable 

To implement the DHPrivateKey and DHPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements:

  • The getX method from the Interface DHPrivateKey interface.
  • The getParams method from the Interface DHKey interface, since DHPrivateKey extends DHKey.
  • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key interface, since DHPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

Similarly, for public Diffie-Hellman keys, you need to supply a class that implements:

  • The getY method from the Interface DHPublicKey interface.
  • The getParams method from the Interface DHKey interface, since DHPublicKey extends DHKey.
  • The getAlgorithm, getEncoded, and getFormat methods from the Interface Key interface, since DHPublicKey extends java.security.PublicKey, and PublicKey extends Key.

Interfaces for Other Algorithm Types

As noted above, the Java Security API contains interfaces for the convenience of programmers implementing services like DSA, RSA and ECC. If there are services without API support, you need to define your own APIs.

If you are implementing a key pair generator for a different algorithm, you should create an interface with one or more initialize methods that clients can call when they want to provide algorithm-specific parameters to be used rather than the default parameters your implementation supplies. Your subclass of KeyPairGeneratorSpi should implement this interface.

For algorithms without direct API support, it is recommended that you create similar interfaces and provide implementation classes. Your public key interface should extend the Interface PublicKey interface. Similarly, your private key interface should extend the Interface PrivateKey interface.

Algorithm Parameter Specification Interfaces and Classes

An algorithm parameter specification is a transparent representation of the sets of parameters used with an algorithm.

A transparent representation of parameters means that you can access each value individually, through one of the get methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access the p, q, and g parameters, respectively).

This is contrasted with an opaque representation, as supplied by the AlgorithmParameters engine class, in which you have no direct access to the key material values; you can only get the name of the algorithm associated with the parameter set (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

If you supply an AlgorithmParametersSpi, AlgorithmParameterGeneratorSpi, or KeyPairGeneratorSpi implementation, you must utilize the AlgorithmParameterSpec interface, since each of those classes contain methods that take an AlgorithmParameterSpec parameter. Such methods need to determine which actual implementation of that interface has been passed in, and act accordingly.

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used signature, cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Java defines the following algorithm parameter specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The AlgorithmParameterSpec Interface

AlgorithmParameterSpec is an interface to a transparent specification of cryptographic parameters.

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.

The DSAParameterSpec Class

This class (which implements the AlgorithmParameterSpec and DSAParams interfaces) specifies the set of parameters used with the DSA algorithm. It has the following methods:

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()

These methods return the DSA algorithm parameters: the prime p, the sub-prime q, and the base g.

Many types of DSA services will find this class useful - for example, it is utilized by the DSA signature, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the Sun provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The DSA algorithm parameters implementation supplied by Sun returns an instance of the DSAParameterSpec class.

The IvParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the initialization vector (IV) used with a cipher in feedback mode.

Table 5-2 Method in IvParameterSpec

Method Description
byte[] getIV() Returns the initialization vector (IV).

The OAEPParameterSpec Class

This class specifies the set of parameters used with OAEP Padding, as defined in the PKCS #1 standard.

Table 5-3 Methods in OAEPParameterSpec

Method Description
String getDigestAlgorithm() Returns the message digest algorithm name.
String getMGFAlgorithm() Returns the mask generation function algorithm name.
AlgorithmParameterSpec getMGFParameters() Returns the parameters for the mask generation function.
PSource getPSource() Returns the source of encoding input P.

The PBEParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with a password-based encryption (PBE) algorithm.

Table 5-4 Methods in PBEParameterSpec

Method Description
int getIterationCount() Returns the iteration count.
byte[] getSalt() Returns the salt.

The RC2ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC2 algorithm.

Table 5-5 Methods in RC2ParameterSpec

Method Description
boolean equals(Object obj) Tests for equality between the specified object and this object.
int getEffectiveKeyBits() Returns the effective key size in bits.
byte[] getIV() Returns the IV or null if this parameter set does not contain an IV.
int hashCode() Calculates a hash code value for the object.

The RC5ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC5 algorithm.

Table 5-6 Methods in RC5ParameterSpec

Method Description
boolean equals(Object obj) Tests for equality between the specified object and this object.
byte[] getIV() Returns the IV or null if this parameter set does not contain an IV.
int getRounds() Returns the number of rounds.
int getVersion() Returns the version.
int getWordSize() Returns the word size in bits.
int hashCode() Calculates a hash code value for the object.

The DHParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the Diffie-Hellman algorithm.

Table 5-7 Methods in DHParameterSpec

Method Description
BigInteger getG() Returns the base generator g.
int getL() Returns the size in bits, l, of the random exponent (private value).
BigInteger getP() Returns the prime modulus p.
Many types of Diffie-Hellman services will find this class useful; for example, it is used by the Diffie-Hellman key agreement, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the "SunJCE" provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The Diffie-Hellman algorithm parameters implementation supplied by "SunJCE" returns an instance of the DHParameterSpec class.

Key Specification Interfaces and Classes Required by Key Factories

A key factory provides bi-directional conversions between opaque keys (of type Key) and key specifications. If you implement a key factory, you thus need to understand and utilize key specifications.

In some cases, you also need to implement your own key specifications.

Further information about key specifications, the interfaces and classes supplied in Java, and key factory requirements with respect to specifications, is provided below.

Key specifications are transparent representations of the key material that constitutes a key. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.

A transparent representation of keys means that you can access each key material value individually, through one of the get methods defined in the corresponding specification class. For example, java.security.spec.DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

This is contrasted with an opaque representation, as defined by the Key interface, in which you have no direct access to the parameter fields. In other words, an "opaque" representation gives you limited access to the key - just the three methods defined by the Key interface: getAlgorithm, getFormat, and getEncoded.

A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

Java defines the following key specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The KeySpec Interface

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all key specifications. All key specifications must implement this interface.

If your provider uses key types (e.g., Your_PublicKey_type and Your_PrivateKey_type) for which the JDK does not already provide corresponding KeySpec classes, there are two possible scenarios, one of which requires that you implement your own key specifications:

  1. If your users will never have to access specific key material values of your key type, you will not have to provide any KeySpec classes for your key type. In this scenario, your users will always create Your_PublicKey_type and Your_PrivateKey_type keys through the appropriate KeyPairGenerator supplied by your provider for that key type. If they want to store the generated keys for later usage, they retrieve the keys' encodings (using the getEncoded method of the Key interface). When they want to create an Your_PublicKey_type or Your_PrivateKey_type key from the encoding (e.g., in order to initialize a Signature object for signing or verification), they create an instance of X509EncodedKeySpec or PKCS8EncodedKeySpec from the encoding, and feed it to the appropriate KeyFactory supplied by your provider for that algorithm, whose generatePublic and generatePrivate methods will return the requested PublicKey (an instance of Your_PublicKey_type) or PrivateKey (an instance of Your_PrivateKey_type) object, respectively.
  2. If you anticipate a need for users to access specific key material values of your key type, or to construct a key of your key type from key material and associated parameter values, rather than from its encoding (as in the above case), you have to specify new KeySpec classes (classes that implement the KeySpec interface) with the appropriate constructor methods and get methods for returning key material fields and associated parameter values for your key type. You will specify those classes in a similar manner as is done by the DSAPrivateKeySpec and DSAPublicKeySpec classes. You need to ship those classes along with your provider classes, for example, as part of your provider JAR file.

Secret-Key Generation

If you provide a secret-key generator (subclass of javax.crypto.KeyGeneratorSpi) for a particular secret-key algorithm, you may return the generated secret-key object.

The generated secret-key object (which must be an instance of javax.crypto.SecretKey, see engineGenerateKey) can be returned in one of the following ways:

  • You implement a class whose instances represent secret-keys of the algorithm associated with your key generator. Your key generator implementation returns instances of that class. This approach is useful if the keys generated by your key generator have provider-specific properties.
  • Your key generator returns an instance of SecretKeySpec, which already implements the javax.crypto.SecretKey interface. You pass the (raw) key bytes and the name of the secret-key algorithm associated with your key generator to the SecretKeySpec constructor. This approach is useful if the underlying (raw) key bytes can be represented as a byte array and have no key-parameters associated with them.

Ensuring Exportability

A key feature of JCA is the exportability of the JCA framework and of the provider cryptography implementations if certain conditions are met.

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK specify that "strong" but limited cryptography may be used. An "unlimited" 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 JCA framework will enforce the restrictions specified in the installed jurisdiction policy files.

As noted elsewhere, you can write just one version of your provider software, implementing cryptography of maximum strength. It is up to JCA, not your provider, to enforce any jurisdiction policy file-mandated restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different locations.

The conditions that must be met by your provider in order to enable it to be plugged into JCA are the following:

Adding New Object Identifiers

The following information applies to providers who supply an algorithm that is not listed as one of the standard algorithms in Java Cryptography Architecture Standard Algorithm Name Documentation.

Mapping from OID to Name

Sometimes the JCA needs to instantiate a cryptographic algorithm implementation from an algorithm identifier (for example, as encoded in a certificate), which by definition includes the object identifier (OID) of the algorithm. For example, in order to verify the signature on an X.509 certificate, the JCA determines the signature algorithm from the signature algorithm identifier that is encoded in the certificate, instantiates a Signature object for that algorithm, and initializes the Signature object for verification.

For the JCA to find your algorithm, you must provide the object identifier of your algorithm as an alias entry for your algorithm in the provider master file.

    put("Alg.Alias.<engine_type>.1.2.3.4.5.6.7.8",
        "<algorithm_alias_name>");

Note that if your algorithm is known under more than one object identifier, you need to create an alias entry for each object identifier under which it is known.

An example of where the JCA needs to perform this type of mapping is when your algorithm ("Foo") is a signature algorithm and users run the keytool command and specify your (signature) algorithm alias.

    % keytool -genkeypair -sigalg 1.2.3.4.5.6.7.8

In this case, your provider master file should contain the following entries:

    put("Signature.Foo", "com.xyz.MyFooSignatureImpl");
    put("Alg.Alias.Signature.1.2.3.4.5.6.7.8", "Foo");

Other examples of where this type of mapping is performed are (1) when your algorithm is a keytype algorithm and your program parses a certificate (using the X.509 implementation of the SUN provider) and extracts the public key from the certificate in order to initialize a Signature object for verification, and (2) when keytool users try to access a private key of your keytype (for example, to perform a digital signature) after having generated the corresponding keypair. In these cases, your provider master file should contain the following entries:

    put("KeyFactory.Foo", "com.xyz.MyFooKeyFactoryImpl");
    put("Alg.Alias.KeyFactory.1.2.3.4.5.6.7.8", "Foo");

Mapping from Name to OID

If the JCA needs to perform the inverse mapping (that is, from your algorithm name to its associated OID), you need to provide an alias entry of the following form for one of the OIDs under which your algorithm should be known:

    put("Alg.Alias.Signature.OID.1.2.3.4.5.6.7.8", "MySigAlg");

If your algorithm is known under more than one object identifier, prefix the preferred one with "OID."

An example of where the JCA needs to perform this kind of mapping is when users run keytool in any mode that takes a -sigalg option. For example, when the -genkeypair and -certreq commands are invoked, the user can specify your (signature) algorithm with the -sigalg option.

Appendix A: Standard Names

The Standard Names document contains information about the algorithm specifications.

The JDK Security API requires and uses a set of standard names for algorithms, certificate and keystore types. The specification names previously found here in Appendix A and in the other security specifications (JSSE/CertPath/etc.) have been combined in the Java Cryptography Architecture Standard Algorithm Name Documentation. This document also contains more information about the algorithm specifications. Specific provider information can be found in the Oracle Providers.

Cryptographic implementations in the JDK are distributed through several different providers primarily for historical reasons (Sun, SunJSSE, SunJCE, SunRsaSign). Note these providers may not be available on all JDK implementations, and therefore, truly portable applications should call getInstance() without specifying specific providers. Applications specifying a particular provider may not be able to take advantage of native providers tuned for an underlying operating environment (such as PKCS or Microsoft's CAPI).

The SunPKCS11 provider itself does not contain any cryptographic algorithms, but instead, directs requests into an underlying PKCS11 implementation. The PKCS11 Reference Guide and the underlying PKCS11 implementation should be consulted to determine if a desired algorithm will be available through the PKCS11 provider. Likewise, on Windows systems, the SunMSCAPI provider does not provide any cryptographic functionality, but instead routes requests to the underlying Operating System for handling.

Appendix B: Jurisdiction Policy File Format

JCA represents its jurisdiction policy files as Java style policy files with corresponding permission statements.

As described in Default Policy Implementation and Policy File Syntax, a Java 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 JCA, 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.

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

<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 C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Due to import control restrictions, the jurisdiction policy files shipped with the Java SE Development Kit allow "strong" but limited cryptography to be used.

See Oracle Providers to know more about import limits on cryptographic algorithm.

Appendix D: The Sun Provider Master Class

Sample Sun provider master class.

Below is an edited version of the Sun.java file, which contains a class named Sun that is the Step 3: Write your Master Class, a subclass of Provider for the provider named Sun.

As with all master classes, this class is a subclass of Provider. It specifies the class names and package locations of all service implementations supplied by the Sun provider. This information is used by the getInstance methods of the engine classes to look up the various algorithms and other services when they are requested.

This code is supplied as an example of a provider master class.

/*
 * @(#)Sun.java 1.28 99/05/27
 *
 * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package sun.security.provider;

import java.io.*;
import java.util.*;
import java.security.*;

/**
 * The SUN Security Provider.
 *
 * @author Benjamin Renaud
 *
 * @version 1.28, 05/27/99
 */

/**
 * Defines the SUN provider.
 *
 * Algorithms supported, and their names:
 *
 * - SHA is the message digest scheme described in FIPS 180-1.
 *   Aliases for SHA are SHA-1 and SHA1.
 *
 * - SHA1withDSA is the signature scheme described in FIPS 186.
 *   (SHA used in DSA is SHA-1: FIPS 186 with Change No 1.)
 *   Aliases for SHA1withDSA are DSA, DSS, SHA/DSA, SHA-1/DSA, SHA1/DSA,
 *   SHAwithDSA, DSAWithSHA1, and the object
 *   identifier strings "OID.1.3.14.3.2.13", "OID.1.3.14.3.2.27" and
 *   "OID.1.2.840.10040.4.3".
 *
 * - DSA is the key generation scheme as described in FIPS 186.
 *   Aliases for DSA include the OID strings "OID.1.3.14.3.2.12"
 *   and "OID.1.2.840.10040.4.1".
 *
 * - MD5 is the message digest scheme described in RFC 1321.
 *   There are no aliases for MD5.
 */

public final class Sun extends Provider {

    private static final String INFO = "SUN " +
    "(DSA key/parameter generation; DSA signing; " +
    "SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore)";

    public Sun() {
        /* We are the SUN provider */
        super("SUN", 1.2, INFO);

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {

                /*
                 * Signature engines
                 */
                put("Signature.SHA1withDSA", "sun.security.provider.DSA");

                put("Alg.Alias.Signature.DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.DSS", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA-1/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHAwithDSA", "SHA1withDSA");
                put("Alg.Alias.Signature.DSAWithSHA1", "SHA1withDSA");
                put("Alg.Alias.Signature.OID.1.2.840.10040.4.3",
                    "SHA1withDSA");
                put("Alg.Alias.Signature.1.2.840.10040.4.3", "SHA1withDSA");
                put("Alg.Alias.Signature.1.3.14.3.2.13", "SHA1withDSA");
                put("Alg.Alias.Signature.1.3.14.3.2.27", "SHA1withDSA");

                /*
                 *  Key Pair Generator engines
                 */
                put("KeyPairGenerator.DSA",
                    "sun.security.provider.DSAKeyPairGenerator");
                put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSA");
                put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSA");
                put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSA");

                /*
                 * Digest engines
                 */
                put("MessageDigest.MD5", "sun.security.provider.MD5");
                put("MessageDigest.SHA", "sun.security.provider.SHA");

                put("Alg.Alias.MessageDigest.SHA-1", "SHA");
                put("Alg.Alias.MessageDigest.SHA1", "SHA");

                /*
                 * Algorithm Parameter Generator engines
                 */
                put("AlgorithmParameterGenerator.DSA",
                    "sun.security.provider.DSAParameterGenerator");

                /*
                 * Algorithm Parameter engines
                 */
                put("AlgorithmParameters.DSA",
                    "sun.security.provider.DSAParameters");
                put("Alg.Alias.AlgorithmParameters.1.3.14.3.2.12", "DSA");
                put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.1", "DSA");

                /*
                 * Key factories
                 */
                put("KeyFactory.DSA", "sun.security.provider.DSAKeyFactory");
                put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
                put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");

                /*
                 * SecureRandom
                 */
                 put("SecureRandom.SHA1PRNG",
                     "sun.security.provider.SecureRandom");

                /*
                 * Certificates
                 */
                put("CertificateFactory.X509",
                    "sun.security.provider.X509Factory");
                put("Alg.Alias.CertificateFactory.X.509", "X509");

                /*
                 * KeyStore
                 */
                put("KeyStore.JKS", "sun.security.provider.JavaKeyStore");

                /*
                 * KeySize
                 */
                put("Signature.SHA1withDSA KeySize", "1024");
                put("KeyPairGenerator.DSA KeySize", "1024");
                put("AlgorithmParameterGenerator.DSA KeySize", "1024");

                /*
                 * Implementation type: software or hardware
                 */
                put("Signature.SHA1withDSA ImplementedIn", "Software");
                put("KeyPairGenerator.DSA ImplementedIn", "Software");
                put("MessageDigest.MD5 ImplementedIn", "Software");
                put("MessageDigest.SHA ImplementedIn", "Software");
                put("AlgorithmParameterGenerator.DSA ImplementedIn",
                    "Software");
                put("AlgorithmParameters.DSA ImplementedIn", "Software");
                put("KeyFactory.DSA ImplementedIn", "Software");
                put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
                put("CertificateFactory.X509 ImplementedIn", "Software");
                put("KeyStore.JKS ImplementedIn", "Software");

                return null;
            }
        });
    }
}

Appendix E: The SunJCE Provider Master Class

A sample SunJCE.java file, for the provider named SunJCE.

Below is an edited version of the SunJCE.java file, which contains a class named SunJCE that is the Step 3: Write your Master Class, a subclass of Provider for the provider named SunJCE.

As with all master classes, this class is a subclass of Provider. It specifies the class names and package locations of all the cryptographic service implementations supplied by the SunJCE provider. This information is used by the getInstance methods of the engine classes to look up the various algorithms and other services when they are requested.

This code is supplied as an example of a provider master class.

/*
 * @(#)SunJCE.java      1.73 05/12/13
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.crypto.provider;

import java.security.*;
import java.security.cert.*;
import java.net.URL;
import java.io.ByteArrayInputStream;

/**
 * The "SunJCE" Cryptographic Service Provider.
 *
 * @author Jan Luehe
 * @author Sharon Liu
 *
 * @version 1.73, 12/13/05
 */

/**
 * Defines the "SunJCE" provider.
 *
 * Supported algorithms and their names:
 *
 * ...edited for space...
 *
 */

public final class SunJCE extends Provider {

    private static final String info = "SunJCE Provider " +
    "(implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, "
    + "Diffie-Hellman, HMAC)";

    private static final String OID_PKCS5_MD5_DES = "1.2.840.113549.1.5.3";
    private static final String OID_PKCS3 = "1.2.840.113549.1.3.1";

    public SunJCE() {
        /* We are the "SunJCE" provider */
        super("SunJCE", 1.6d, info);

        final String BLOCK_MODES = "ECB|CBC|PCBC|CTR|CTS|CFB|OFB" +
            "|CFB8|CFB16|CFB24|CFB32|CFB40|CFB48|CFB56|CFB64" +
            "|OFB8|OFB16|OFB24|OFB32|OFB40|OFB48|OFB56|OFB64";
        final String BLOCK_MODES128 = BLOCK_MODES +
            "|CFB72|CFB80|CFB88|CFB96|CFB104|CFB112|CFB120|CFB128" +
            "|OFB72|OFB80|OFB88|OFB96|OFB104|OFB112|OFB120|OFB128";
        final String BLOCK_PADS = "NOPADDING|PKCS5PADDING|ISO10126PADDING";

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
                public Object run() {

                /*
                 * Cipher engines
                 */
                put("Cipher.RSA", "com.sun.crypto.provider.RSACipher");
                put("Cipher.RSA SupportedModes", "ECB");
                put("Cipher.RSA SupportedPaddings",
                        "NOPADDING|PKCS1PADDING|OAEPWITHMD5ANDMGF1PADDING"
                        + "|OAEPWITHSHA1ANDMGF1PADDING"
                        + "|OAEPWITHSHA-1ANDMGF1PADDING"
                        + "|OAEPWITHSHA-256ANDMGF1PADDING"
                        + "|OAEPWITHSHA-384ANDMGF1PADDING"
                        + "|OAEPWITHSHA-512ANDMGF1PADDING");
                put("Cipher.RSA SupportedKeyClasses",
                        "java.security.interfaces.RSAPublicKey" +
                        "|java.security.interfaces.RSAPrivateKey");

                put("Cipher.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEWithMD5AndDESCipher");
                put("Alg.Alias.Cipher.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.Cipher."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                put("Cipher.AES", "com.sun.crypto.provider.AESCipher");
                put("Alg.Alias.Cipher.Rijndael", "AES");
                put("Cipher.AES SupportedModes", BLOCK_MODES128);
                put("Cipher.AES SupportedPaddings", BLOCK_PADS);
                put("Cipher.AES SupportedKeyFormats", "RAW");

                put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher");
                put("Cipher.AESWrap SupportedModes", "ECB");
                put("Cipher.AESWrap SupportedPaddings", "NOPADDING");
                put("Cipher.AESWrap SupportedKeyFormats", "RAW");

                put("Cipher.ARCFOUR",
                    "com.sun.crypto.provider.ARCFOURCipher");
                put("Alg.Alias.Cipher.RC4", "ARCFOUR");
                put("Cipher.ARCFOUR SupportedModes", "ECB");
                put("Cipher.ARCFOUR SupportedPaddings", "NOPADDING");
                put("Cipher.ARCFOUR SupportedKeyFormats", "RAW");

                /*
                 *  Key(pair) Generator engines
                 */
                put("KeyGenerator.AES",
                    "com.sun.crypto.provider.AESKeyGenerator");
                put("Alg.Alias.KeyGenerator.Rijndael", "AES");

                put("KeyGenerator.ARCFOUR",
                    "com.sun.crypto.provider.KeyGeneratorCore$" +
                    "ARCFOURKeyGenerator");
                put("Alg.Alias.KeyGenerator.RC4", "ARCFOUR");

                put("KeyGenerator.HmacMD5",
                    "com.sun.crypto.provider.HmacMD5KeyGenerator");

                put("KeyGenerator.HmacSHA256",
                    "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA256KG");

                put("KeyPairGenerator.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyPairGenerator");
                put("Alg.Alias.KeyPairGenerator.DH", "DiffieHellman");
                put("Alg.Alias.KeyPairGenerator.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.KeyPairGenerator."+OID_PKCS3,
                    "DiffieHellman");

                /*
                 * Algorithm parameter generation engines
                 */
                put("AlgorithmParameterGenerator.DiffieHellman",
                    "com.sun.crypto.provider.DHParameterGenerator");
                put("Alg.Alias.AlgorithmParameterGenerator.DH",
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameterGenerator.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameterGenerator."+OID_PKCS3,
                    "DiffieHellman");

                /*
                 * Key Agreement engines
                 */
                put("KeyAgreement.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyAgreement");
                put("Alg.Alias.KeyAgreement.DH", "DiffieHellman");
                put("Alg.Alias.KeyAgreement.OID."+OID_PKCS3, "DiffieHellman");
                put("Alg.Alias.KeyAgreement."+OID_PKCS3, "DiffieHellman");

                put("KeyAgreement.DiffieHellman SupportedKeyClasses",
                    "javax.crypto.interfaces.DHPublicKey" +
                    "|javax.crypto.interfaces.DHPrivateKey");

                /*
                 * Algorithm Parameter engines
                 */
                put("AlgorithmParameters.DiffieHellman",
                    "com.sun.crypto.provider.DHParameters");
                put("Alg.Alias.AlgorithmParameters.DH", "DiffieHellman");
                put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameters."+OID_PKCS3,
                    "DiffieHellman");

                put("AlgorithmParameters.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEParameters");
                put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.AlgorithmParameters."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                put("AlgorithmParameters.OAEP",
                    "com.sun.crypto.provider.OAEPParameters");

                /*
                 * Key factories
                 */
                put("KeyFactory.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyFactory");
                put("Alg.Alias.KeyFactory.DH", "DiffieHellman");
                put("Alg.Alias.KeyFactory.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.KeyFactory."+OID_PKCS3, "DiffieHellman");

                /*
                 * Secret-key factories
                 */
                put("SecretKeyFactory.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEKeyFactory$PBEWithMD5AndDES"
                    );
                put("Alg.Alias.SecretKeyFactory.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.SecretKeyFactory."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                /*
                 * MAC
                 */
                put("Mac.HmacMD5", "com.sun.crypto.provider.HmacMD5");
                put("Mac.HmacSHA256",
                    "com.sun.crypto.provider.HmacCore$HmacSHA256");

                put("Mac.HmacMD5 SupportedKeyFormats", "RAW");
                put("Mac.HmacSHA256 SupportedKeyFormats", "RAW");

                /*
                 * KeyStore
                 */
                put("KeyStore.JCEKS", "com.sun.crypto.provider.JceKeyStore");

                return null;
            }
        });
    }
}
 

Appendix F: The java.security properties File

The java.security file that shows the default list of installed providers.

Below is part of the java.security file that shows the default list of installed providers. It appears in every JRE installation. The file also contains other entries, but for brevity, we show only part of the file here. See the complete file at:

  • Solaris, Linux, or macOS: <java-home>/conf/security/java.security
  • Windows: <java-home>\conf\security\java.security

Here <java-home> refers to the directory where the JRE was installed.

See Step 5: Place Your Provider in a JAR File for an example of adding information about your provider to this file.

#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register
# Cryptography Package Providers ("providers" for short). The term
# "provider" refers to a package or set of packages that supply a
# concrete implementation of a subset of the cryptography aspects of
# the Java Security API. A provider may, for example, implement one or
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file,
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className>
#
# 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.
#
# <className> must specify the subclass of the Provider class whose
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other
# facilities implemented by the provider.
#
# There must be at least one provider specification in java.security.
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun
#
# (The number 1 is used for the default provider.)
#
# Note: Providers can be dynamically registered instead by calls to
# either the addProvider or insertProviderAt method in the Security
# class.

#
# List of providers and their preference orders (see above):
#

security.provider.1=sun.security.pkcs11.SunPKCS11 \
    ${java.home}/lib/security/sunpkcs11-solaris.cfg
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.9=sun.security.smartcardio.SunPCSC

# Rest of file deleted

Appendix G: MyJCE.java

/*
 *
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * -Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduct the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of Oracle nor the names of
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
 * DAMAGES OR LIABILITIES  SUFFERED BY LICENSEE AS A RESULT OF  OR
 * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
 * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
 * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
 * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
 * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that Software is not designed, licensed or
 * intended for use in the design, construction, operation or
  * maintenance of any nuclear facility.
 */

import java.io.*;
import java.net.*;
import java.security.cert.*;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.Provider;
import java.security.PublicKey;
import java.util.*;
import java.util.jar.*;

public final class MyJCE extends Provider {

    // Flag for avoiding unnecessary self-integrity checking.
    private static boolean verifiedSelfIntegrity = false;

    // Provider's signing cert which is used to sign the jar.
    private static X509Certificate providerCert = null;

    // Raw bytes of provider's own code signing cert.
    // NOTE: YOU NEED TO CHANGE THIS TO YOUR OWN PROVIDER CERTIFICATE
    private static final byte[] bytesOfProviderCert = {
        (byte)0x30, (byte)0x82, (byte)0x03, (byte)0xB4, (byte)0x30, (byte)0x82,
        (byte)0x03, (byte)0x72, (byte)0xA0, (byte)0x03, (byte)0x02, (byte)0x01,
        (byte)0x02, (byte)0x02, (byte)0x02, (byte)0x01, (byte)0x04, (byte)0x30,
        (byte)0x0B, (byte)0x06, (byte)0x07, (byte)0x2A, (byte)0x86, (byte)0x48,
        (byte)0xCE, (byte)0x38, (byte)0x04, (byte)0x03, (byte)0x05, (byte)0x00,
        (byte)0x30, (byte)0x81, (byte)0x90, (byte)0x31, (byte)0x0B, (byte)0x30,
        (byte)0x09, (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x06,
        (byte)0x13, (byte)0x02, (byte)0x55, (byte)0x53, (byte)0x31, (byte)0x0B,
        (byte)0x30, (byte)0x09, (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04,
        (byte)0x08, (byte)0x13, (byte)0x02, (byte)0x43, (byte)0x41, (byte)0x31,
        (byte)0x12, (byte)0x30, (byte)0x10, (byte)0x06, (byte)0x03, (byte)0x55,
        (byte)0x04, (byte)0x07, (byte)0x13, (byte)0x09, (byte)0x50, (byte)0x61,
        (byte)0x6C, (byte)0x6F, (byte)0x20, (byte)0x41, (byte)0x6C, (byte)0x74,
        (byte)0x6F, (byte)0x31, (byte)0x1D, (byte)0x30, (byte)0x1B, (byte)0x06,
        (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x0A, (byte)0x13, (byte)0x14,
        (byte)0x53, (byte)0x75, (byte)0x6E, (byte)0x20, (byte)0x4D, (byte)0x69,
        (byte)0x63, (byte)0x72, (byte)0x6F, (byte)0x73, (byte)0x79, (byte)0x73,
        (byte)0x74, (byte)0x65, (byte)0x6D, (byte)0x73, (byte)0x20, (byte)0x49,
        (byte)0x6E, (byte)0x63, (byte)0x31, (byte)0x23, (byte)0x30, (byte)0x21,
        (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x0B, (byte)0x13,
        (byte)0x1A, (byte)0x4A, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x20,
        (byte)0x53, (byte)0x6F, (byte)0x66, (byte)0x74, (byte)0x77, (byte)0x61,
        (byte)0x72, (byte)0x65, (byte)0x20, (byte)0x43, (byte)0x6F, (byte)0x64,
        (byte)0x65, (byte)0x20, (byte)0x53, (byte)0x69, (byte)0x67, (byte)0x6E,
        (byte)0x69, (byte)0x6E, (byte)0x67, (byte)0x31, (byte)0x1C, (byte)0x30,
        (byte)0x1A, (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x03,
        (byte)0x13, (byte)0x13, (byte)0x4A, (byte)0x43, (byte)0x45, (byte)0x20,
        (byte)0x43, (byte)0x6F, (byte)0x64, (byte)0x65, (byte)0x20, (byte)0x53,
        (byte)0x69, (byte)0x67, (byte)0x6E, (byte)0x69, (byte)0x6E, (byte)0x67,
        (byte)0x20, (byte)0x43, (byte)0x41, (byte)0x30, (byte)0x1E, (byte)0x17,
        (byte)0x0D, (byte)0x30, (byte)0x31, (byte)0x31, (byte)0x30, (byte)0x31,
        (byte)0x39, (byte)0x32, (byte)0x33, (byte)0x30, (byte)0x34, (byte)0x33,
        (byte)0x31, (byte)0x5A, (byte)0x17, (byte)0x0D, (byte)0x30, (byte)0x36,
        (byte)0x31, (byte)0x30, (byte)0x32, (byte)0x33, (byte)0x32, (byte)0x33,
        (byte)0x30, (byte)0x34, (byte)0x33, (byte)0x31, (byte)0x5A, (byte)0x30,
        (byte)0x63, (byte)0x31, (byte)0x1D, (byte)0x30, (byte)0x1B, (byte)0x06,
        (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x0A, (byte)0x0C, (byte)0x14,
        (byte)0x53, (byte)0x75, (byte)0x6E, (byte)0x20, (byte)0x4D, (byte)0x69,
        (byte)0x63, (byte)0x72, (byte)0x6F, (byte)0x73, (byte)0x79, (byte)0x73,
        (byte)0x74, (byte)0x65, (byte)0x6D, (byte)0x73, (byte)0x20, (byte)0x49,
        (byte)0x6E, (byte)0x63, (byte)0x31, (byte)0x23, (byte)0x30, (byte)0x21,
        (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x0B, (byte)0x0C,
        (byte)0x1A, (byte)0x4A, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x20,
        (byte)0x53, (byte)0x6F, (byte)0x66, (byte)0x74, (byte)0x77, (byte)0x61,
        (byte)0x72, (byte)0x65, (byte)0x20, (byte)0x43, (byte)0x6F, (byte)0x64,
        (byte)0x65, (byte)0x20, (byte)0x53, (byte)0x69, (byte)0x67, (byte)0x6E,
        (byte)0x69, (byte)0x6E, (byte)0x67, (byte)0x31, (byte)0x1D, (byte)0x30,
        (byte)0x1B, (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x04, (byte)0x03,
        (byte)0x0C, (byte)0x14, (byte)0x53, (byte)0x75, (byte)0x6E, (byte)0x20,
        (byte)0x4D, (byte)0x69, (byte)0x63, (byte)0x72, (byte)0x6F, (byte)0x73,
        (byte)0x79, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x6D, (byte)0x73,
        (byte)0x20, (byte)0x49, (byte)0x6E, (byte)0x63, (byte)0x30, (byte)0x82,
        (byte)0x01, (byte)0xB5, (byte)0x30, (byte)0x82, (byte)0x01, (byte)0x2A,
        (byte)0x06, (byte)0x05, (byte)0x2B, (byte)0x0E, (byte)0x03, (byte)0x02,
        (byte)0x0C, (byte)0x30, (byte)0x82, (byte)0x01, (byte)0x1F, (byte)0x02,
        (byte)0x81, (byte)0x81, (byte)0x00, (byte)0xFD, (byte)0x7F, (byte)0x53,
        (byte)0x81, (byte)0x1D, (byte)0x75, (byte)0x12, (byte)0x29, (byte)0x52,
        (byte)0xDF, (byte)0x4A, (byte)0x9C, (byte)0x2E, (byte)0xEC, (byte)0xE4,
        (byte)0xE7, (byte)0xF6, (byte)0x11, (byte)0xB7, (byte)0x52, (byte)0x3C,
        (byte)0xEF, (byte)0x44, (byte)0x00, (byte)0xC3, (byte)0x1E, (byte)0x3F,
        (byte)0x80, (byte)0xB6, (byte)0x51, (byte)0x26, (byte)0x69, (byte)0x45,
        (byte)0x5D, (byte)0x40, (byte)0x22, (byte)0x51, (byte)0xFB, (byte)0x59,
        (byte)0x3D, (byte)0x8D, (byte)0x58, (byte)0xFA, (byte)0xBF, (byte)0xC5,
        (byte)0xF5, (byte)0xBA, (byte)0x30, (byte)0xF6, (byte)0xCB, (byte)0x9B,
        (byte)0x55, (byte)0x6C, (byte)0xD7, (byte)0x81, (byte)0x3B, (byte)0x80,
        (byte)0x1D, (byte)0x34, (byte)0x6F, (byte)0xF2, (byte)0x66, (byte)0x60,
        (byte)0xB7, (byte)0x6B, (byte)0x99, (byte)0x50, (byte)0xA5, (byte)0xA4,
        (byte)0x9F, (byte)0x9F, (byte)0xE8, (byte)0x04, (byte)0x7B, (byte)0x10,
        (byte)0x22, (byte)0xC2, (byte)0x4F, (byte)0xBB, (byte)0xA9, (byte)0xD7,
        (byte)0xFE, (byte)0xB7, (byte)0xC6, (byte)0x1B, (byte)0xF8, (byte)0x3B,
        (byte)0x57, (byte)0xE7, (byte)0xC6, (byte)0xA8, (byte)0xA6, (byte)0x15,
        (byte)0x0F, (byte)0x04, (byte)0xFB, (byte)0x83, (byte)0xF6, (byte)0xD3,
        (byte)0xC5, (byte)0x1E, (byte)0xC3, (byte)0x02, (byte)0x35, (byte)0x54,
        (byte)0x13, (byte)0x5A, (byte)0x16, (byte)0x91, (byte)0x32, (byte)0xF6,
        (byte)0x75, (byte)0xF3, (byte)0xAE, (byte)0x2B, (byte)0x61, (byte)0xD7,
        (byte)0x2A, (byte)0xEF, (byte)0xF2, (byte)0x22, (byte)0x03, (byte)0x19,
        (byte)0x9D, (byte)0xD1, (byte)0x48, (byte)0x01, (byte)0xC7, (byte)0x02,
        (byte)0x15, (byte)0x00, (byte)0x97, (byte)0x60, (byte)0x50, (byte)0x8F,
        (byte)0x15, (byte)0x23, (byte)0x0B, (byte)0xCC, (byte)0xB2, (byte)0x92,
        (byte)0xB9, (byte)0x82, (byte)0xA2, (byte)0xEB, (byte)0x84, (byte)0x0B,
        (byte)0xF0, (byte)0x58, (byte)0x1C, (byte)0xF5, (byte)0x02, (byte)0x81,
        (byte)0x81, (byte)0x00, (byte)0xF7, (byte)0xE1, (byte)0xA0, (byte)0x85,
        (byte)0xD6, (byte)0x9B, (byte)0x3D, (byte)0xDE, (byte)0xCB, (byte)0xBC,
        (byte)0xAB, (byte)0x5C, (byte)0x36, (byte)0xB8, (byte)0x57, (byte)0xB9,
        (byte)0x79, (byte)0x94, (byte)0xAF, (byte)0xBB, (byte)0xFA, (byte)0x3A,
        (byte)0xEA, (byte)0x82, (byte)0xF9, (byte)0x57, (byte)0x4C, (byte)0x0B,
        (byte)0x3D, (byte)0x07, (byte)0x82, (byte)0x67, (byte)0x51, (byte)0x59,
        (byte)0x57, (byte)0x8E, (byte)0xBA, (byte)0xD4, (byte)0x59, (byte)0x4F,
        (byte)0xE6, (byte)0x71, (byte)0x07, (byte)0x10, (byte)0x81, (byte)0x80,
        (byte)0xB4, (byte)0x49, (byte)0x16, (byte)0x71, (byte)0x23, (byte)0xE8,
        (byte)0x4C, (byte)0x28, (byte)0x16, (byte)0x13, (byte)0xB7, (byte)0xCF,
        (byte)0x09, (byte)0x32, (byte)0x8C, (byte)0xC8, (byte)0xA6, (byte)0xE1,
        (byte)0x3C, (byte)0x16, (byte)0x7A, (byte)0x8B, (byte)0x54, (byte)0x7C,
        (byte)0x8D, (byte)0x28, (byte)0xE0, (byte)0xA3, (byte)0xAE, (byte)0x1E,
        (byte)0x2B, (byte)0xB3, (byte)0xA6, (byte)0x75, (byte)0x91, (byte)0x6E,
        (byte)0xA3, (byte)0x7F, (byte)0x0B, (byte)0xFA, (byte)0x21, (byte)0x35,
        (byte)0x62, (byte)0xF1, (byte)0xFB, (byte)0x62, (byte)0x7A, (byte)0x01,
        (byte)0x24, (byte)0x3B, (byte)0xCC, (byte)0xA4, (byte)0xF1, (byte)0xBE,
        (byte)0xA8, (byte)0x51, (byte)0x90, (byte)0x89, (byte)0xA8, (byte)0x83,
        (byte)0xDF, (byte)0xE1, (byte)0x5A, (byte)0xE5, (byte)0x9F, (byte)0x06,
        (byte)0x92, (byte)0x8B, (byte)0x66, (byte)0x5E, (byte)0x80, (byte)0x7B,
        (byte)0x55, (byte)0x25, (byte)0x64, (byte)0x01, (byte)0x4C, (byte)0x3B,
        (byte)0xFE, (byte)0xCF, (byte)0x49, (byte)0x2A, (byte)0x03, (byte)0x81,
        (byte)0x84, (byte)0x00, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x07,
        (byte)0xCC, (byte)0xF6, (byte)0x38, (byte)0x3A, (byte)0xCD, (byte)0xD3,
        (byte)0x58, (byte)0x99, (byte)0x90, (byte)0x0F, (byte)0x71, (byte)0xAF,
        (byte)0xAA, (byte)0xD0, (byte)0x03, (byte)0x27, (byte)0x3B, (byte)0x74,
        (byte)0xE1, (byte)0x64, (byte)0x38, (byte)0x11, (byte)0xBF, (byte)0xFA,
        (byte)0xB7, (byte)0xBF, (byte)0x2C, (byte)0xE7, (byte)0xBB, (byte)0xA7,
        (byte)0x92, (byte)0x2F, (byte)0x08, (byte)0xCE, (byte)0x27, (byte)0xF8,
        (byte)0xB4, (byte)0xFD, (byte)0xD8, (byte)0x14, (byte)0x1D, (byte)0xA3,
        (byte)0x95, (byte)0xBB, (byte)0x03, (byte)0x16, (byte)0xA6, (byte)0xBA,
        (byte)0xBC, (byte)0x35, (byte)0xC0, (byte)0xCD, (byte)0xF9, (byte)0xF5,
        (byte)0x6C, (byte)0xA7, (byte)0x94, (byte)0x5B, (byte)0x23, (byte)0x01,
        (byte)0xF9, (byte)0xAE, (byte)0xF5, (byte)0xC9, (byte)0xE0, (byte)0x81,
        (byte)0x7A, (byte)0xE8, (byte)0xE4, (byte)0x69, (byte)0xEB, (byte)0xF8,
        (byte)0xF5, (byte)0x80, (byte)0x25, (byte)0x04, (byte)0x2C, (byte)0x91,
        (byte)0x73, (byte)0x96, (byte)0x59, (byte)0xB4, (byte)0x06, (byte)0x83,
        (byte)0x17, (byte)0xB2, (byte)0x50, (byte)0xAC, (byte)0x4F, (byte)0xEB,
        (byte)0x9D, (byte)0x51, (byte)0x25, (byte)0x3D, (byte)0xF7, (byte)0xEE,
        (byte)0xB0, (byte)0x24, (byte)0x25, (byte)0x0E, (byte)0xFE, (byte)0xB4,
        (byte)0x32, (byte)0xA1, (byte)0xC4, (byte)0x0E, (byte)0xB3, (byte)0x66,
        (byte)0x41, (byte)0xE0, (byte)0x57, (byte)0xCE, (byte)0x9D, (byte)0xBE,
        (byte)0x33, (byte)0x2E, (byte)0x93, (byte)0x9A, (byte)0xC9, (byte)0x7A,
        (byte)0x57, (byte)0xDC, (byte)0xCD, (byte)0x88, (byte)0x60, (byte)0xA7,
        (byte)0xCE, (byte)0xA3, (byte)0x81, (byte)0x88, (byte)0x30, (byte)0x81,
        (byte)0x85, (byte)0x30, (byte)0x11, (byte)0x06, (byte)0x09, (byte)0x60,
        (byte)0x86, (byte)0x48, (byte)0x01, (byte)0x86, (byte)0xF8, (byte)0x42,
        (byte)0x01, (byte)0x01, (byte)0x04, (byte)0x04, (byte)0x03, (byte)0x02,
        (byte)0x04, (byte)0x10, (byte)0x30, (byte)0x0E, (byte)0x06, (byte)0x03,
        (byte)0x55, (byte)0x1D, (byte)0x0F, (byte)0x01, (byte)0x01, (byte)0xFF,
        (byte)0x04, (byte)0x04, (byte)0x03, (byte)0x02, (byte)0x05, (byte)0xE0,
        (byte)0x30, (byte)0x1D, (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x1D,
        (byte)0x0E, (byte)0x04, (byte)0x16, (byte)0x04, (byte)0x14, (byte)0x55,
        (byte)0x8D, (byte)0x1F, (byte)0x2A, (byte)0x05, (byte)0xAB, (byte)0x9B,
        (byte)0xCE, (byte)0x86, (byte)0x10, (byte)0xAE, (byte)0x3B, (byte)0x5D,
        (byte)0xF6, (byte)0xBA, (byte)0x3F, (byte)0x22, (byte)0xC5, (byte)0x6A,
        (byte)0xCA, (byte)0x30, (byte)0x1F, (byte)0x06, (byte)0x03, (byte)0x55,
        (byte)0x1D, (byte)0x23, (byte)0x04, (byte)0x18, (byte)0x30, (byte)0x16,
        (byte)0x80, (byte)0x14, (byte)0x65, (byte)0xE2, (byte)0xF4, (byte)0x86,
        (byte)0xC9, (byte)0xD3, (byte)0x4E, (byte)0xF0, (byte)0x91, (byte)0x4E,
        (byte)0x58, (byte)0xA2, (byte)0x6A, (byte)0xF5, (byte)0xD8, (byte)0x78,
        (byte)0x5A, (byte)0x9A, (byte)0xC1, (byte)0xA6, (byte)0x30, (byte)0x20,
        (byte)0x06, (byte)0x03, (byte)0x55, (byte)0x1D, (byte)0x11, (byte)0x04,
        (byte)0x19, (byte)0x30, (byte)0x17, (byte)0x81, (byte)0x15, (byte)0x79,
        (byte)0x75, (byte)0x2D, (byte)0x63, (byte)0x68, (byte)0x69, (byte)0x6E,
        (byte)0x67, (byte)0x2E, (byte)0x70, (byte)0x65, (byte)0x6E, (byte)0x67,
        (byte)0x40, (byte)0x73, (byte)0x75, (byte)0x6E, (byte)0x2E, (byte)0x63,
        (byte)0x6F, (byte)0x6D, (byte)0x30, (byte)0x0B, (byte)0x06, (byte)0x07,
        (byte)0x2A, (byte)0x86, (byte)0x48, (byte)0xCE, (byte)0x38, (byte)0x04,
        (byte)0x03, (byte)0x05, (byte)0x00, (byte)0x03, (byte)0x2F, (byte)0x00,
        (byte)0x30, (byte)0x2C, (byte)0x02, (byte)0x14, (byte)0x75, (byte)0x4B,
        (byte)0xE8, (byte)0x21, (byte)0x37, (byte)0x78, (byte)0x79, (byte)0x0A,
        (byte)0xD0, (byte)0xB5, (byte)0xDC, (byte)0x7E, (byte)0x36, (byte)0x75,
        (byte)0xB9, (byte)0xE4, (byte)0x14, (byte)0xB5, (byte)0xD0, (byte)0x46,
        (byte)0x02, (byte)0x14, (byte)0x6A, (byte)0x51, (byte)0xDC, (byte)0xBA,
        (byte)0x6D, (byte)0x1A, (byte)0x6B, (byte)0x5C, (byte)0x18, (byte)0x23,
        (byte)0x6A, (byte)0xF1, (byte)0xCA, (byte)0x21, (byte)0x8A, (byte)0x77,
        (byte)0xC2, (byte)0x05, (byte)0x16, (byte)0x42
    };

    // UNCOMMENT FOR TESTING AFTER YOU'VE REPLACED THE ABOVE CERT
    // RAW BYTES WITH YOUR OWN.
    // public static void main(String[] argv) {
    //     System.out.println("Integrity Checking? "
    //   + MyJCE.selfIntegrityChecking());
    // }

    public MyJCE() {
        // First, register provider name, version and description.
        super("MyJCE", 1.0, "sample provider which supports nothing");
        // Set up the provider properties here
        // For examples, reference the Appendix A and B of
        // JCE "How to Implement a Provider" Guide.
        //
        //    ...
        //
    }

    /**
     * Perform self-integrity checking. Call this method in all
     * the constructors of your SPI implementation classes.
     * NOTE: The following implementation assumes that all
     * your provider implementation is packaged inside ONE jar.
     */
    public static final synchronized boolean selfIntegrityChecking() {
        if (verifiedSelfIntegrity) {
            return true;
        }

        URL providerURL = AccessController.doPrivileged(
                                new PrivilegedAction<URL>() {
            public URL run() {
                CodeSource cs = MyJCE.class.getProtectionDomain().
                                            getCodeSource();
                return cs.getLocation();
            }
        });

        if (providerURL == null) {
            return false;
        }

        // Open a connnection to the provider JAR file
        JarVerifier jv = new JarVerifier(providerURL);

        // Make sure that the provider JAR file is signed with
        // provider's own signing certificate.
        try {
            if (providerCert == null) {
                providerCert = setupProviderCert();
            }
            jv.verify(providerCert);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        verifiedSelfIntegrity = true;
        return true;
    }

    /*
     * Set up 'providerCert' with the certificate bytes.
     */
    private static X509Certificate setupProviderCert()
              throws IOException, CertificateException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream inStream = new ByteArrayInputStream(
                                            bytesOfProviderCert);
        X509Certificate cert = (X509Certificate)
                                cf.generateCertificate(inStream);
        inStream.close();
        return cert;
    }

    static class JarVerifier {

        private URL jarURL = null;
        private JarFile jarFile = null;

        JarVerifier(URL jarURL) {
            this.jarURL = jarURL;
        }

        /**
         * Retrive the jar file from the specified url.
         */
        private JarFile retrieveJarFileFromURL(URL url)
            throws PrivilegedActionException, MalformedURLException {
            JarFile jf = null;

            // Prep the url with the appropriate protocol.
            jarURL =
                url.getProtocol().equalsIgnoreCase("jar") ?
                url :
                new URL("jar:" + url.toString() + "!/");
            // Retrieve the jar file using JarURLConnection
            jf = AccessController.doPrivileged(
                     new PrivilegedExceptionAction<JarFile>() {
                public JarFile run() throws Exception {
                    JarURLConnection conn =
                       (JarURLConnection) jarURL.openConnection();
                    // Always get a fresh copy, so we don't have to
                    // worry about the stale file handle when the
                    // cached jar is closed by some other application.
                    conn.setUseCaches(false);
                    return conn.getJarFile();
                }
            });
            return jf;
        }

        /**
         * First, retrieve the jar file from the URL passed in constructor.
         * Then, compare it to the expected X509Certificate.
         * If everything went well and the certificates are the same, no
         * exception is thrown.
         */
        public void verify(X509Certificate targetCert)
            throws IOException {
            // Sanity checking
            if (targetCert == null) {
                throw new SecurityException("Provider certificate is invalid");
            }

            try {
                if (jarFile == null) {
                    jarFile = retrieveJarFileFromURL(jarURL);
                }
            } catch (Exception ex) {
                SecurityException se = new SecurityException();
                se.initCause(ex);
                throw se;
            }

            Vector<JarEntry> entriesVec = new Vector<JarEntry>();

            // Ensure the jar file is signed.
            Manifest man = jarFile.getManifest();
            if (man == null) {
                throw new SecurityException("The provider is not signed");
            }

            // Ensure all the entries' signatures verify correctly
            byte[] buffer = new byte[8192];
            Enumeration entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry je = (JarEntry) entries.nextElement();

                // Skip directories.
                if (je.isDirectory()) continue;
                entriesVec.addElement(je);
                InputStream is = jarFile.getInputStream(je);

                // Read in each jar entry. A security exception will
                // be thrown if a signature/digest check fails.
                int n;
                while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                    // Don't care
                }
                is.close();
            }

            // Get the list of signer certificates
            Enumeration e = entriesVec.elements();

            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();

                // Every file must be signed except files in META-INF.
                Certificate[] certs = je.getCertificates();
                if ((certs == null) || (certs.length == 0)) {
                    if (!je.getName().startsWith("META-INF"))
                        throw new SecurityException("The provider " +
                                                    "has unsigned " +
                                                    "class files.");
                } else {
                    // Check whether the file is signed by the expected
                    // signer. The jar may be signed by multiple signers.
                    // See if one of the signers is 'targetCert'.
                    int startIndex = 0;
                    X509Certificate[] certChain;
                    boolean signedAsExpected = false;

                    while ((certChain = getAChain(certs, startIndex)) != null) {
                        if (certChain[0].equals(targetCert)) {
                            // Stop since one trusted signer is found.
                            signedAsExpected = true;
                            break;
                        }
                        // Proceed to the next chain.
                        startIndex += certChain.length;
                    }

                    if (!signedAsExpected) {
                        throw new SecurityException("The provider " +
                                                    "is not signed by a " +
                                                    "trusted signer");
                    }
                }
            }
        }

        /**
         * Extracts ONE certificate chain from the specified certificate array
         * which may contain multiple certificate chains, starting from index
         * 'startIndex'.
         */
        private static X509Certificate[] getAChain(Certificate[] certs,
                                                   int startIndex) {
            if (startIndex > certs.length - 1)
                return null;

            int i;
            // Keep going until the next certificate is not the
            // issuer of this certificate.
            for (i = startIndex; i < certs.length - 1; i++) {
                if (!((X509Certificate)certs[i + 1]).getSubjectDN().
                    equals(((X509Certificate)certs[i]).getIssuerDN())) {
                    break;
                }
            }
            // Construct and return the found certificate chain.
            int certChainSize = (i-startIndex) + 1;
            X509Certificate[] ret = new X509Certificate[certChainSize];
            for (int j = 0; j < certChainSize; j++ ) {
                ret[j] = (X509Certificate) certs[startIndex + j];
            }
            return ret;
        }

        // Close the jar file once this object is no longer needed.
        protected void finalize() throws Throwable {
            jarFile.close();
        }
    }
}

Appendix H: Code Samples

Examples which illustrate use of several of the JCA mechanisms. In addition, complete working examples can be found in Appendix I.

Computing a MessageDigest Object

An example describing the procedure to compute a MessageDigest object.

  1. Create the MessageDigest object, as in the following example:
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    

    This call assigns a properly initialized message digest object to the sha variable. The implementation implements the Secure Hash Algorithm (SHA-1), as defined in the National Institute for Standards and Technology's (NIST) FIPS 180-2 document.

  2. Suppose we have three byte arrays, i1, i2 and i3, which form the total input whose message digest we want to compute. This digest (or "hash") could be calculated via the following calls:
    sha.update(i1);
    sha.update(i2);
    sha.update(i3);
    byte[] hash = sha.digest();
    
  3. Optional: An equivalent alternative series of calls would be:
    sha.update(i1);
    sha.update(i2);
    byte[] hash = sha.digest(i3);
    

    After the message digest has been calculated, the message digest object is automatically reset and ready to receive new data and calculate its digest. All former state (i.e., the data supplied to

    update calls) is lost.

Example 5-14 Hash Implementations Through Cloning

Some hash implementations may support intermediate hashes through cloning. Suppose we want to calculate separate hashes for:

  • i1
  • i1 and i2
  • i1, i2, and i3

A way to do it is:

/* compute the hash for i1 */
sha.update(i1);
byte[] i1Hash = sha.clone().digest();

/* compute the hash for i1 and i2 */
sha.update(i2);
byte[] i12Hash = sha.clone().digest();

/* compute the hash for i1, i2 and i3 */
sha.update(i3);
byte[] i123hash = sha.digest();

Example 5-15 Determine if the Hash Implementation is Cloneable or not Cloneable

Some implementations of message digests are cloneable, others are not. To determine whether or not cloning is possible, attempt to clone the MessageDigest object and catch the potential exception as follows:
try {
    // try and clone it
    /* compute the hash for i1 */
    sha.update(i1);
    byte[] i1Hash = sha.clone().digest();
    // ...
    byte[] i123hash = sha.digest();
} catch (CloneNotSupportedException cnse) {
    // do something else, such as the code shown below
}

Example 5-16 Compute Intermediate Digests if the Hash Implementation is not Cloneable

If a message digest is not cloneable, the other, less elegant way to compute intermediate digests is to create several digests. In this case, the number of intermediate digests to be computed must be known in advance:
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
MessageDigest sha12 = MessageDigest.getInstance("SHA-1");
MessageDigest sha123 = MessageDigest.getInstance("SHA-1");

byte[] i1Hash = sha1.digest(i1);

sha12.update(i1);
byte[] i12Hash = sha12.digest(i2);

sha123.update(i1);
sha123.update(i2);
byte[] i123Hash = sha123.digest(i3);

Generating a Pair of Keys

In this example we will generate a public-private key pair for the algorithm named "DSA" (Digital Signature Algorithm), and use this keypair in future examples. We will generate keys with a 1024-bit modulus. We don't care which provider supplies the algorithm implementation.

Creating the Key Pair Generator

The first step is to get a key pair generator object for generating keys for the DSA algorithm:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

Initializing the Key Pair Generator

The next step is to initialize the key pair generator. In most cases, algorithm-independent initialization is sufficient, but in some cases, algorithm-specific initialization is used.

Algorithm-Independent Initialization

All key pair generators share the concepts of a keysize and a source of randomness. The KeyPairGenerator class initialization methods at a minimum needs a keysize. If the source of randomness is not explicitly provided, a SecureRandom implementation of the highest-priority installed provider will be used. Thus to generate keys with a keysize of 1024, simply call:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);

The following code illustrates how to use a specific, additionally seeded SecureRandom object:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed(userSeed);
keyGen.initialize(1024, random);

Since no other parameters are specified when you call the above algorithm-independent initialize method, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys. The provider may use precomputed parameter values or may generate new values.

Algorithm-Specific Initialization

For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two initialize methods that have an AlgorithmParameterSpec argument. Suppose your key pair generator is for the "DSA" algorithm, and you have a set of DSA-specific parameters, p, q, and g, that you would like to use to generate your key pair. You could execute the following code to initialize your key pair generator (recall that DSAParameterSpec is an AlgorithmParameterSpec):

DSAParameterSpec dsaSpec = new DSAParameterSpec(p, q, g);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed(userSeed);
keyGen.initialize(dsaSpec, random);

Generating the Pair of Keys

The final step is actually generating the key pair. No matter which type of initialization was used (algorithm-independent or algorithm-specific), the same code is used to generate the KeyPair:

KeyPair pair = keyGen.generateKeyPair();

Generating and Verifying a Signature Using Generated Keys

Examples of generating and verifying a signature using generated keys.

The following signature generation and verification examples use the KeyPair generated in the Generating a Pair of Keys .

Generating a Signature

We first create a Signature Class object:

Signature dsa = Signature.getInstance("SHA1withDSA");

Next, using the key pair generated in the key pair example, we initialize the object with the private key, then sign a byte array called data.

/* Initializing the object with a private key */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);

/* Update and sign the data */
dsa.update(data);
byte[] sig = dsa.sign();

Verifying a Signature

Verifying the signature is straightforward. (Note that here we also use the key pair generated in the key pair example.)

/* Initializing the object with the public key */
PublicKey pub = pair.getPublic();
dsa.initVerify(pub);

/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
System.out.println("signature verifies: " + verifies);

Generating/Verifying Signatures Using Key Specifications and KeyFactory

Sample code that is used to generate and verify signatures using key specifications and KeyFactory.

Suppose that, rather than having a public/private key pair (as, for example, was generated in the Generating a Pair of Keys above), you simply have the components of your DSA private key: x (the private key), p (the prime), q (the sub-prime), and g (the base).

Further suppose you want to use your private key to digitally sign some data, which is in a byte array named someData. You would do the following steps, which also illustrate creating a key specification and using a key factory to obtain a PrivateKey from the key specification (initSign requires a PrivateKey):

DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(x, p, q, g);

KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec);

Signature sig = Signature.getInstance("SHA1withDSA");
sig.initSign(privKey);
sig.update(someData);
byte[] signature = sig.sign();

Suppose Alice wants to use the data you signed. In order for her to do so, and to verify your signature, you need to send her three things:

  1. the data,
  2. the signature, and
  3. the public key corresponding to the private key you used to sign the data.

You can store the someData bytes in one file, and the signature bytes in another, and send those to Alice.

For the public key, assume, as in the signing example above, you have the components of the DSA public key corresponding to the DSA private key used to sign the data. Then you can create a DSAPublicKeySpec from those components:

DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(y, p, q, g);

You still need to extract the key bytes so that you can put them in a file. To do so, you can first call the generatePublic method on the DSA key factory already created in the example above:

PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);

Then you can extract the (encoded) key bytes via the following:

byte[] encKey = pubKey.getEncoded();

You can now store these bytes in a file, and send it to Alice along with the files containing the data and the signature.

Now, assume Alice has received these files, and she copied the data bytes from the data file to a byte array named data, the signature bytes from the signature file to a byte array named signature, and the encoded public key bytes from the public key file to a byte array named encodedPubKey.

Alice can now execute the following code to verify the signature. The code also illustrates how to use a key factory in order to instantiate a DSA public key from its encoding (initVerify requires a PublicKey).

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedPubKey);

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initVerify(pubKey);
    sig.update(data);
    sig.verify(signature);

Note:

In the above, Alice needed to generate a PublicKey from the encoded key bits, since initVerify requires a PublicKey . Once she has a PublicKey, she could also use the KeyFactorygetKeySpec method to convert it to a DSAPublicKeySpec so that she can access the components, if desired, as in:
    DSAPublicKeySpec dsaPubKeySpec =
        (DSAPublicKeySpec)keyFactory.getKeySpec(pubKey,
            DSAPublicKeySpec.class)

Now she can access the DSA public key components y, p, q, and g through the corresponding "get" methods on the DSAPublicKeySpec class (getY, getP, getQ, and getG).

Generating Random Numbers

The following code sample illustrates generating random numbers configured with different security strengths using the SecureRandom class:

    SecureRandom drbg;
    byte[] buffer = new byte[32];

    // Any DRBG can be provided 
    drbg = SecureRandom.getInstance("DRBG");
    drbg.nextBytes(buffer);

    SecureRandomParameters params = drbg.getParameters();
    if (params instanceof DrbgParameters.Instantiation) {
       DrbgParameters.Instantiation ins = (DrbgParameters.Instantiation) params;
         if (ins.getCapability().supportsReseeding()) {
         drbg.reseed();
       }
    }

    // The following call requests a weak DRBG instance. It is only
    // guaranteed to support 112 bits of security strength.
    drbg = SecureRandom.getInstance("DRBG",
         DrbgParameters.instantiation(112, NONE, null));

    // Both the next two calls will likely fail, because drbg could be
    // instantiated with a smaller strength with no prediction resistance
    // support.
    drbg.nextBytes(buffer,
         DrbgParameters.nextBytes(256, false, "more".getBytes()));
    drbg.nextBytes(buffer,
         DrbgParameters.nextBytes(112, true, "more".getBytes()));

    // The following call requests a strong DRBG instance, with a
    // personalization string. If it successfully returns an instance,
    // that instance is guaranteed to support 256 bits of security strength
    // with prediction resistance available.
    drbg = SecureRandom.getInstance("DRBG", DrbgParameters.instantiation(
         256, PR_AND_RESEED, "hello".getBytes()));

    // Prediction resistance is not requested in this single call,
    // but an additional input is used.
    drbg.nextBytes(buffer,
         DrbgParameters.nextBytes(-1, false, "more".getBytes()));

    // Same for this call.
    drbg.reseed(DrbgParameters.reseed(false, "extra".getBytes()));

Determining If Two Keys Are Equal

Example code for determining if two keys are equal.

In many cases you would like to know if two keys are equal; however, the default method java.lang.Object.equals may not give the desired result. The most provider-independent approach is to compare the encoded keys. If this comparison isn't appropriate (for example, when comparing an RSAPrivateKey and an RSAPrivateCrtKey), you should compare each component.

The following code demonstrates this idea:

static boolean keysEqual(Key key1, Key key2) {
    if (key1.equals(key2)) {
        return true;
    }

    if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        return true;
    }

    // More code for different types of keys here.
    // For example, the following code can check if
    // an RSAPrivateKey and an RSAPrivateCrtKey are equal:
    // if ((key1 instanceof RSAPrivateKey) &&
    //     (key2 instanceof RSAPrivateKey)) {
    //     if ((key1.getModulus().equals(key2.getModulus())) &&
    //         (key1.getPrivateExponent().equals(
    //                                      key2.getPrivateExponent()))) {
    //         return true;
    //     }
    // }

    return false;
}

Reading Base64-Encoded Certificates

Example that reads a file with Base64-encoded certificates.

The following example reads a file with Base64-encoded certificates, which are each bounded at the beginning by

-----BEGIN CERTIFICATE-----

and at the end by

-----END CERTIFICATE-----

We convert the FileInputStream (which does not support mark and reset ) to a ByteArrayInputStream (which supports those methods), so that each call to generateCertificate consumes only one certificate, and the read position of the input stream is positioned to the next certificate in the file:

FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

while (bis.available() > 0) {
    Certificate cert = cf.generateCertificate(bis);
    System.out.println(cert.toString());
}

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 Advanced Encryption Standard (AES).

Parsing a Certificate Reply

Example that parses a PKCS7–formatted certificate reply stored in a file and extracts certificates from it.

The following example parses a PKCS7-formatted certificate reply stored in a file and extracts all the certificates from it:

FileInputStream fis = new FileInputStream(filename);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection c = cf.generateCertificates(fis);
Iterator i = c.iterator();
while (i.hasNext()) {
   Certificate cert = (Certificate)i.next();
   System.out.println(cert);
}

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 Advanced Encryption Standard (AES).

Generating a Key

To create an AES key, we have to instantiate a KeyGenerator for AES. We do not specify a provider, because we do not care about a particular AES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness and a default keysize will be used to create the AES key:

    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecretKey aesKey = 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 an AES cipher in Electronic Codebook mode, with PKCS5-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 AES is "AES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS5-style padding is "PKCS5Padding":

    Cipher aesCipher;

    // Create the cipher
    aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

We use the generated aesKey from above to initialize the Cipher object for encryption:

    // Initialize the cipher for encryption
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);

    // Our cleartext
    byte[] cleartext = "This is just an example".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = aesCipher.doFinal(cleartext);

    // Initialize the same cipher for decryption
    aesCipher.init(Cipher.DECRYPT_MODE, aesKey);

    // Decrypt the ciphertext
    byte[] cleartext1 = aesCipher.doFinal(ciphertext);

cleartext and cleartext1 are identical.

Using Password-Based Encryption

Example code where we prompt the user for a password from which we derive an encryption key.

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. See the ReadPassword class in the sample code in Appendix D for one possible way of reading character array passwords from an input stream.

In order to use Password-Based Encryption (PBE) as defined in PKCS5, 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. Newer PBE Algorithms use an iteration count of atleast 1000.

            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 = 1000;

            // Create PBE parameter set
            pbeParamSpec = new PBEParameterSpec(salt, count);

            // Prompt user for encryption password.
            // Collect user password as char array (using the
            // "readPassword" 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(readPassword(System.in));
            keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
            SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

            // Create PBE Cipher
            Cipher pbeCipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");

            // 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

Sample programs for using key agreement.

Refer to Appendix I: Sample Programs for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties.

Appendix I: Sample Programs

Sample programs for Diffie-Hellman key exchange, Blowfish cipher, HMAC-MD5, and reading ASCII passwords from an InputStream.

Diffie-Hellman Key Exchange between 2 Parties

Program that executes the Diffie-Hellman key agreement protocol between 2 parties.

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

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 program 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 is created.
 */

public class DHKeyAgreement2 {

    private DHKeyAgreement2() {}

    public static void main(String argv[]) {
        try {
            String mode = "USE_SKIP_DH_PARAMS";

            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.out.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.out.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.out.println("ALICE: Generate DH keypair ...");
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
        aliceKpairGen.initialize(dhSkipParamSpec);
        KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

        // Alice creates and initializes her DH KeyAgreement object
        System.out.println("ALICE: Initialization ...");
        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.out.println("BOB: Generate DH keypair ...");
        KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
        bobKpairGen.initialize(dhParamSpec);
        KeyPair bobKpair = bobKpairGen.generateKeyPair();

        // Bob creates and initializes his DH KeyAgreement object
        System.out.println("BOB: Initialization ...");
        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 the first (and only) phase
         * of her version of the DH
         * protocol.
         * Before she can do so, she has to instantiate 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.out.println("ALICE: Execute PHASE1 ...");
        aliceKeyAgree.doPhase(bobPubKey, true);

        /*
         * Bob uses Alice's public key for the first (and only) phase
         * of his version of the DH
         * protocol.
         */
        System.out.println("BOB: Execute PHASE1 ...");
        bobKeyAgree.doPhase(alicePubKey, true);

        /*
         * At this stage, both Alice and Bob have completed the DH key
         * agreement protocol.
         * Both generate the (same) shared secret.
         */
        byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
        int aliceLen = aliceSharedSecret.length;

        byte[] bobSharedSecret = new byte[aliceLen];
        int bobLen;
        try {
            // show example of what happens if you
            // provide an 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 (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
            throw new Exception("Shared secrets differ");
        System.out.println("Shared secrets are the same");

        /*
         * Now let's return the shared secret as a SecretKey object
         * and use it for encryption. First, we generate SecretKeys for the
         * "DES" algorithm (based on the raw shared secret data) and
         * then we use DES in ECB mode
         * as the encryption algorithm. DES in ECB mode does not require any
         * parameters.
         *
         * Then we use DES in CBC mode, which requires an initialization
         * vector (IV) parameter. In CBC mode, you need to initialize the
         * Cipher object with an IV, which can be supplied using the
         * javax.crypto.spec.IvParameterSpec class. Note that you have to use
         * the same IV for encryption and decryption: If you use a different
         * IV for decryption than you used for encryption, decryption will
         * fail.
         *
         * NOTE: If you do not specify an IV when you initialize the
         * Cipher object for encryption, the underlying implementation
         * will generate a random one, which you have to retrieve using the
         * javax.crypto.Cipher.getParameters() method, which returns an
         * instance of java.security.AlgorithmParameters. You need to transfer
         * the contents of that object (e.g., in encoded format, obtained via
         * the AlgorithmParameters.getEncoded() method) to the party who will
         * do the decryption. When initializing the Cipher for decryption,
         * the (reinstantiated) AlgorithmParameters object must be passed to
         * the Cipher.init() method.
         */
        System.out.println("Return shared secret as SecretKey object ...");
        // Bob
        // NOTE: The call to bobKeyAgree.generateSecret above reset the key
        // agreement object, so we call doPhase again prior to another
        // generateSecret call
        bobKeyAgree.doPhase(alicePubKey, true);
        SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");

        // Alice
        // NOTE: The call to aliceKeyAgree.generateSecret above reset the key
        // agreement object, so we call doPhase again prior to another
        // generateSecret call
        aliceKeyAgree.doPhase(bobPubKey, true);
        SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");

        /*
         * Bob encrypts, using DES in ECB mode
         */
        Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

        byte[] cleartext = "This is just an example".getBytes();
        byte[] ciphertext = bobCipher.doFinal(cleartext);

        /*
         * Alice decrypts, using DES in ECB mode
         */
        Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
        byte[] recovered = aliceCipher.doFinal(ciphertext);

        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in ECB mode recovered text is " +
            "same as cleartext");

        /*
         * Bob encrypts, using DES in CBC mode
         */
        bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

        cleartext = "This is just an example".getBytes();
        ciphertext = bobCipher.doFinal(cleartext);
        // Retrieve the parameter that was used, and transfer it to Alice in
        // encoded format
        byte[] encodedParams = bobCipher.getParameters().getEncoded();

        /*
         * Alice decrypts, using DES in CBC mode
         */
        // Instantiate AlgorithmParameters object from parameter encoding
        // obtained from Bob
        AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
        params.init(encodedParams);
        aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
        recovered = aliceCipher.doFinal(ciphertext);

        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in CBC mode recovered text is " +
            "same as cleartext");
    }

    /*
     * Converts a byte to hex digit and writes to the supplied buffer
     */
    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 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);
}

Diffie-Hellman Key Exchange between 3 Parties

Program that executes the Diffie-Hellman key agreement protocol between 3 parties.

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

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 program 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 {
            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.out.println("Using SKIP Diffie-Hellman parameters");
        dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);

        // Alice creates her own DH key pair
        System.out.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.out.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.out.println("CAROL: Generate DH keypair ...");
        KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH");
        carolKpairGen.initialize(dhSkipParamSpec);
        KeyPair carolKpair = carolKpairGen.generateKeyPair();


        // Alice initialize
        System.out.println("ALICE: Initialize ...");
        KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
        aliceKeyAgree.init(aliceKpair.getPrivate());

        // Bob initialize
        System.out.println("BOB: Initialize ...");
        KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
        bobKeyAgree.init(bobKpair.getPrivate());

        // Carol initialize
        System.out.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();
        System.out.println("Alice secret: " + toHexString(aliceSharedSecret));

        byte[] bobSharedSecret = bobKeyAgree.generateSecret();
        System.out.println("Bob secret: " + toHexString(bobSharedSecret));

        byte[] carolSharedSecret = carolKeyAgree.generateSecret();
        System.out.println("Carol secret: " + toHexString(carolSharedSecret));


        // Compare Alice and Bob
        if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
            throw new Exception("Alice and Bob differ");
        System.out.println("Alice and Bob are the same");

        // Compare Bob and Carol
        if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret))
            throw new Exception("Bob and Carol differ");
        System.out.println("Bob and Carol are the same");
    }


    /*
     * Converts a byte to hex digit and writes to the supplied buffer
     */
    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 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);
}

Blowfish Cipher Example

This program generates a Blowfish key, retrieves its raw bytes, and then reinstantiates a Blowfish key from the key bytes. The reinstantiated key is used to initialize a Blowfish cipher for encryption.

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

/**
 * This program generates a Blowfish key, retrieves its raw bytes, and
 * then reinstantiates a Blowfish key from the key bytes.
 * The reinstantiated key is used to initialize a Blowfish cipher for
 * encryption.
 */

public class BlowfishKey {

    public static void main(String[] args) throws Exception {

        KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted =
            cipher.doFinal("This is just an example".getBytes());
    }
}

HMAC-MD5 Example

Sample program that demonstrates how to generate a secret-key object for HMAC-MD5, and initialize a HMAC-MD5 object with it.

Example 5-17 Generate a Secret-key Object for HMAC-MD5

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.security.*;
import javax.crypto.*;

/**
 * This program demonstrates how to generate a secret-key object for
 * HMAC-MD5, and initialize an HMAC-MD5 object with it.
 */

public class initMac {

    public static void main(String[] args) throws Exception {

        // Generate secret key for HMAC-MD5
        KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
        SecretKey sk = kg.generateKey();

        // Get instance of Mac object implementing HMAC-MD5, and
        // initialize it with the above secret key
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(sk);
        byte[] result = mac.doFinal("Hi There".getBytes());
    }
}

Reading ASCII Passwords From an InputStream Example

This program reads ASCII passwords from an InputStream.

/*
 * @(#)ReadPassword.java  1.1 06/06/07
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

import java.util.*;
import java.io.*;
import java.security.*;

public class ReadPassword {
    /**
     * Read a password from the InputStream "in".
     * <p>
     * As Strings are immutable, passwords should be stored as an array
     * of characters, which can be blanked out when no longer needed.
     * <p>
     * If the provided InputStream is the System's Console, this method
     * uses the non-echoing readPassword() method of java.io.Console
     * (new to JDK 6).  If not, a fallback implementation is used.
     * <p>
     * NOTE:  For expository purposes, and because some applications do
     * not understand multi-byte characters, only 8-bit ASCII passwords
     * are handled here.
     * <p>
     * NOTE:  If a SecurityManager is used, the default standard
     * java.policy file found in the JDK (i.e.
     * <java-home>/conf/security/java.policy) allows reading the
     * line.separator property.  If your environment is different, this
     * code will need to be granted the appropriate privilege.
     *
     * @param   in
     *          the InputStream used to obtain the password.
     *
     * @return  A character array containing the password or passphrase,
     *          not including the line-termination characters,
     *          or null if an end of stream has been reached.
     *
     * @throws  IOException
     *          if an I/O problem occurs
     */
    public static final char[] readPassword(InputStream in)
            throws IOException {

        /*
         * If available, directly use the java.io.Console class to
         * avoid character echoing.
         */
        if (in == System.in && System.console() != null) {
            // readPassword returns "" if you just print ENTER,
            return System.console().readPassword();
        }

        /*
         * If a console is not available, read the InputStream
         * directly.  This approach may cause password echoing.
         *
         * Since different operating systems have different End-Of-Line
         * (EOL) sequences, this algorithm should allow for
         * platform-independent implementations.  Typical EOL sequences
         * are a single line feed ('\n'), or a carriage return/linefeed
         * combination ('\r\n').  However, some OS's use a single
         * a carriage return ('\r'), which complicates portability.
         *
         * Since we may not have the ability to push bytes back into the
         * InputStream, another approach is used here.  The javadoc for
         * <code>java.lang.System.getProperties()</code> specifies that
         * the set of system properties will contain a system-specific
         * value for the "line.separator".  Scan for this character
         * sequence instead of hard-coding a particular sequence.
         */

        /*
         * Enclose the getProperty in a doPrivileged block to minimize
         * the call stack permission required.
         */
        char [] EOL = AccessController.doPrivileged(
            new PrivilegedAction<char[]>() {
                public char[] run() {
                    String s = System.getProperty("line.separator");
                    // Shouldn't happen.
                    if (s == null) {
                        throw new RuntimeException(
                            "line.separator not defined");
                    }
                    return s.toCharArray();
                }
            });

        char [] buffer = new char[128];
        try {
            int len = 0;                // len of data in buffer.
            boolean done = false;       // found the EOL sequence
            int b;                      // byte read

            while (!done) {
                /*
                 * realloc if necessary
                 */
                if (len >= buffer.length) {
                    char [] newbuffer = new char[len + 128];
                    System.arraycopy(buffer, 0, newbuffer, 0, len);
                    Arrays.fill(buffer, ' ');
                    buffer = newbuffer;
                }

                /*
                 * End-of-Stream?
                 */
                if ((b = in.read()) == -1) {
                    // Return as much as we have, null otherwise.
                    if (len == 0) {
                        return null;
                    }
                    break;
                } else {
                    /*
                     * NOTE:  In the simple PBE example here,
                     * only 8 bit ASCII characters are handled.
                     */
                    buffer[len++] = (char) b;
                }

                /*
                 * check for the EOL sequence.  Do we have enough bytes?
                 */
                if (len >= EOL.length) {
                    int i = 0;
                    for (i = 0; i < EOL.length; i++) {
                        if (buffer[len - EOL.length + i] != EOL[i]) {
                            break;
                        }
                    }
                    done = (i == EOL.length);
                }
            }

            /*
             * If we found the EOL, strip the EOL chars.
             */
            char [] result = new char[done ? len - EOL.length : len];
            System.arraycopy(buffer, 0, result, 0, result.length);

            return result;
        } finally {
            /*
             * Zero out the buffer.
             */
            if (buffer != null) {
                Arrays.fill(buffer, ' ');
            }
        }
    }
}