Design Principles
Architecture
JCA Concepts
TheHow the JCA Might Be Used in a SSL/TLS ImplementationProviderClass
How Provider Implementations are Requested and SuppliedThe
Installing Providers
SecurityClass
TheSecureRandomClass
TheMessageDigestClass
TheSignatureClass
TheCipherClass
OtherCipher-based Classes
The Cipher Stream ClassesThe
TheTheCipherInputStreamClass
TheCipherOutputStreamClass
SealedObjectClass
MacClass
KeyInterfaces
TheKeyPairClass
KeySpecification Interfaces and Classes
TheOf Factories and GeneratorsKeySpecInterface
TheKeySpecSubinterfaces
TheEncodedKeySpecClass
ThePKCS8EncodedKeySpecClass
TheX509EncodedKeySpecClass
TheKeyFactoryClass
TheSecretKeyFactoryClass
TheKeyPairGeneratorClass
TheKeyGeneratorClass
TheKeyAgreementClass
Key Management
Keystore LocationAlgorithm Parameters Classes
Keystore Implementation
TheKeyStoreClass
TheTheAlgorithmParameterSpecInterface
TheAlgorithmParametersClass
TheAlgorithmParameterGeneratorClass
CertificateFactoryClass
How to Make Applications
"Exempt" from Cryptographic Restrictions
Computing aAppendix A: Standard NamesMessageDigestObject
Generating a Pair of Keys
Generating and Verifying a Signature Using Generated Keys
Generating/Verifying Signatures UsingKeySpecifications andKeyFactory
Determining If Two Keys Are Equal
Reading Base64-Encoded Certificates
Parsing a Certificate Reply
Using Encryption
Using Password-Based Encryption
Using Key Agreement
Appendix B: Jurisdiction Policy File Format
Appendix C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files
Diffie-Hellman Key Exchange between 2 Parties
Diffie-Hellman Key Exchange between 3 Parties
Blowfish Cipher Example
HMAC-MD5 Example
Reading ASCII Passwords From an InputStream Example
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 (hashs), 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 JavaTM Secure Socket Extension (JSSE) provides access to Secure Socket Layer (SSL) and Transport Layer Security (TLS) implementations. The Java Generic Security Services (JGSS) (via Kerberos) APIs, and the Simple Authentication and Security Layer (SASL) 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:
- 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, andjavax.crypto.interfaces.- 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.
Design Principles
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,Signature,KeyFactory,KeyPairGenerator, andCipherclasses.Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Provider (CSP) (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
Signatureobject) 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.
Architecture
Cryptographic Service Providers
java.security.Provideris 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 (see the Provider and Security classes). 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-256"). 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.
![]()
Cryptographic implementations in the Sun 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 The
ProviderClass for more information on how providers are written, installed, and registered.How Providers Are Actually Implemented
As mentioned earlier, 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, theSignatureengine class provides access to the functionality of a digital signature algorithm. The actual provider implementation is supplied in a subclass ofSignatureSpi. 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 the following code and illustration:
import javax.crypto.*; Cipher c = Cipher.getInstance("AES"); c.init(ENCRYPT_MODE, key);
![]()
Here an application wants an "AES"
javax.crypto.Cipherinstance, and doesn't care which provider is used. The application calls thegetInstance()factory methods of theCipherengine 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 theProviderclass. (Recall that theProviderclass 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 classcom.foo.AESCipherwhich extendsCipherSpi, and is thus suitable for use by theCipherengine class. An instance ofcom.foo.AESCipheris created, and is encapsulated in a newly-created instance ofjavax.crypto.Cipher, which is returned to the application. When the application now does theinit()operation on theCipherinstance, theCipherengine class routes the request into the correspondingengineInit()backing method in thecom.foo.AESCipherclass.Appendix A 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
KeyStoreclass, which is in thejava.securitypackage. A defaultKeyStoreimplementation is provided by Sun Microsystems. It implements the keystore as a file, using a proprietary keystore type (format) named "jks". Other keystore formats are available, such as "jceks" which is an alternate proprietary keystore format with much stronger encryption than "jks", and "pkcs12", which is based on the RSA PKCS12 Personal Information Exchange Syntax Standard.Applications can choose different keystore implementations from different providers, using the same provider mechanism described above.
See the Key Management section for more information.
JCA Concepts
This section introduces the major JCA APIs.
Engine Classes and Algorithms
An engine class provides the interface to a specific type of cryptographic service, independent of a particular cryptographic algorithm or provider. The engines either provide:
- cryptographic operations (encryption, digital signatures, message digests, etc.),
- generators or converters of cryptographic material (keys and algorithm parameters), or
- objects (keystores or certificates) that encapsulate the cryptographic data and can be used at higher layers of abstraction.
The following engine classes are available:
SecureRandom: used to generate random or pseudo-random numbers.
MessageDigest: used to calculate the message digest (hash) of specified data.
Signature: initilialized with keys, these are used to sign data and verify digital signatures.
Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA), stream encryption (e.g. RC4), asymmetric encryption (e.g. RSA), and password-based encryption (PBE).
- Message Authentication Codes (MAC): like
MessageDigests, these also generate hash values, but are first initialized with keys to protect the integrity of messages.
KeyFactory: used to convert existing opaque cryptographic keys of typeKeyinto key specifications (transparent representations of the underlying key material), and vice versa.
SecretKeyFactory: used to convert existing opaque cryptographic keys of typeSecretKeyinto key specifications (transparent representations of the underlying key material), and vice versa.SecretKeyFactorys are specializedKeyFactorys that create secret (symmetric) keys only.
KeyPairGenerator: used to generate a new pair of public and private keys suitable for use with a specified algorithm.
KeyGenerator: used to generate new secret keys for use with a specified algorithm.
KeyAgreement: used by two or more parties to agree upon and establish a specific key to use for a particular cryptographic operation.
AlgorithmParameters: used to store the parameters for a particular algorithm, including parameter encoding and decoding.
AlgorithmParameterGenerator: used to generate a set of AlgorithmParameters suitable for a specified algorithm.
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).
CertPathBuilder: used to build certificate chains (also known as certification paths).
CertPathValidator: used to validate certificate chains.
CertStore: used to retrieveCertificates andCRLs from a repository.
NOTE: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).
This section discusses the core classes and interfaces provided in the JCA:
The guide will cover the most useful high-level classes first (
- the
ProviderandSecurityclasses,
- the
SecureRandom,MessageDigest,Signature,Cipher,Mac,KeyFactory,SecretKeyFactory,KeyPairGenerator,KeyGenerator,KeyAgreement,AlgorithmParameters,AlgorithmParameterGenerator,KeyStore, andCertificateFactory, engine classes,
- the
Keyinterfaces and classes,
- the Algorithm Parameter Specification Interfaces and Classes and the Key Specification Interfaces and Classes, and
- miscellaneous support and convenience interfaces and classes.
NOTE: For more information on theCertPathBuilder,CertPathValidator, andCertStoreengine classes, please see the Java(TM) PKI Programmer's Guide.
Provider,Security,SecureRandom,MessageDigest,Signature,Cipher, andMac), then delve into the various support classes. For now, it is sufficient to simply say that Keys (public, private, and secret) are generated and represented by the various JCA classes, and are used by the high-level classes as part of their operation.This section shows the signatures of the main methods in each class and interface. Examples for some of these classes (
MessageDigest,Signature,KeyPairGenerator,SecureRandom,KeyFactory, and key specification classes) are supplied in the corresponding Examples sections.The complete reference documentation for the relevant Security API packages can be found in the package summaries:
The
ProviderClassThe 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
Providerclass 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, theProviderclass 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
Providerclass. The constructor of theProvidersubclass 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; for more information, see Engine Classes and Algorithms.
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.
In this section we explain how end-users install the cryptography implementations that fit their needs, and how developers request the implementations that fit theirs.
NOTE: For information about implementing a provider, see the guide How To Implement a Provider for the Java Cryptography Architecture.
How Provider Implementations Are Requested and Supplied
For each engine class in the API, a implementation instance is requested and instantiated by calling one of thegetInstancemethods on the engine class, specifying the name of the desired algorithm and, optionally, the name of the provider (or theProviderclass) whose implementation is desired.where EngineClassName is the desired engine type (MessageDigest/Cipher/etc). For example: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 NoSuchAlgorithmExceptionMessageDigest md = MessageDigest.getInstance("MD5"); KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");return an instance of the "MD5" MessageDigest and "DH" KeyAgreement objects, respectively.Appendix A 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,
getInstancesearches 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 installed 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_1andPROVIDER_2. Assume that:Now let's look at three scenarios:
PROVIDER_1implements SHA1withDSA, SHA-1, MD5, DES, and DES3.
PROVIDER_1has preference order 1 (the highest priority).
PROVIDER_2implements SHA1withDSA, MD5withRSA, MD2withRSA, MD2, MD5, RC4, RC5, DES, and RSA.PROVIDER_2has preference order 2.
- If we are looking for an MD5 implementation. Both providers supply such an implementation. The
PROVIDER_1implementation is returned sincePROVIDER_1has the highest priority and is searched first.- If we are looking for an MD5withRSA signature algorithm,
PROVIDER_1is first searched for it. No implementation is found, soPROVIDER_2is searched. Since an implementation is found, it is returned.- Suppose we are looking for a SHA1withRSA signature algorithm. Since no installed provider implements it, a
NoSuchAlgorithmExceptionis thrown.The
getInstancemethods 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 fromPROVIDER_1has not received such certification, while the DSA implementation ofPROVIDER_2has received it.A federal agency program would then have the following call, specifying
PROVIDER_2since it has the certified implementation:Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");In this case, if
PROVIDER_2was not installed, aNoSuchProviderExceptionwould 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
getProvidersmethod in theSecurityclass) 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
There are two possible ways to install the provider classes:
- 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.
- As an Installed/Bundled Extension
The provider will be considered an installed extension if it is placed in the standard extension directory. In Sun's JDK, that would be located in:
Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the JavaTM Runtime Environment (JRE) or the jre directory in the JavaTM JDK software. For example, if you have JDK 6 installed on Solaris in a directory named<java-home>/lib/ext [Unix] <java-home>\lib\ext [Windows]/home/user1/JDK1.6.0, or on Microsoft Windows in a directory namedC:\Java\JDK1.6.0, then you need to install the JAR file in the following directory:/home/user1/JDK1.6.0/jre/lib/ext [Unix] C:\JDK1.6.0\jre\lib\ext [Windows]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 namedC:\jre1.6.0, you need to install the JAR file in the following directory:For more information on how to deploy an extension, see How is an extension deployed?/home/user1/jre1.6.0/lib/ext [Unix] C:\jre1.6.0\lib\ext [Windows]Registering the Provider
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.
Static Registration
The configuration file is located in the following location:For each registered provider, this file should have a statement of the following form:<java-home>/lib/security/java.security [Unix] <java-home>\lib\security\java.security [Windows]security.provider.n=masterClassNameThis 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.
masterClassNamemust 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 theProviderclass. 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
SUNclass in thesun.security.providerpackage, and the corresponding java.security file entry is as follows:security.provider.5=sun.security.provider.SunTo 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 thejava.securityfile:security.provider.8=com.companyx.provider.ProviderXDynamic Registration
To register providers dynamically, applications call either theaddProviderorinsertProviderAtmethod in theSecurityclass. 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 Provider Permissions
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 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 policy configuration file grants all permissions to installed extensions (that is, installed in the extensions directory).
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.jarappears below. Such a statement could appear in a policy file. In this example, themyjce_provider.jarfile is assumed to be in the/localWorkdirectory.grant codeBase "file:/localWork/myjce_provider.jar" { permission java.lang.RuntimePermission "getProtectionDomain"; permission java.security.SecurityPermission "putProviderProperty.MyJCE"; };
ProviderClass MethodsEach
Providerclass instance has a (currently case-sensitive) name, a version number, and a string description of the provider and its services. You can query theProviderinstance for this information by calling the following methods:public String getName() public double getVersion() public String getInfo()The
SecurityClassThe
Securityclass 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 settingSecurityproperties, can only be executed by a trusted program. Currently, a "trusted program" is eitherThe 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 for more information.)
- a local application not running under a security manager, or
- an applet or application with permission to execute the specified method (see below).
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 keystore.
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:
This configuration file specifies that code loaded from a signed JAR file from beneath thegrant codeBase "file:/home/sysadmin/", signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; permission java.security.SecurityPermission "putProviderProperty.*"; };/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 namesysadminin 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
codeBaseis omitted:If this policy is in effect, code that comes in a JAR File signed bygrant signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };sysadmincan add/remove providers--regardless of where the JAR File originated.Here's an example without a signer:
In this case, code that comes from anywhere within thegrant codeBase "file:/home/sysadmin/" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };/home/sysadmin/directory on the local filesystem can add/remove providers. The code does not need to be signed.An example where neither
codeBasenorsignedByis included is: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 roguegrant { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };Cipherobject might capture and store the sensitive information it receives.)Managing Providers
The following tables summarize the methods in the
Securityclass you can use to query whichProviders are installed, as well as to install or remove providers at runtime.
Quering Providers Method Description static Provider[] getProviders()Returns an array containing all the installed providers (technically, the Providersubclass for each package provider). The order of theProviders in the array is their preference order.static Provider getProvider
(String providerName)Returns the ProvidernamedproviderName. It returnsnullif theProvideris not found.
Adding Providers Method Description static int
addProvider(Provider provider)Adds a Providerto the end of the list of installedProviders. It returns the preference position in which theProviderwas added, or-1if theProviderwas not added because it was already installed.static int insertProviderAt
(Provider provider, int position)Adds a new
Providerat 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 thanpositionare shifted up one position (towards the end of the list). This method returns the preference position in which theProviderwas added, or-1if theProviderwas not added because it was already installed.
Removing Providers Method Description static void removeProvider(String name)Removes the Providerwith 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
Securityclass maintains a list of system-wide security properties. These properties are similar to theSystemproperties, but are security-related. These properties can be set statically or dynamically. We have already seen an example of static security properties (that is, registering a provider statically via the"security.provider.i"security property). If you want to set properties dynamically, trusted programs can use the following methods:Note: the list of security providers is established during VM startup, therefore the methods described above must be used to alter the provider list.static String getProperty(String key) static void setProperty(String key, String datum)As a reminder, the configuration file is located in the following location:
<java-home>/lib/security/java.security [Unix] <java-home>\lib\security\java.security [Windows]The
SecureRandomClassThe
SecureRandomclass is an engine class that provides the functionality of a Random Number Generator (RNG). It differs from theRandomclass in that it produces cryptographically strong random numbers. If there is insufficient randomness in a generator, it makes it much easier to compromise your protection mechanisms. Random numbers are used throughout cryptography, such as generating cryptographic keys or algorithmic parameters.
![]()
Creating a
SecureRandomObjectAs with all engine classes, the way to get aSecureRandomobject is to call one of thegetInstance()static factory methods in theSecureRandomclass.
Seeding or Re-Seeding the
SecureRandomObjectThe
SecureRandomimplementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to agetInstancemethod with a call to one of thesetSeedmethods:Once thesynchronized public void setSeed(byte[] seed) public void setSeed(long seed)SecureRandomobject has been seeded, it will produce bits as random as the original seeds.At any time a
SecureRandomobject may be re-seeded using one of thesetSeedmethods. The given seed supplements, rather than replaces, the existing seed; therefore, repeated calls are guaranteed never to reduce randomness.Using a
SecureRandomObjectTo get random bytes, a caller simply passes an array of any length, which is then filled with random bytes:
synchronized public void nextBytes(byte[] bytes)Generating Seed Bytes
If desired, it is possible to invoke thegenerateSeedmethod to generate a given number of seed bytes (to seed other random number generators, for example):byte[] generateSeed(int numBytes)The
MessageDigestClassThe
MessageDigestclass is an engine class 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.![]()
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
MessageDigestObjectThe first step for computing a digest is to create a message digest instance.
MessageDigestobjects are obtained by using one of thegetInstance()static factory methods in theMessageDigestclass. The factory method returns an initialized message digest object. It thus does not need further initialization.Updating a Message Digest Object
The next step for calculating the digest of some data is 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
updatemethods:
void update(byte input) void update(byte[] input) void update(byte[] input, int offset, int len)Computing the Digest
After the data chunks have been supplied by calls to
update, the digest is computed using a call to one of thedigestmethods:
byte[] digest() byte[] digest(byte[] input) int digest(byte[] buf, int offset, int len)The first method return the computed digest. The second method does a final
update(input)with the input byte array before callingdigest(), which returns the digest byte array. The last method stores the computed digest in the provided bufferbuf, starting atoffset.lenis the number of bytes inbufallotted for the digest, the method returns the number of bytes actually stored inbuf. If there is not enough room in the buffer, the method will throw an exception.Please see the Computing a
MessageDigestexample in the Code Examples section for more details.The
SignatureClassTheSignatureclass is an engine class 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: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.
- 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.
![]()
A
Signatureobject is initialized for signing with a Private Key and is given the data to be signed. The resulting signature bytes are typically kept with the signed data. When verification is needed, anotherSignatureobject is created and initialized for verification and given the corresponding Public Key. The data and the signature bytes are fed to the signature object, and if the data and signature match, theSignatureobject reports success.Even though a signature seems similar to a message digest, they have very different purposes in the type of protection they provide. In fact, algorithms such as "SHA1WithRSA" use the message digest "SHA1" to initially "compress" the large data sets into a more manageable form, then sign the resulting 20 byte message digest with the "RSA" algorithm.
Please see the Examples section for an example of signing and verifying data.
SignatureObject StatesSignatureobjects are modal objects. This means that aSignatureobject 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
Signatureobject may have are:When it is first created, a
UNINITIALIZEDSIGNVERIFYSignatureobject is in theUNINITIALIZEDstate. TheSignatureclass defines two initialization methods,initSignandinitVerify, which change the state toSIGNandVERIFY, respectively.Creating a
SignatureObjectThe first step for signing or verifying a signature is to create aSignatureinstance.Signatureobjects are obtained by using one of theSignaturegetInstance()static factory methods.Initializing a
SignatureObjectA
Signatureobject 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:
This method puts thefinal void initSign(PrivateKey privateKey)Signatureobject in theSIGNstate.If instead the
Signatureobject 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
Signatureobject in theVERIFYstate.Signing
If the
Signatureobject has been initialized for signing (if it is in theSIGNstate), the data to be signed can then be supplied to the object. This is done by making one or more calls to one of theupdatemethods:
final void update(byte b) final void update(byte[] data) final void update(byte[] data, int off, int len)Calls to the
updatemethod(s) should be made until all the data to be signed has been supplied to theSignatureobject.To generate the signature, simply call one of the
signmethods: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 the Standard Names document for more information about the use of ASN.1 encoding in the Java Cryptography Architecture.
A call to a
signmethod resets the signature object to the state it was in when previously initialized for signing via a call toinitSign. That is, the object is reset and available to generate another signature with the same private key, if desired, via new calls toupdateandsign.Alternatively, a new call can be made to
initSignspecifying a different private key, or toinitVerify(to initialize theSignatureobject to verify a signature).Verifying
If the
Signatureobject has been initialized for verification (if it is in theVERIFYstate), 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 theupdatemethods:final void update(byte b) final void update(byte[] data) final void update(byte[] data, int off, int len)Calls to the
updatemethod(s) should be made until all the data to be verified has been supplied to theSignatureobject. The signature can now be verified by calling one of theverifymethods:final boolean verify(byte[] signature) final boolean verify(byte[] signature, int offset, int length)The argument must be a byte array containing the signature. 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
signmethods.The
verifymethod returns abooleanindicating whether or not the encoded signature is the authentic signature of the data supplied to theupdatemethod(s).A call to the
verifymethod resets the signature object to its state when it was initialized for verification via a call toinitVerify. That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call toinitVerify.Alternatively, a new call can be made to
initVerifyspecifying a different public key (to initialize theSignatureobject for verifying a signature from a different entity), or toinitSign(to initialize theSignatureobject for generating a signature).The Cipher Class
The
Cipherclass 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.
Creating a Cipher Object
Cipherobjects are obtained by using one of theCiphergetInstance()static factory methods. 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.
If no mode or padding is specified, provider-specific default values for the mode and padding scheme are used. For example, the
SunJCEprovider usesECBas the default mode, andPKCS5Paddingas the default padding scheme forDES,DES-EDEandBlowfishciphers. This means that in the case of theSunJCEprovider:
Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");andCipher c1 = Cipher.getInstance("DES");are equivalent statements.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
SunJCEprovider 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 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
getInstancemust be initialized for one of four modes, which are defined as final integer constants in theCipherclass. 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.Keyinto bytes so that the key can be securely transported.- UNWRAP_MODE
- Unwrapping of a previously wrapped key into a
java.security.Keyobject.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
initmethods: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
initmethod, 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
initmethod, anInvalidKeyExceptionorInvalidAlgorithmParameterExceptionexception will be raised, depending on theinitmethod that has been used.See the section about Managing Algorithm Parameters for more details.
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
doFinalmethods: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
updatemethods: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
doFinalmethods (if there is still some input data left for the last step), or by one of the followingdoFinalmethods (if there is no input data left for the last step):public byte[] doFinal(); public int doFinal(byte[] output, int outputOffset);All the
doFinalmethods take care of any necessary padding (or unpadding), if padding (or unpadding) has been requested as part of the specified transformation.A call to
doFinalresets the Cipher object to the state it was in when initialized via a call toinit. That is, the Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call toinit) more data.Wrapping and Unwrapping Keys
Wrapping a key enables secure transfer of the key from one place to another.
The
wrap/unwrapAPI 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 theunwrap:
- the name of the key algorithm, and
- the type of the wrapped key (one of
Cipher.SECRET_KEY,Cipher.PRIVATE_KEY, orCipher.PUBLIC_KEY).The key algorithm name can be determined by calling the
getAlgorithmmethod 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,
wrappedKeyis the bytes returned from the previous call to wrap,wrappedKeyAlgorithmis the algorithm associated with the wrapped key, andwrappedKeyTypeis the type of the wrapped key. This must be one ofCipher.SECRET_KEY,Cipher.PRIVATE_KEY, orCipher.PUBLIC_KEY.Managing Algorithm Parameters
The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the
initmethod by the application or generated by the underlying implementation itself, can be retrieved from the Cipher object by calling itsgetParametersmethod, which returns the parameters as ajava.security.AlgorithmParametersobject (ornullif no parameters are being used). If the parameter is an initialization vector (IV), it can also be retrieved by calling thegetIVmethod.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 as follows:
import javax.crypto.*; import java.security.AlgorithmParameters; // get cipher object for password-based encryption Cipher c = Cipher.getInstance("PBEWithMD5AndDES"); // 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();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("PBEWithMD5AndDES"); // initialize with parameter encoding from above algParams.init(encodedAlgParams); // get cipher object for password-based encryption Cipher c = Cipher.getInstance("PBEWithMD5AndDES"); // 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);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
getParametersmethod of your Cipher object and checking the value returned. A return value ofnullindicates that no parameters were used.The following cipher algorithms implemented by the
SunJCEprovider 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.IvParameterSpecclass can be used to initialize a Cipher object with a given IV.- PBEWithMD5AndDES uses a set of parameters, comprising a salt and an iteration count. The
javax.crypto.spec.PBEParameterSpecclass can be used to initialize a Cipher object implementing PBEWithMD5AndDES 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
SealedObjectclass. This class attaches the parameters used for sealing (encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).Cipher Output Considerations
Some of the
updateanddoFinalmethods 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 ClassesThere are some helper classes which interally useCiphers to provide easy access to common cipher uses.The Cipher Stream Classes
A simple, secure, stream-based communication object can be created by combining existing
InputStream/OutputStreams withCipherobjects.The CipherInputStream Class
This class is a
FilterInputStreamthat encrypts or decrypts the data passing through it. It is composed of anInputStream, or one of its subclasses, and aCipher. CipherInputStream represents a secure input stream into which a Cipher object has been interposed. Thereadmethods 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.FilterInputStreamandjava.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, theskip(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.
As an example of its usage, suppose
cipher1has been initialized for encryption. 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();The above program reads and encrypts the content from the file
/tmp/a.txtand then stores the result (the encrypted bytes) in/tmp/b.txt.The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that
cipher1andcipher2have 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 above program copies the content from file
/tmp/a.txtto/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
CipherInputStreamwill 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.The CipherOutputStream Class
This class is a
FilterOutputStreamthat encrypts or decrypts the data passing through it. It is composed of anOutputStream, or one of its subclasses, and aCipher. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. Thewritemethods 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.OutputStreamandjava.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.
As an example of its usage, suppose
cipher1has been initialized for encryption. The code below 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();The above program reads the content from the file
/tmp/a.txt, then encrypts and stores the result (the encrypted bytes) in/tmp/b.txt.The following example demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that
cipher1andcipher2have 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 above program copies the content from file
/tmp/a.txtto/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
CipherOutputStreambefore the data will be encrypted and sent to the underlying output stream.There is one other important difference between the
flushandclosemethods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:
flushflushes 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.closecloses the underlying OutputStream and releases any system resources associated with it. It invokes thedoFinalmethod of the encapsulated Cipher object, causing any bytes buffered by it to be processed and written out to the underlying stream by calling itsflushmethod.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.Serializableinterface, one can create aSealedObjectthat 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
SealedObjectfrom the object to be sealed and a fully initializedCipherobject 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 ofSealedObject:// 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
Cipherobject 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
getObjectmethod 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
Macclass provides the functionality of a Message Authentication Code (MAC). Please refer to the code example.Creating a
MacObjectMacobjects are obtained by using one of theMacgetInstance()static factory methods.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
initmethods: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.SecretKeyinterface. This could be an object returned byjavax.crypto.KeyGenerator.generateKey(), or one that is the result of a key agreement protocol, as returned byjavax.crypto.KeyAgreement.generateSecret(), or an instance ofjavax.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
SunJCEprovider). With others, however, the (secret-)key algorithm does matter, and anInvalidKeyExceptionis 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
doFinalmethod:public byte[] doFinal(byte[] input);To compute the MAC of some data in multiple steps, call one of the
updatemethods: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
doFinalmethod (if there is still some input data left for the last step), or by one of the followingdoFinalmethods (if there is no input data left for the last step):public byte[] doFinal(); public void doFinal(byte[] output, int outOffset);
KeyInterfacesTo 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.
The
java.security.Keyinterface is the top-level interface for all opaque keys. It defines the functionality shared by all opaque key objects.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
Keyinterface (see below):getAlgorithm,getFormat, andgetEncoded.This is in contrast to a transparent representation, in which you can access each key material value individually, through one of the
getmethods defined in the corresponding specification class.All opaque keys have three characteristics:
Keys are generally obtained through key generators such as KeyGenerator and KeyPairGenerator, certificates, key specifications (using a
- An Algorithm
- The key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as
AES,DSAorRSA), which will work with those algorithms and with related algorithms (such asMD5withRSA,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()KeyFactory), or aKeyStoreimplementation accessing a keystore database used to manage keys. It is possible to parse encoded keys, in an algorithm-dependent manner, using aKeyFactory.It is also possible to parse certificates, using a
CertificateFactory.Here is a list of interfaces which extend the
Keyinterface in thejava.security.interfacesandjavax.crypto.interfacespackages:
The
PublicKeyandPrivateKeyInterfacesThe
PublicKeyandPrivateKeyinterfaces (which both extend theKeyinterface) are methodless interfaces, used for type-safety and type-identification.The
KeyPairClassThe
KeyPairclass 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
Keyobjects and key specifications (KeySpecs) are two different representations of key data.Ciphers useKeyobjects 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
getmethods defined in the corresponding specification class. For example,DSAPrivateKeySpecdefinesgetX,getP,getQ, andgetGmethods, to access the private keyx, and the DSA algorithm parameters used to calculate the key: the primep, the sub-primeq, and the baseg. 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
Keyinterface, 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 theKeyinterface:getAlgorithm,getFormat, andgetEncoded.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, andg(seeDSAPrivateKeySpec), or it may be specified using its DER encoding (seePKCS8EncodedKeySpec).The
KeyFactoryandSecretKeyFactoryclasses can be used to convert between opaque and transparent key representations (that is, betweenKeys andKeySpecs, assuming that the operation is possible. (For example, private keys on smart cards might not be able leave the card. SuchKeys are not convertible.)In the following sections, we discuss the key specification interfaces and classes in the
java.security.specpackage.The
KeySpecInterfaceThis 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
KeySpecSubinterfacesLike theKeyinterface, there are a similar set ofKeySpecinterfaces.
The
EncodedKeySpecClassThis abstract class (which implements theKeySpecinterface) represents a public or private key in encoded format. ItsgetEncodedmethod returns the encoded key:and itsabstract byte[] getEncoded();getFormatmethod returns the name of the encoding format:abstract String getFormat();See the next sections for the concrete implementations
PKCS8EncodedKeySpecandX509EncodedKeySpec.The
PKCS8EncodedKeySpecClassThis class, which is a subclass ofEncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS8 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the PKCS8 standard. ItsgetFormatmethod returns the string "PKCS#8".The
X509EncodedKeySpecClassThis class, which is a subclass ofEncodedKeySpec, represents the DER encoding of a public key, according to the format specified in the X.509 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the X.509 standard. ItsgetFormatmethod returns the string "X.509".Of Generators and Factories
Newcomers to Java and the JCA APIs in particular sometimes do not grasp the distinction between 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 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
KeySpec, but needs to convert them into aPrivateKeyobject that can be used by aKeyAgreementobject, or vice-versa. Or they might have the byte array of a certificate, but need to use aCertificateFactoryto convert it into aX509Certificateobject. Applications use factory objects to do the conversion.The
KeyFactoryClassTheKeyFactoryclass is an engine class designed to perform conversions between opaque cryptographicKeys and key specifications (transparent representations of the underlying key material).
![]()
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, andg(seejava.security.spec.DSAPublicKeySpec), or it may be specified using its DER encoding according to the X.509 standard (seeX509EncodedKeySpec).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
X509EncodedKeySpectoDSAPublicKeySpec, you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications andKeyFactorysection.Creating a
KeyFactoryObject
KeyFactoryobjects are obtained by using one of theKeyFactorygetInstance()static factory methods.Converting Between a Key Specification and a Key Object
If you have a key specification for a public key, you can obtain an opaque
PublicKeyobject from the specification by using thegeneratePublicmethod:PublicKey generatePublic(KeySpec keySpec)Similarly, if you have a key specification for a private key, you can obtain an opaque
PrivateKeyobject from the specification by using thegeneratePrivatemethod:PrivateKey generatePrivate(KeySpec keySpec)Converting Between a Key Object and a Key Specification
If you have a
Keyobject, you can get a corresponding key specification object by calling thegetKeySpecmethod:KeySpec getKeySpec(Key key, Class keySpec)keySpecidentifies the specification class in which the key material should be returned. It could, for example, beDSAPublicKeySpec.class, to indicate that the key material should be returned in an instance of theDSAPublicKeySpecclass.Please see the Examples section for more details.
The SecretKeyFactory Class
This class represents a factory for secret keys. Unlike
KeyFactory, ajavax.crypto.SecretKeyFactoryobject operates only on secret (symmetric) keys, whereas ajava.security.KeyFactoryobject processes the public and private key components of a key pair.
![]()
Key factories are used to convert
Keys (opaque cryptographic keys of typejava.security.Key) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.Objects of type
java.security.Key, of whichjava.security.PublicKey,java.security.PrivateKey, andjavax.crypto.SecretKeyare subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and may be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value
y, the prime modulusp, and the baseg, and you feed the same specification to Diffie-Hellman key factories from different providers, the resultingPublicKeyobjects will most likely have different underlying implementations.A provider should document the key specifications supported by its secret key factory. For example, the
SecretKeyFactoryfor DES keys supplied by theSunJCEprovider supportsDESKeySpecas a transparent representation of DES keys, theSecretKeyFactoryfor DES-EDE keys supportsDESedeKeySpecas a transparent representation of DES-EDE keys, and theSecretKeyFactoryfor PBE supportsPBEKeySpecas a transparent representation of the underlying password.The following is an example of how to use a
SecretKeyFactoryto convert secret key data into aSecretKeyobject, which can be used for a subsequentCipheroperation:// 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
SecretKeyis based on the provider ofKeyFactory.An alternative, provider-independent way of creating a functionally equivalent
SecretKeyobject from the same key material is to use thejavax.crypto.spec.SecretKeySpecclass, which implements thejavax.crypto.SecretKeyinterface:byte[] desKeyData = { (byte)0x01, (byte)0x02, ...}; SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");Creating a
SecretKeyFactoryObject
SecretKeyFactoryobjects are obtained by using one of theSecretKeyFactorygetInstance()static factory methods.Converting Between a Key Specification and a Secret Key Object
If you have a key specification for a secret key, you can obtain an opaque
SecretKeyobject from the specification by using thegenerateSecretmethod:SecretKey generateSecret(KeySpec keySpec)Converting Between a Secret Key Object and a Key Specification
If you have a
Secret Keyobject, you can get a corresponding key specification object by calling thegetKeySpecmethod:KeySpec getKeySpec(Key key, Class keySpec)keySpecidentifies the specification class in which the key material should be returned. It could, for example, beDESKeySpec.class, to indicate that the key material should be returned in an instance of theDESKeySpecclass.The
KeyPairGeneratorClassThe
KeyPairGeneratorclass is an engine class used to generate pairs of public and private keys.
![]()
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.
Please see the Examples section for examples of calls to the methods documented below.
Creating a
KeyPairGeneratorAll key pair generation starts with a
KeyPairGenerator.KeyPairGeneratorobjects are obtained by using one of theKeyPairGeneratorgetInstance()static factory methods.Initializing a
KeyPairGeneratorA 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 the Standard Names document for information about the keysizes for specific algorithms.)
An
initializemethod takes two universally shared types of arguments:Anothervoid initialize(int keysize, SecureRandom random)initializemethod takes only akeysizeargument; 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
initializemethods, 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
SUNprovider uses a set of precomputed values for thep,q, andgparameters. If the modulus size is not one of the above values, theSUNprovider 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
initializemethods that have anAlgorithmParameterSpecargument. One also has aSecure