Provider ClassSecurity ClassSecureRandomClassMessageDigestClassSignature ClassCipher ClassCipher-basedClassesMac ClassKey InterfacesKeyPair ClassKey Specification Interfacesand ClassesKeyFactoryClassSecretKeyFactoryClassKeyPairGeneratorClassKeyGeneratorClassKeyAgreementClassCertificateFactory ClassMessageDigestObjectKey Specifications andKeyFactoryThe Java platform strongly emphasizes security, includinglanguage safety, cryptography, public key infrastructure,authentication, secure communication, and access control.
The JCA is a major piece of the platform, and contains a"provider" architecture and a set of APIs for digital signatures,message digests (hashes), certificates and certificate validation,encryption (symmetric/asymmetric block/stream ciphers), keygeneration and management, and secure random number generation, toname a few. These APIs allow developers to easily integratesecurity into their application code. The architecture was designedaround the following principles:
Implementation independence: Applications do not need toimplement security algorithms. Rather, they can request securityservices from the Java platform. Security services are implementedin providers (see below), which are plugged into the Java platformvia a standard interface. An application may rely on multipleindependent providers for security functionality.
Implementation interoperability: Providers areinteroperable across applications. Specifically, an application isnot bound to a specific provider, and a provider is not bound to aspecific application.
Algorithm extensibility: The Java platform includes anumber of built-in providers that implement a basic set of securityservices that are widely used today. However, some applications mayrely on emerging standards not yet implemented, or on proprietaryservices. The Java platform supports the installation of customproviders that implement such services.
Other cryptographic communication libraries available in the JDKuse the JCA provider architecture, but are described elsewhere. TheJava Secure Socket Extension(JSSE) provides access to Secure Socket Layer (SSL) andTransport Layer Security (TLS) implementations. TheJava Generic Security Services(JGSS) (via Kerberos) APIs, and theSimple Authentication and SecurityLayer (SASL) can also be used for securely exchanging messagesbetween communicating applications.
Prior to JDK 1.4, the JCE was an unbundled product, and as such,the JCA and JCE were regularly referred to as separate, distinctcomponents. As JCE is now bundled in the JDK, the distinction isbecoming less apparent. Since the JCE uses the same architecture asthe JCA, the JCE should be more properly thought of as a part ofthe JCA.
The JCA within the JDK includes two software components:
java.security,javax.crypto,javax.crypto.spec, andjavax.crypto.interfaces.Sun,SunRsaSign,SunJCE, which contain theactual cryptographic implementations.Whenever a specific JCA provider is mentioned, it will bereferred to explicitly by the provider's name.
WARNING: The JCA makes it easy to incorporate securityfeatures into your application. However, this document does notcover the theory of security/cryptography beyond an elementaryintroduction to concepts necessary to discuss the APIs. Thisdocument also does not cover the strengths/weaknesses of specificalgorithms, not does it cover protocol design. Cryptography is anadvanced 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: DONOT simply copy random code and expect it to fully solve your usagescenario. Many applications have been deployed that containsignificant security or performance problems because the wrong toolor algorithm was selected.
The JCA was designed around these principles:
Implementation independence and algorithm independence arecomplementary; you can use cryptographic services, such as digitalsignatures and message digests, without worrying about theimplementation details or even the algorithms that form the basisfor these concepts. While complete algorithm-independence is notpossible, the JCA provides standardized, algorithm-specific APIs.When implementation-independence is not desirable, the JCA letsdevelopers indicate a specific implementation.
Algorithm independence is achieved by defining types ofcryptographic "engines" (services), and defining classes thatprovide the functionality of these cryptographic engines. Theseclasses are calledengine classes, and examples are theMessageDigest,Signature,KeyFactory,KeyPairGenerator, andCipher classes.
Implementation independence is achieved using a "provider"-basedarchitecture. The termCryptographicService Provider (CSP) (used interchangeably with "provider" inthis document) refers to a package or set of packages thatimplement one or more cryptographic services, such as digitalsignature algorithms, message digest algorithms, and key conversionservices. A program may simply request a particular type of object(such as aSignature object) implementing a particularservice (such as the DSA signature algorithm) and get animplementation from one of the installed providers. If desired, aprogram may instead request an implementation from a specificprovider. Providers may be updated transparently to theapplication, for example when faster or more secure versions areavailable.
Implementation interoperability means that variousimplementations can work with each other, use each other's keys, orverify each other's signatures. This would mean, for example, thatfor the same algorithms, a key generated by one provider would beusable by another, and a signature generated by one provider wouldbe verifiable by another.
Algorithm extensibility means that new algorithms that fit inone of the supported engine classes can be added easily.
java.security.Provider is the base class for allsecurity providers. Each CSP contains an instance of this classwhich contains the provider's name and lists all of the securityservices/algorithms it implements. When an instance of a particularalgorithm is needed, the JCA framework consults the provider'sdatabase, and if a suitable match is found, the instance iscreated.
Providers contain a package (or a set of packages) that supplyconcrete implementations for the advertised cryptographicalgorithms. Each JDK installation has one or more providersinstalled and configured by default. Additional providers may beadded statically or dynamically (see theProvider andSecurityclasses). Clients may configure their runtime environment tospecify the providerpreference order. The preference orderis the order in which providers are searched for requested serviceswhen no specific provider is requested.
To use the JCA, an application simply requests a particular typeof object (such as aMessageDigest) and a particularalgorithm or service (such as the "SHA-256" algorithm), and gets animplementation from one of the installed providers. Alternatively,the program can request the objects from a specific provider. Eachprovider has a name used to refer to it.
md = MessageDigest.getInstance("SHA-256"); md = MessageDigest.getInstance("SHA-256", "ProviderC");The following figures illustrate requesting an "SHA-256" messagedigest implementation. The figures show three different providersthat implement various message digest algorithms ("SHA-256", "SHA-384",and "SHA-512"). The providers are ordered by preferencefrom left to right (1-3). In the first illustration, an applicationrequests an SHA-256 algorithm implementationwithout specifyinga provider name. The providers are searched in preference order andthe implementation from the first provider supplying thatparticular algorithm, ProviderB, is returned. In the second figure,the application requests the SHA-256 algorithm implementationfrom aspecific provider, ProviderC. This time the implementation fromProviderC is returned, even though a provider with a higherpreference order, ProviderB, also supplies an SHA-256implementation.
![]() | ![]() |
| Figure 1a: Provider searching | Figure 1b: Specific providerrequested |
Description of Figure 1a Provider: searching and Figure 1b: Specific providerrequested
Cryptographic implementations in the JDK are distributed viaseveral different providers (Sun,SunJSSE,SunJCE,SunRsaSign)primarily for historical reasons, but to a lesser extent by thetype of functionality and algorithms they provide. Other Javaruntime environments may not necessarily contain these Sunproviders, so applications should not request an provider-specificimplementation unless it is known that a particular provider willbe available.
The JCA offers a set of APIs that allow users to query whichproviders are installed and what services they support.
This architecture also makes it easy for end-users to addadditional providers. Many third party provider implementations arealready available. SeeTheProvider Class for more information on howproviders are written, installed, and registered.
As mentioned earlier,algorithm independence is achievedby defining a generic high-level Application Programming Interface(API) that all applications use to access a service type.Implementation independence is achieved by having allprovider implementations conform to well-defined interfaces.Instances of engine classes are thus "backed" by implementationclasses which have the same method signatures. Application callsare routed through the engine class and are delivered to theunderlying backing implementation. The implementation handles therequest and return the proper results.
The application API methods in each engine class are routed tothe provider's implementations through classes that implement thecorresponding Service Provider Interface (SPI). That is, for eachengine class, there is a corresponding abstract SPI class whichdefines the methods that each cryptographic service provider'salgorithm must implement. The name of each SPI class is the same asthat of the corresponding engine class, followed bySpi. For example, theSignature engineclass provides access to the functionality of a digital signaturealgorithm. The actual provider implementation is supplied in asubclass ofSignatureSpi. Applications call the engineclass' API methods, which in turn call the SPI methods in theactual implementation.
Each SPI class is abstract. To supply the implementation of aparticular type of service for a specific algorithm, a providermust subclass the corresponding SPI class and provideimplementations for all the abstract methods.
For each engine class in the API, implementation instances arerequested and instantiated by calling thegetInstance()factory method in the engineclass. A factory method is a static method that returns an instanceof a class. The engine classes use the framework provider selectionmechanism described above to obtain the actual backingimplementation (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 SPIobject. All API methods of an API object are declared final andtheir implementations invoke the corresponding SPI methods of theencapsulated SPI object.
To make this clearer, review the following code andillustration:
import javax.crypto.*; Cipher c = Cipher.getInstance("AES"); c.init(ENCRYPT_MODE, key);
Description ofExample of How Application Retrieves "AES" Cipher Instance
Here an application wants an "AES"javax.crypto.Cipher instance, and doesn't care whichprovider is used. The application calls thegetInstance() factory methods of theCipher engine class, which in turn asks the JCAframework to find the first provider instance that supports "AES".The framework consults each installed provider, and obtains theprovider's instance of theProvider class. (Recallthat theProvider class is a database of availablealgorithms.) The framework searches each provider, finally findinga suitable entry in CSP3. This database entry points to theimplementation classcom.foo.AESCipher which extendsCipherSpi, and is thus suitable for use by theCipher engine class. An instance ofcom.foo.AESCipher is created, and is encapsulated in anewly-created instance ofjavax.crypto.Cipher, whichis returned to the application. When the application now does theinit() operation on theCipher instance,theCipher engine class routes the request into thecorrespondingengineInit() backing method in thecom.foo.AESCipher class.
Appendix A lists the Standard Names definedfor the Java environment. Other third-party providers may definetheir own implementations of these services, or even additionalservices.
A database called a "keystore" can be used to manage arepository of keys and certificates. Keystores are available toapplications that need data for authentication, encryption, orsigning purposes.
Applications can access a keystore via an implementation of theKeyStore class, which is in thejava.security package.The recommended keystore type (format) is "pkcs12", which is based on the RSAPKCS12 Personal Information Exchange Syntax Standard. The default keystore typeis "jks", which is a proprietary format. Other keystore formats are available,such as "jceks", which is an alternate proprietary keystore format, and"pkcs11", which is based on the RSA PKCS11 Standard and supports access tocryptographic tokens such as hardware security modules and smartcards.
Applications can choose different keystore implementations fromdifferent providers, using the same provider mechanism describedabove.
See theKey Management section formore information.
This section introduces the major JCA APIs.
An engine class provides the interface to a specific type ofcryptographic service, independent of a particular cryptographicalgorithm or provider. The engines either provide:
The following engine classes are available:
SecureRandom: used togenerate random or pseudo-random numbers.MessageDigest: usedto calculate the message digest (hash) of specified data.Signature: initializedwith keys, these are used to sign data and verify digitalsignatures.Cipher: initialized with keys, these areused for encrypting/decrypting data. There are various types of algorithms:symmetric bulk encryption (e.g. AES), asymmetric encryption (e.g. RSA), andpassword-based encryption (e.g. PBE).MessageDigests, these also generate hash values, butare first initialized with keys to protect the integrity ofmessages.KeyFactory: used toconvert existing opaque cryptographic keys of typeKey into key specifications (transparentrepresentations of the underlying key material), and viceversa.SecretKeyFactory:used to convert existing opaque cryptographic keys of typeSecretKey into key specifications(transparent representations of the underlying key material), andvice versa.SecretKeyFactorys are specializedKeyFactorys that create secret (symmetric) keysonly.KeyPairGenerator:used to generate a new pair of public and private keys suitable foruse with a specified algorithm.KeyGenerator: used togenerate new secret keys for use with a specified algorithm.KeyAgreement: used bytwo or more parties to agree upon and establish a specific key touse for a particular cryptographic operation.AlgorithmParameters: usedto store the parameters for a particular algorithm, includingparameter encoding and decoding.AlgorithmParameterGenerator: used to generate a set of AlgorithmParameters suitable for aspecified algorithm.KeyStore: used to createand manage akeystore. A keystore is a database of keys.Private keys in a keystore have a certificate chain associated withthem, which authenticates the corresponding public key. A keystorealso contains certificates from trusted entities.CertificateFactory: used tocreate public key certificates and Certificate Revocation Lists(CRLs).CertPathBuilder:used to build certificate chains (also known as certificationpaths).CertPathValidator:used to validate certificate chains.CertStore:used to retrieveCertificates andCRLsfrom a repository.NOTE: Agenerator creates objects with brand-newcontents, whereas afactory creates objects from existingmaterial (for example, an encoding).
This section discusses the core classes and interfaces providedin the JCA:
Provider andSecurity classes,SecureRandom,MessageDigest,Signature,Cipher,Mac,KeyFactory,SecretKeyFactory,KeyPairGenerator,KeyGenerator,KeyAgreement,AlgorithmParameters,AlgorithmParameterGenerator,KeyStore, andCertificateFactory, engineclasses,Key interfaces andclasses,NOTE: For more information on theCertPathBuilder,CertPathValidator,andCertStoreengine classes, please see theJava PKI Programmer'sGuide.
The guide will cover the most useful high-level classes first(Provider,Security,SecureRandom,MessageDigest,Signature,Cipher, andMac),then delve into the various support classes. For now, it issufficient to simply say that Keys (public, private, and secret)are generated and represented by the various JCA classes, and areused by the high-level classes as part of their operation.
This section shows the signatures of the main methods in eachclass and interface. Examples for some of these classes(MessageDigest,Signature,KeyPairGenerator,SecureRandom,KeyFactory, and key specification classes) aresupplied in the correspondingExamplessections.
The complete reference documentation for the relevant SecurityAPI packages can be found in the package summaries:
java.securityjavax.cryptojava.security.certjava.security.specjavax.crypto.specjava.security.interfacesjavax.crypto.interfacesProviderClassThe term "Cryptographic Service Provider" (used interchangeablywith "provider" in this document) refers to a package or set ofpackages that supply a concrete implementation of a subset of theJDK Security API cryptography features. TheProviderclass is the interface to such a package or set ofpackages. It has methods for accessing the provider name, versionnumber, and other information. Please note that in addition toregistering implementations of cryptographic services, theProvider class can also be used to registerimplementations of other security services that might get definedas 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 andcreates a subclass of theProvider class. Theconstructor of theProvider subclass sets the valuesof various properties; the JDK Security API uses these values tolook up the services that the provider implements. In other words,the subclass specifies the names of the classes implementing theservices.

Description of Figure Exampleof Provider Subclass
There are several types of services that can be implemented byprovider packages; for more information, seeEngine Classes and Algorithms.
The different implementations may have differentcharacteristics. Some may be software-based, while others may behardware-based. Some may be platform-independent, while others maybe platform-specific. Some provider source code may be availablefor review and evaluation, while some may not. The JCA lets bothend-users and developers decide what their needs are.
In this section we explain how end-users install thecryptography implementations that fit their needs, and howdevelopers request the implementations that fit theirs.
NOTE: For information about implementing a provider, seethe guideHow To Implement aProvider for the Java Cryptography Architecture.
For eachengine class in the API, aimplementation instance is requested and instantiated by callingone of thegetInstance methods on the engine class,specifying the name of the desired algorithm and, optionally, thename of the provider (or theProvider class) whoseimplementation is desired.
staticEngineClassName getInstance(String algorithm) throws NoSuchAlgorithmExceptionstaticEngineClassName getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderExceptionstaticEngineClassName getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmExceptionwhereEngineClassName is the desired engine type(MessageDigest/Cipher/etc). For example:
MessageDigest md = MessageDigest.getInstance("SHA-256"); KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");return an instance of the "SHA-256" MessageDigest and "DH" KeyAgreement objects,respectively.Appendix A contains the list of names thathave been standardized for use with the Java environment. Someproviders may choose to also include alias names that also refer tothe same algorithm. For example, the "SHA256" algorithm might bereferred to as "SHA-256". Applications should use standard namesinstead of an alias, as not all providers may alias algorithm namesin the same way.
NOTE: The algorithm name is not case-sensitive. Forexample, all the following calls are equivalent:
MessageDigest.getInstance("SHA256")MessageDigest.getInstance("sha256")MessageDigest.getInstance("sHa256")If no provider is specified,getInstance searchesthe registered providers for an implementation of the requestedcryptographic service associated with the named algorithm. In anygiven Java Virtual Machine (JVM), providers areinstalled in a givenpreferenceorder, the order in which the provider list is searched if aspecific provider is not requested. For example, suppose there aretwo providers installed in a JVM,PROVIDER_1 andPROVIDER_2. Assume that:
PROVIDER_1 implements SHA-256 and DESede.PROVIDER_1 has preference order 1 (the highestpriority).PROVIDER_2 implements SHA256withDSA, SHA-256, RC5, and RSA.PROVIDER_2 has preference order 2.PROVIDER_1implementation is returned sincePROVIDER_1 has thehighest priority and is searched first.PROVIDER_1 is first searched for it. No implementationis found, soPROVIDER_2 is searched. Since animplementation is found, it is returned.NoSuchAlgorithmException is thrown.ThegetInstance methods that include a providerargument are for developers who want to specify which provider theywant an algorithm from. A federal agency, for example, will want touse a provider implementation that has received federalcertification. Let's assume that the SHA256withDSA implementationfromPROVIDER_1 has not received such certification,while the DSA implementation ofPROVIDER_2 hasreceived it.
A federal agency program would then have the following call,specifyingPROVIDER_2 since it has the certifiedimplementation:
Signature dsa = Signature.getInstance("SHA256withDSA", "PROVIDER_2");In this case, ifPROVIDER_2 was not installed, aNoSuchProviderException would be thrown, even ifanother installed provider implements the algorithm requested.
A program also has the option of getting a list of all theinstalled providers (using thegetProviders method intheSecurity class) andchoosing one from the list.
NOTE: General purpose applicationsSHOULD NOTrequest cryptographic services from specific providers. Otherwise,applications are tied to specific providers which may not beavailable on other Java implementations. They also might not beable to take advantage of available optimized providers (forexample hardware accelerators via PKCS11 or native OSimplementations such as Microsoft's MSCAPI) that have a higherpreference order than the specific requested provider.
In order to be used, a cryptographic provider must first beinstalled, then registered either statically or dynamically. Thereare a variety of Sun providers shipped with this release(SUN,SunJCE,SunJSSE,SunRsaSign, etc.) that are already installed andregistered. The following sections describe how to install andregister additional providers.
There are two possible ways to install the provider classes:
Place a zip or JAR file containing the classes anywhere in yourclasspath. Some algorithms types (Ciphers) require the provider bea signed Jar file.
The provider will be considered aninstalled extensionif it is placed in the standard extension directory. In the JDK,that would be located in:
<java-home>/lib/ext<java-home>\lib\extHere<java-home> refers to the directory wherethe runtime software is installed, which is the top-level directoryof the Java Runtime Environment (JRE) or thejre directoryin the Java JDK software. For example, if you have JDK 6 installedon Solaris in a directory named/home/user1/JDK1.6.0,or on Microsoft Windows in a directory namedC:\Java\JDK1.6.0, then you need to install the JARfile in the following directory:
/home/user1/JDK1.6.0/jre/lib/extC:\JDK1.6.0\jre\lib\extSimilarly, if you have the JRE 6 installed on Solaris in adirectory named/home/user1/jre1.6.0, or on MicrosoftWindows in a directory namedC:\jre1.6.0, you need toinstall the JAR file in the following directory:
/home/user1/jre1.6.0/lib/extC:\jre1.6.0\lib\extThe next step is to add the provider to your list of registeredproviders. Providers can be registered statically by editing asecurity properties configuration file before running a Javaapplication, or dynamically by calling a method at runtime. Toprevent the installation of rogue providers being added to theruntime environment, applications attempting to dynamicallyregister a provider must possess the appropriate runtimeprivilege.
The configuration file is located in the following location:
<java-home>/lib/security/java.security<java-home>\lib\security\java.securityFor each registered provider, this file should have a statementof the following form:
security.provider.n=masterClassName
This declares a provider, and specifies its preference ordern. The preference order is the order in which providers aresearched for requested algorithms (when no specific provider isrequested). The order is 1-based: 1 is the most preferred, followedby 2, and so on.
masterClassName must specify the fullyqualified name of provider's master class. The provider'sdocumentation will specify its master class. This class is always asubclass of theProvider class. The subclassconstructor sets the values of various properties that are requiredfor the Java Cryptography API to look up the algorithms or otherfacilities the provider implements.
The JDK comes standard with automatically installed andconfigured providers such as "SUN" and "SunJCE". The "SUN"provider's master class is theSUN class in thesun.security.provider package, and the correspondingjava.security file entry is as follows:
security.provider.5=sun.security.provider.Sun
To utilize another JCA provider, add a line referencing thealternate provider, specify the preference order ( makingcorresponding adjustments to the other providers' orders, ifneeded).
Suppose that the master class of CompanyX's provider iscom.companyx.provider.ProviderX, and that you wouldlike to configure this provider as the eighth most-preferred. To doso, you would add the following line to thejava.security file:
security.provider.8=com.companyx.provider.ProviderX
addProvider orinsertProviderAt method intheSecurity class. This type of registration is notpersistent across VM instances, and can only be done by "trusted"programs with the appropriate privilege. SeeSecurity.Whenever encryption providers are used (that is, those thatsupply implementations of Cipher, KeyAgreement, KeyGenerator, Mac,or SecretKeyFactory), and the provider is not an installedextensionPermissions may need tobe granted for when applets or applications using JCA are run whilea security manager is installed. There is typically a securitymanager installed whenever an applet is running, and a securitymanager may be installed for an application either via code in theapplication itself or via a command-line argument. Permissions donot need to be granted to installed extensions, since the defaultsystempolicy configuration filegrants all permissions to installed extensions (that is, installedin theextensions directory).
The documentation from the vendor of each provider you will beusing should include information as to which permissions itrequires, and how to grant such permissions. For example, thefollowing permissions may be needed by a provider if it is not aninstalled extension and a security manager is installed:
java.lang.RuntimePermission "getProtectionDomain"to get class protection domains. The provider may need to get itsown protection domain in the process of doing self-integritychecking.java.security.SecurityPermission"putProviderProperty.{name}" to set provider properties,where{name} is replaced by the actual providername.For example, a sample statement granting permissions to aprovider whose name is "MyJCE" and whose code is inmyjce_provider.jar appears below. Such a statementcould appear in a policy file. In this example, themyjce_provider.jar file is assumed to be in the/localWork directory.
grant codeBase "file:/localWork/myjce_provider.jar" { permission java.lang.RuntimePermission "getProtectionDomain"; permission java.security.SecurityPermission "putProviderProperty.MyJCE"; };Provider Class MethodsEachProvider class instance has a (currentlycase-sensitive) name, a version number, and a string description ofthe provider and its services. You can query theProvider instance for this information by calling thefollowing methods:
public String getName()public double getVersion()public String getInfo()
SecurityClassTheSecurity class manages installed providers andsecurity-wide properties. It only contains static methods and isnever instantiated. The methods for adding or removing providers,and for settingSecurity properties, can only beexecuted by a trusted program. Currently, a "trusted program" iseither
Code being executed is always considered to come from aparticular "code source". The code source includes not only thelocation (URL) where the code originated from, but also a referenceto any public key(s) corresponding to the private key(s) that mayhave been used to sign the code. Public keys in a code source arereferenced by (symbolic) alias names from the user'skeystore.
In a policy configuration file, a code source is represented bytwo components: a code base (URL), and an alias name (preceded bysignedBy), where the alias name identifies thekeystore entry containing the public key that must be used toverify the code's signature.
Each "grant" statement in such a file grants a specified codesource a set of permissions, specifying which actions areallowed.
Here is a sample policy configuration file:
grant codeBase "file:/home/sysadmin/", signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; permission java.security.SecurityPermission "putProviderProperty.*";};This configuration file specifies that code loaded from a signedJAR file from beneath the/home/sysadmin/ directory onthe local file system can add or remove providers or set providerproperties. (Note that the signature of the JAR file can beverified using the public key referenced by the alias namesysadmin in the user's keystore.)Either component of the code source (or both) may be missing.Here's an example of a configuration file where thecodeBase is omitted:
grant signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*";};If this policy is in effect, code that comes in a JAR File signedbysysadmin can add/remove providers--regardless ofwhere the JAR File originated.Here's an example without a signer:
grant codeBase "file:/home/sysadmin/" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*";};In this case, code that comes from anywhere within the/home/sysadmin/ directory on the local file system canadd/remove providers. The code does not need to be signed.An example where neithercodeBase norsignedBy is included is:
grant { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*";};Here, with both code source components missing, any code(regardless of where it originates, or whether or not it is signed,or who signed it) can add/remove providers. Obviously, this isdefinitelyNOT recommended, as this grant could open asecurity hole. Untrusted code could install a Provider, thusaffecting later code that is depending on a properly functioningimplementation. (For example, a rogueCipher objectmight capture and store the sensitive information it receives.)The following tables summarize the methods in theSecurity class you can use to query whichProviders are installed, as well as to install orremove providers at runtime.
| Method | Description |
|---|---|
static Provider[] getProviders() | Returns an array containing all the installed providers(technically, theProvider subclass for each packageprovider). The order of theProviders in the array istheir preference order. |
static Provider getProvider | Returns theProvider namedproviderName. It returnsnull if theProvider is not found. |
| Method | Description |
|---|---|
static int addProvider(Provider provider) | Adds aProvider to the end of the list ofinstalledProviders. It returns the preferenceposition in which theProvider was added, or-1 if theProvider was not added becauseit was already installed. |
static int insertProviderAt (Provider provider, intposition) | Adds a newProvider at a specified position. Ifthe given provider is installed at the requested position, theprovider formerly at that position and all providers with aposition greater thanposition are shifted up oneposition (towards the end of the list). This method returns thepreference position in which theProvider was added,or-1 if theProvider was not addedbecause it was already installed. |
| Method | Description |
|---|---|
static void removeProvider(String name) | Removes theProvider with the specified name. Itreturns silently if the provider is not installed. When thespecified provider is removed, all providers located at a positiongreater than where the specified provider was are shifted down oneposition (towards the head of the list of installedproviders). |
NOTE: If you want to change the preference position of aprovider, you must first remove it, and then insert it back in atthe new preference position.
TheSecurity class maintains a list of system-widesecurity properties. These properties are similar to theSystem properties, but are security-related. Theseproperties can be set statically or dynamically. We have alreadyseen an example of static security properties (that is, registeringa provider statically via the"security.provider.i"security property). If you want to set properties dynamically,trusted programs can use the following methods:
static String getProperty(String key)static void setProperty(String key, String datum)Note: the list of security providers is established during VMstartup, therefore the methods described above must be used toalter the provider list.
As a reminder, the configuration file is located in thefollowing location:
<java-home>/lib/security/java.security<java-home>\lib\security\java.securitySecureRandom ClassTheSecureRandom class is anengine class that provides the functionality of aRandom Number Generator (RNG). It differs from thejava.lang.Random class in that it producescryptographically strong random numbers. If there is insufficientrandomness in a generator, it makes it much easier to compromiseyour protection mechanisms. Random numbers are used throughoutcryptography, such as generating cryptographic keys, algorithmicparameters, and so on.
All Java SE implementations must indicate the strongest (mostrandom) implementation ofSecureRandom that theyprovide in thesecurerandom.strongAlgorithms propertyof thejava.security.Security class. Thisimplementation can be used when a particularly strong random valueis required.

Description of TheSecureRandom Class
SecureRandom ObjectThere are several ways to obtain an instance ofSecureRandom:
All Java SE implementations provide a defaultSecureRandom using the no-argument constructor:new SecureRandom().
To get a specific implementation ofSecureRandom,use one of thegetInstance() static factorymethods.
Use thegetInstanceStrong() method to obtain astrongSecureRandom implementation as defined by thesecurerandom.strongAlgorithms property of thejava.security.Security class. This property listsplatform implementations that are suitable for generating importantvalues.
SecureRandom ObjectTheSecureRandom implementation attempts tocompletely randomize the internal state of the generator itselfunless the caller follows the call to agetInstancemethod with a call to one of thesetSeed methods:
synchronized public void setSeed(byte[] seed)public void setSeed(long seed)
Once theSecureRandom object has been seeded, itwill produce bits as random as the original seeds.
At any time aSecureRandom object may be re-seededusing one of thesetSeed methods. The given seedsupplements, rather than replaces, the existing seed; therefore,repeated calls are guaranteed never to reduce randomness.
SecureRandom ObjectTo get random bytes, a caller simply passes an array of anylength, which is then filled with random bytes:
synchronized public void nextBytes(byte[] bytes)
If desired, it is possible to invoke thegenerateSeed method to generate a given number of seedbytes (to seed other random number generators, for example):
byte[] generateSeed(int numBytes)
MessageDigest ClassTheMessageDigest class is anengine class designed to provide the functionality ofcryptographically secure message digests such as SHA-256 or SHA-512. Acryptographically secure message digest takes arbitrary-sized input(a byte array), and generates a fixed-size output, called adigest or hash.

Description of Figure TheMessageDigest Class
For example, the SHA-256 algorithm produces a 32-byte digest, and SHA-512'sis 64 bytes.
A digest has two properties:
Message digests are used to produce unique and reliableidentifiers of data. They are sometimes called "checksums" or the"digital fingerprints" of the data. Changes to just one bit of themessage should produce a different digest value.
Message digests have many uses and can determine when data hasbeen modified, intentionally or not. Recently, there has beenconsiderable effort to determine if there are any weaknesses inpopular algorithms, with mixed results. When selecting a digestalgorithm, one should always consult a recent reference todetermine its status and appropriateness for the task at hand.
MessageDigest ObjectThe first step for computing a digest is to create a messagedigest instance.MessageDigest objects are obtained byusing one of thegetInstance() static factorymethods in theMessageDigest class. The factorymethod returns an initialized message digest object. It thus doesnot need further initialization.
The next step for calculating the digest of some data is tosupply the data to the initialized message digest object. It can beprovided all at once, or in chunks. Pieces can be fed to themessage digest by calling one of theupdatemethods:
void update(byte input)void update(byte[] input)void update(byte[] input, int offset, int len)
After the data chunks have been supplied by calls toupdate, the digest is computed using a call to one ofthedigest methods:
byte[] digest()byte[] digest(byte[] input)int digest(byte[] buf, int offset, int len)
The first method return the computed digest. The second methoddoes a finalupdate(input) with the input byte arraybefore callingdigest(), which returns the digest bytearray. The last method stores the computed digest in the providedbufferbuf, starting atoffset.len is the number of bytes inbufallotted for the digest, the method returns the number of bytesactually stored inbuf. If there is not enough room inthe buffer, the method will throw an exception.
Please see theComputing aMessageDigest example in theCode Examples section for more details.
SignatureClassTheSignature class is anengineclass designed to provide the functionality of a cryptographicdigital signature algorithm such as DSA or RSAwithMD5. Acryptographically secure signature algorithm takes arbitrary-sizedinput and a private key and generates a relatively short (oftenfixed-size) string of bytes, called thesignature, with thefollowing properties:
It can also be used to verify whether or not an allegedsignature is in fact the authentic signature of the data associatedwith it.

Description of Figure TheSignature Class
ASignature object is initialized for signing witha Private Key and is given the data to be signed. The resultingsignature bytes are typically kept with the signed data. Whenverification is needed, anotherSignature object iscreated and initialized for verification and given thecorresponding Public Key. The data and the signature bytes are fedto the signature object, and if the data and signature match, theSignature object reports success.
Even though a signature seems similar to a message digest, theyhave very different purposes in the type of protection theyprovide. In fact, algorithms such as "SHA256withRSA" use the messagedigest "SHA256" to initially "compress" the large data sets into amore manageable form, then sign the resulting 32 byte messagedigest with the "RSA" algorithm.
Please see theExamples section for anexample of signing and verifying data.
Signature Object StatesSignature objects are modal objects. This meansthat aSignature object is always in a given state,where it may only do one type of operation. States are representedas final integer constants defined in their respective classes.
The three states aSignature object may haveare:
UNINITIALIZEDSIGNVERIFYSignature object is in theUNINITIALIZED state. TheSignature classdefines two initialization methods,initSign andinitVerify, which change the state toSIGN andVERIFY, respectively.Signature ObjectThe first step for signing or verifying a signature is to createaSignature instance.Signature objectsare obtained by using one of theSignaturegetInstance() static factorymethods.
Signature ObjectASignature object must be initialized before it isused. The initialization method depends on whether the object isgoing to be used for signing or for verification.
If it is going to be used for signing, the object must first beinitialized with the private key of the entity whose signature isgoing to be generated. This initialization is done by calling themethod:
final void initSign(PrivateKey privateKey)This method puts the
Signature object in theSIGN state.If instead theSignature object is going to be usedfor verification, it must first be initialized with the public keyof the entity whose signature is going to be verified. Thisinitialization is done by calling either of these methods:
final void initVerify(PublicKey publicKey) final void initVerify(Certificate certificate)
This method puts theSignature object in theVERIFY state.
If theSignature object has been initialized forsigning (if it is in theSIGN state), the data to besigned can then be supplied to the object. This is done by makingone or more calls to one of theupdate methods:
final void update(byte b)final void update(byte[] data)final void update(byte[] data, int off, int len)
Calls to theupdate method(s) should be made untilall the data to be signed has been supplied to theSignature object.
To generate the signature, simply call one of thesign methods:
final byte[] sign()final int sign(byte[] outbuf, int offset, int len)
The first method returns the signature result in a byte array.The second stores the signature result in the provided bufferoutbuf, starting atoffset.len is the numberof bytes inoutbuf allotted for the signature. The methodreturns the number of bytes actually stored.
Signature encoding is algorithm specific. SeeJava Cryptography Architecture (JCA) Oracle Providers Documentation for JDK 8 for moreinformation about the use of ASN.1 encoding in the JavaCryptography Architecture.
A call to asign method resets the signature objectto the state it was in when previously initialized for signing viaa call toinitSign. That is, the object is reset andavailable to generate another signature with the same private key,if desired, via new calls toupdate andsign.
Alternatively, a new call can be made toinitSignspecifying a different private key, or toinitVerify(to initialize theSignature object to verify asignature).
If theSignature object has been initialized forverification (if it is in theVERIFY state), it canthen verify if an alleged signature is in fact the authenticsignature of the data associated with it. To start the process, thedata to be verified (as opposed to the signature itself) issupplied to the object. The data is passed to the object by callingone of theupdate methods:
final void update(byte b)final void update(byte[] data)final void update(byte[] data, int off, int len)
Calls to theupdate method(s) should be made untilall the data to be verified has been supplied to theSignature object. The signature can now be verified bycalling one of theverify methods:
final boolean verify(byte[] signature)final boolean verify(byte[] signature, int offset, int length)
The argument must be a byte array containing the signature. Thisbyte array would hold the signature bytes which were returned by aprevious call to one of thesign methods.
Theverify method returns abooleanindicating whether or not the encoded signature is the authenticsignature of the data supplied to theupdatemethod(s).
A call to theverify method resets the signatureobject to its state when it was initialized for verification via acall toinitVerify. That is, the object is reset andavailable to verify another signature from the identity whosepublic key was specified in the call toinitVerify.
Alternatively, a new call can be made toinitVerifyspecifying a different public key (to initialize theSignature object for verifying a signature from adifferent entity), or toinitSign (to initialize theSignature object for generating a signature).
TheCipher class provides the functionality of acryptographic cipher used for encryption and decryption. Encryptionis the process of taking data (calledcleartext) and akey, and producing data (ciphertext) meaningless to athird-party who does not know the key. Decryption is the inverseprocess: that of taking ciphertext and a key and producingcleartext.

Description of Figure The CipherClass
There are two major types of encryption:symmetric (alsoknown assecret key), andasymmetric (orpublickey cryptography). In symmetric cryptography, the same secretkey to both encrypt and decrypt the data. Keeping the key privateis critical to keeping the data confidential. On the other hand,asymmetric cryptography uses a public/private key pair to encryptdata. Data encrypted with one key is decrypted with the other. Auser first generates a public/private key pair, and then publishesthe public key in a trusted database that anyone can access. A userwho wishes to communicate securely with that user encrypts the datausing the retrieved public key. Only the holder of the private keywill be able to decrypt. Keeping the private key confidential iscritical to this scheme.
Asymmetric algorithms (such as RSA) are generally much slowerthan symmetric ones. These algorithms are not designed forefficiently protecting large amounts of data. In practice,asymmetric algorithms are used to exchange smaller secret keyswhich are used to initialize symmetric algorithms.
There are two major types of ciphers:block andstream. Block ciphers process entire blocks at a time,usually many bytes in length. If there is not enough data to make acomplete input block, the data must bepadded: that is,before encryption, dummy bytes must be added to make a multiple ofthe cipher's block size. These bytes are then stripped off duringthe decryption phase. The padding can either be done by theapplication, or by initializing a cipher to use a padding type suchas "PKCS5PADDING". In contrast, stream ciphers process incomingdata one small unit (typically a byte or even a bit) at a time.This allows for ciphers to process an arbitrary amount of datawithout padding.
When encrypting using a simple block cipher, two identicalblocks of plaintext will always produce an identical block ofcipher text. Cryptanalysts trying to break the ciphertext will havean easier job if they note blocks of repeating text. In order toadd more complexity to the text, feedback modes use the previousblock of output to alter the input blocks before applying theencryption algorithm. The first block will need an initial value,and this value is called theinitialization vector (IV).Since the IV simply alters the data before any encryption, the IVshould 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 (ElectronicCodebook Mode) is a mode in which there is no influence from block position orother ciphertext blocks. Because ECB ciphertexts are the same if they use thesame plaintext/key, this mode is not typically suitable for cryptographicapplications and should not be used.
Some algorithms such as AES and RSA allow for keys of differentlengths, but others are fixed, such as 3DES. Encryptionusing a longer key generally implies a stronger resistance tomessage recovery. As usual, there is a trade off between securityand time, so choose the key length appropriately.
Most algorithms use binary keys. Most humans do not have theability to remember long sequences of binary numbers, even whenrepresented in hexadecimal. Character passwords are much easier torecall. Because character passwords are generally chosen from asmall number of characters (for example, [a-zA-Z0-9]), protocolssuch as "Password-Based Encryption" (PBE) have been defined whichtake character passwords and generate strong binary keys. In orderto make the task of getting from password to key verytime-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 asalt, to increase the key randomness.
Newer cipher modes such as Authenticated Encryption withAssociated Data (AEAD) (for example,Galois/Counter Mode (GCM)) encrypt data and authenticate theresulting message simultaneously. Additional Associated Data (AAD)can be used during the calculation of the resulting AEAD tag (Mac),but this AAD data is not output as ciphertext. (For example, somedata might not need to be kept confidential, but should figure intothe tag calculation to detect modifications.) TheCipher.updateAAD() methods can be used to include AAD in the tagcalculations.
AES Cipher with GCM is an AEAD Cipher which has different usage patternsthan the non-AEAD ciphers. Apart from the regular data, it also takes AAD which is optional for encryption/decryptionbut AAD must be supplied before data for encryption/decryption. In addition, in order to use GCM securely,callers should not re-use key and IV combinations for encryption. This means that the cipher object should be explicitlyre-initialized with a different set of parameters every time for each encryption operation.
SecretKey myKey = ...byte[] myAAD = ...byte[] plainText = ... int myTLen = ... byte[] myIv = ...GCMParameterSpec myParams = new GCMParameterSpec(myTLen, myIv);Cipher c = Cipher.getInstance("AES/GCM/NoPadding");c.init(Cipher.ENCRYPT_MODE, myKey, myParams);// AAD is optional, if present, it must be supplied before any update/doFinal calls.c.updateAAD(myAAD); // if AAD is non-nullbyte[] cipherText = new byte[c.getOutputSize(plainText.length)];c.doFinal(plainText, 0, plainText.length, cipherText); // conclusion of encryption operation// To decrypt, same AAD and GCM parameters must be suppliedc.init(Cipher.DECRYPT_MODE, myKey, myParams);c.updateAAD(myAAD);byte[] recoveredText = c.doFinal(cipherText);// MUST CHANGE IV VALUE if the same key were to be used again for encryption byte[] newIv = ...;myParams = new GCMParameterSpec(myTLen, newIv);Cipher objects are obtained by using one of theCiphergetInstance() static factorymethods. Here, the algorithm name is slightly different thanwith other engine classes, in that it specifies not just analgorithm name, but a "transformation".A transformation is a string that describes theoperation (or set of operations) to be performed on the given inputto produce some output. A transformation always includes the nameof a cryptographic algorithm (e.g.,AES), and may befollowed by a mode and padding scheme.
A transformation is of the form:
For example, the following are valid transformations:
"AES/CBC/PKCS5Padding" "AES"
If just a transformation name is specified, the system willdetermine if there is an implementation of the requestedtransformation available in the environment, and if there is morethan one, returns there is a preferred one.
If both a transformation name and a package provider arespecified, the system will determine if there is an implementationof the requested transformation in the package requested, and throwan exception if there is not.
It is recommended to use a transformation that fully specifies the algorithm, mode, and padding. By not doing so, the provider will use a default. For example, the SunJCE and SunPKCS11 providers use ECB as the default mode, and PKCS5Padding as the default padding for many symmetric ciphers.
This means that in the case of theSunJCE provider:
Cipher c1 = Cipher.getInstance("AES/ECB/PKCS5Padding");and Cipher c1 = Cipher.getInstance("AES");are equivalent statements.
Note: ECB mode is the easiest block cipher mode to use and is the default in the JDK/JRE. ECB works well for single blocks of data, but absolutely should not be used for multiple data blocks.
Using modes such as CFB and OFB, block ciphers can encrypt datain units smaller than the cipher's actual block size. Whenrequesting such a mode, you may optionally specify the number ofbits to be processed at a time by appending this number to the modename as shown in the "AES/CFB8/NoPadding" and"AES/OFB32/PKCS5Padding" transformations. If no such numberis specified, a provider-specific default is used. (For example,theSunJCE provider uses a default of 128 bits forAES.) Thus, block ciphers can be turned into byte-oriented streamciphers by using an 8 bit mode such as CFB8 or OFB8.
Appendix A of this document contains a listof 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, andmust be initialized before they become usable.
A Cipher object obtained viagetInstance must beinitialized for one of four modes, which are defined as finalinteger constants in theCipher class. The modes canbe referenced by their symbolic names, which are shown below alongwith a description of the purpose of each mode:
java.security.Key into bytes so thatthe key can be securely transported.java.security.Key object.Each of the Cipher initialization methods takes an operationalmode parameter (opmode), and initializes the Cipherobject 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 followinginit methods:
public void init(int opmode, Key key); public void init(int opmode, Certificate certificate); public void init(int opmode, Key key, SecureRandom random); public void init(int opmode, Certificate certificate, SecureRandom random); public void init(int opmode, Key key, AlgorithmParameterSpec params); public void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random); public void init(int opmode, Key key, AlgorithmParameters params); public void init(int opmode, Key key, AlgorithmParameters params, SecureRandom random);
If a Cipher object that requires parameters (e.g., aninitialization vector) is initialized for encryption, and noparameters are supplied to theinit method, theunderlying cipher implementation is supposed to supply the requiredparameters itself, either by generating random parameters or byusing a default, provider-specific set of parameters.
However, if a Cipher object that requires parameters isinitialized for decryption, and no parameters are supplied to theinit method, anInvalidKeyException orInvalidAlgorithmParameterException exception will beraised, depending on theinit method that has beenused.
See the section aboutManagingAlgorithm Parameters for more details.
The same parameters that were used for encryption must be usedfor decryption.
Note that when a Cipher object is initialized, it loses allpreviously-acquired state. In other words, initializing a Cipher isequivalent to creating a new instance of that Cipher, andinitializing it. For example, if a Cipher is first initialized fordecryption with a given key, and then initialized for encryption,it will lose any state acquired while in decryption mode.
Data can be encrypted or decrypted in one step (single-partoperation) or in multiple steps (multiple-partoperation). A multiple-part operation is useful if you do notknow in advance how long the data is going to be, or if the data istoo long to be stored in memory all at once.
To encrypt or decrypt data in a single step, call one of thedoFinal methods:
public byte[] doFinal(byte[] input); public byte[] doFinal(byte[] input, int inputOffset, int inputLen); public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output); public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
To encrypt or decrypt data in multiple steps, call one of theupdate methods:
public byte[] update(byte[] input); public byte[] update(byte[] input, int inputOffset, int inputLen); public int update(byte[] input, int inputOffset, int inputLen, byte[] output); public int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
A multiple-part operation must be terminated by one of the abovedoFinal methods (if there is still some input dataleft for the last step), or by one of the followingdoFinal methods (if there is no input data left forthe last step):
public byte[] doFinal(); public int doFinal(byte[] output, int outputOffset);
All thedoFinal methods take care of any necessarypadding (or unpadding), if padding (or unpadding) has beenrequested as part of the specified transformation.
A call todoFinal resets the Cipher object to thestate it was in when initialized via a call toinit.That is, the Cipher object is reset and available to encrypt ordecrypt (depending on the operation mode that was specified in thecall toinit) more data.
Wrapping a key enables secure transfer of the key from one placeto another.
Thewrap/unwrap API makes it more convenient towrite code since it works with key objects directly. These methodsalso enable the possibility of secure transfer of hardware-basedkeys.
Towrap a Key, first initialize the Cipher object forWRAP_MODE, and then call the following:
public final byte[] wrap(Key key);
If you are supplying the wrapped key bytes (the result ofcallingwrap) to someone else who will unwrap them, besure to also send additional information the recipient will need inorder to do theunwrap:
Cipher.SECRET_KEY,Cipher.PRIVATE_KEY, orCipher.PUBLIC_KEY).The key algorithm name can be determined by calling thegetAlgorithm method from the Key interface:
public String getAlgorithm();
Tounwrap the bytes returned by a previous call towrap, first initialize a Cipher object forUNWRAP_MODE, then call the following:
public final Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType));
Here,wrappedKey is the bytes returned from theprevious call to wrap,wrappedKeyAlgorithm is thealgorithm associated with the wrapped key, andwrappedKeyType is the type of the wrapped key. Thismust be one ofCipher.SECRET_KEY,Cipher.PRIVATE_KEY, orCipher.PUBLIC_KEY.
The parameters being used by the underlying Cipherimplementation, which were either explicitly passed to theinit method by the application or generated by theunderlying implementation itself, can be retrieved from the Cipherobject by calling itsgetParameters method, whichreturns the parameters as ajava.security.AlgorithmParameters object (ornull if no parameters are being used). If theparameter is an initialization vector (IV), it can also beretrieved by calling thegetIV method.
In the following example, a Cipher object implementingpassword-based encryption (PBE) is initialized with just a key andno parameters. However, the selected algorithm for password-basedencryption requires two parameters - asalt and aniteration count. Those will be generated by the underlyingalgorithm implementation itself. The application can retrieve thegenerated 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("PBEWithHmacSHA256AndAES_256"); // initialize cipher for encryption, without supplying // any parameters. Here, "myKey" is assumed to refer // to an already-generated key. c.init(Cipher.ENCRYPT_MODE, myKey); // encrypt some data and store away ciphertext // for later decryption byte[] cipherText = c.doFinal("This is just an example".getBytes()); // retrieve parameters generated by underlying cipher // implementation AlgorithmParameters algParams = c.getParameters(); // get parameter encoding and store it away byte[] encodedAlgParams = algParams.getEncoded();The same parameters that were used for encryption must be usedfor decryption. They can be instantiated from their encoding andused to initialize the corresponding Cipher object for decryption,as follows:
import javax.crypto.*; import java.security.AlgorithmParameters; // get parameter object for password-based encryption AlgorithmParameters algParams; algParams = AlgorithmParameters.getInstance("PBEWithHmacSHA256AndAES_256"); // initialize with parameter encoding from above algParams.init(encodedAlgParams); // get cipher object for password-based encryption Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_256"); // initialize cipher for decryption, using one of the // init() methods that takes an AlgorithmParameters // object, and pass it the algParams object from above c.init(Cipher.DECRYPT_MODE, myKey, algParams);If you did not specify any parameters when you initialized aCipher object, and you are not sure whether or not the underlyingimplementation uses any parameters, you can find out by simplycalling thegetParameters method of your Cipher objectand checking the value returned. A return value ofnull indicates that no parameters were used.
The following cipher algorithms implemented by theSunJCE provider use parameters:
javax.crypto.spec.IvParameterSpec class can be used toinitialize a Cipher object with a given IV.javax.crypto.spec.PBEParameterSpec class can be usedto initialize a Cipher object implementing a PBE algorithm (for example: PBEWithHmacSHA256AndAES_256) with agiven salt and iteration count.Note that you do not have to worry about storing or transferringany algorithm parameters for use by the decryption operation if youuse theSealedObjectclass. This class attaches the parameters used for sealing(encryption) to the encrypted object contents, and uses the sameparameters for unsealing (decryption).
Some of theupdate anddoFinal methodsof Cipher allow the caller to specify the output buffer into whichto encrypt or decrypt the data. In these cases, it is important topass a buffer that is large enough to hold the result of theencryption or decryption operation.
The following method in Cipher can be used to determine how bigthe output buffer should be:
public int getOutputSize(int inputLen)
Cipher-based ClassesThere are some helper classes which internally useCiphers to provide easy access to common cipheruses.
This class is aFilterInputStream that encrypts ordecrypts the data passing through it. It is composed of anInputStream, or one of its subclasses, and aCipher. CipherInputStream represents a secure inputstream into which a Cipher object has been interposed. Theread methods of CipherInputStream return data that areread from the underlying InputStream but have additionally beenprocessed by the embedded Cipher object. The Cipher object must befully initialized before being used by a CipherInputStream.
For example, if the embedded Cipher has been initialized fordecryption, the CipherInputStream will attempt to decrypt the datait reads from the underlying InputStream before returning them tothe application.
This class adheres strictly to the semantics, especially thefailure semantics, of its ancestor classesjava.io.FilterInputStream andjava.io.InputStream. This class has exactly thosemethods 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 byits 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 usemethods that are not defined or overridden in this class (such as anew method or constructor that is later added to one of the superclasses), because the design and implementation of those methodsare unlikely to have considered security impact with regard toCipherInputStream.
As an example of its usage, supposecipher1 hasbeen initialized for encryption. The code below demonstrates how touse a CipherInputStream containing that cipher and aFileInputStream 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.txt and then stores the result (the encryptedbytes) in/tmp/b.txt.
The following example demonstrates how to easily connect severalinstances of CipherInputStream and FileInputStream. In thisexample, assume thatcipher1 andcipher2have been initialized for encryption and decryption (withcorresponding 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.txt to/tmp/b.txt, except that thecontent is first encrypted and then decrypted back when it is readfrom/tmp/a.txt. Of course since this program simplyencrypts text and decrypts it back right away, it's actually notvery useful except as a simple way of illustrating chaining ofCipherInputStreams.
Note that the read methods of theCipherInputStreamwill block until data is returned from the underlying cipher. If ablock cipher is used, a full block of cipher text will have to beobtained from the underlying InputStream.
This class is aFilterOutputStream that encrypts ordecrypts the data passing through it. It is composed of anOutputStream, or one of its subclasses, and aCipher. CipherOutputStream represents a secure outputstream into which a Cipher object has been interposed. Thewrite methods of CipherOutputStream first process thedata with the embedded Cipher object before writing them out to theunderlying OutputStream. The Cipher object must be fullyinitialized before being used by a CipherOutputStream.
For example, if the embedded Cipher has been initialized forencryption, the CipherOutputStream will encrypt its data, beforewriting them out to the underlying output stream.
This class adheres strictly to the semantics, especially thefailure semantics, of its ancestor classesjava.io.OutputStream andjava.io.FilterOutputStream. This class has exactlythose methods specified in its ancestor classes, and overrides themall, so that all data are additionally processed by the embeddedcipher. Moreover, this class catches all exceptions that are notthrown by its ancestor classes.
It is crucial for a programmer using this class not to usemethods that are not defined or overridden in this class (such as anew method or constructor that is later added to one of the superclasses), because the design and implementation of those methodsare unlikely to have considered security impact with regard toCipherOutputStream.
As an example of its usage, supposecipher1 hasbeen initialized for encryption. The code below demonstrates how touse a CipherOutputStream containing that cipher and aFileOutputStream in order to encrypt data to be written to anoutput 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 (theencrypted bytes) in/tmp/b.txt.
The following example demonstrates how to easily connect severalinstances of CipherOutputStream and FileOutputStream. In thisexample, assume thatcipher1 andcipher2have been initialized for decryption and encryption (withcorresponding 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.txt to/tmp/b.txt, except that thecontent is first encrypted and then decrypted back before it iswritten to/tmp/b.txt.
One thing to keep in mind when usingblock cipheralgorithms is that a full block of plaintext data must be given totheCipherOutputStream before the data will beencrypted and sent to the underlying output stream.
There is one other important difference between theflush andclose methods of this class,which becomes even more relevant if the encapsulated Cipher objectimplements a block cipher algorithm with padding turned on:
flush flushes the underlying OutputStream byforcing any buffered output bytes that have already been processedby the encapsulated Cipher object to be written out. Any bytesbuffered by the encapsulated Cipher object and waiting to beprocessed by it willnot be written out.close closes the underlying OutputStream andreleases any system resources associated with it. It invokes thedoFinal method of the encapsulated Cipher object,causing any bytes buffered by it to be processed and written out tothe underlying stream by calling itsflushmethod.This class enables a programmer to create an object and protectits confidentiality with a cryptographic algorithm.
Given any object that implements thejava.io.Serializable interface, one can create aSealedObject that encapsulates the original object, inserialized format (i.e., a "deep copy"), and seals (encrypts) itsserialized contents, using a cryptographic algorithm such as AES,to protect its confidentiality. The encrypted content can later bedecrypted (with the corresponding algorithm using the correctdecryption key) and deserialized, yielding the originalobject.
A typical usage is illustrated in the following code segment: Inorder to seal an object, you create aSealedObjectfrom the object to be sealed and a fully initializedCipher object that will encrypt the serialized objectcontents. In this example, the String "This is a secret" is sealedusing the AES algorithm. Note that any algorithm parameters thatmay be used in the sealing operation are stored inside ofSealedObject:
// create Cipher object // NOTE: sKey is assumed to refer to an already-generated // secret AES key. Cipher c = Cipher.getInstance("AES"); 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 twodifferent ways:
Cipher object that has been initializedwith the exact same algorithm, key, padding scheme, etc., that wereused 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 thesealed object does not require knowledge of the decryption key. Forexample, after one party has initialized the cipher object with therequired decryption key, it could hand over the cipher object toanother party who then unseals the sealed object.
try { String s = (String)so.getObject(sKey); } catch (Exception e) { // do something };In this approach, thegetObject method creates acipher object for the appropriate decryption algorithm andinitializes it with the given decryption key and the algorithmparameters (if any) that were stored in the sealed object. Thisapproach has the advantage that the party who unseals the objectdoes not need to keep track of the parameters (e.g., the IV) thatwere used to seal the object.
Similar to aMessageDigest, a MessageAuthentication Code (MAC) provides a way to check the integrity ofinformation transmitted over or stored in an unreliable medium, butincludes a secret key in the calculation. Only someone with theproper key will be able to verify the received message. Typically,message authentication codes are used between two parties thatshare a secret key in order to validate information transmittedbetween these parties.

Description of Figure 8: The MacClass
A MAC mechanism that is based on cryptographic hash functions isreferred to as HMAC. HMAC can be used with any cryptographic hashfunction, e.g., SHA-256, in combination with a secret sharedkey.
TheMac class provides the functionality of aMessage Authentication Code (MAC). Please refer to thecode example.
Mac ObjectMac objects are obtained by using one of theMacgetInstance() static factorymethods.
A Mac object is always initialized with a (secret) key and mayoptionally be initialized with a set of parameters, depending onthe underlying MAC algorithm.
To initialize a Mac object, call one of itsinitmethods:
public void init(Key key); public void init(Key key, AlgorithmParameterSpec params);
You can initialize your Mac object with any (secret-)key objectthat implements thejavax.crypto.SecretKey interface.This could be an object returned byjavax.crypto.KeyGenerator.generateKey(), or one thatis the result of a key agreement protocol, as returned byjavax.crypto.KeyAgreement.generateSecret(), or aninstance ofjavax.crypto.spec.SecretKeySpec.
With some MAC algorithms, the (secret-)key algorithm associatedwith the (secret-)key object used to initialize the Mac object doesnot matter (this is the case with the HMAC-MD5 and HMAC-SHA1implementations of theSunJCE provider). With others,however, the (secret-)key algorithm does matter, and anInvalidKeyException is thrown if a (secret-)key objectwith an inappropriate (secret-)key algorithm is used.
A MAC can be computed in one step (single-part operation)or in multiple steps (multiple-part operation). Amultiple-part operation is useful if you do not know in advance howlong the data is going to be, or if the data is too long to bestored in memory all at once.
To compute the MAC of some data in a single step, call thefollowingdoFinal method:
public byte[] doFinal(byte[] input);
To compute the MAC of some data in multiple steps, call one oftheupdate methods:
public void update(byte input); public void update(byte[] input); public void update(byte[] input, int inputOffset, int inputLen);
A multiple-part operation must be terminated by the abovedoFinal method (if there is still some input data leftfor 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);
Key InterfacesTo this point, we have focused the high-level uses of the JCAwithout getting lost in the details of what keys are and how theyare generated/represented. It is now time to turn our attention tokeys.
Thejava.security.Key interface is the top-levelinterface for all opaque keys. It defines the functionality sharedby all opaque key objects.
Anopaque key representation is one in which you have nodirect access to the key material that constitutes a key. In otherwords: "opaque" gives you limited access to the key--just the threemethods defined by theKey interface (see below):getAlgorithm,getFormat, andgetEncoded.
This is in contrast to atransparent representation, inwhich you can access each key material value individually, throughone of theget methods defined in the correspondingspecification class.
All opaque keys have three characteristics:
AES,DSA orRSA), which willwork with those algorithms and with related algorithms (such asSHA256withRSA) The nameof the algorithm of a key is obtained using this method:String getAlgorithm()
byte[] getEncoded()
String getFormat()
KeyGenerator andKeyPairGenerator,certificates,key specifications (using aKeyFactory), or aKeyStore implementation accessing akeystore database used to manage keys. It is possible to parseencoded keys, in an algorithm-dependent manner, using aKeyFactory.It is also possible to parse certificates, using aCertificateFactory.
Here is a list of interfaces which extend theKeyinterface in thejava.security.interfaces andjavax.crypto.interfaces packages:
PublicKey andPrivateKeyInterfacesThePublicKey andPrivateKeyinterfaces (which both extend theKey interface) aremethodless interfaces, used for type-safety andtype-identification.
KeyPairClassTheKeyPair class is a simple holder for a key pair(a public key and a private key). It has two public methods, onefor returning the private key, and the other for returning thepublic key:
PrivateKey getPrivate()PublicKey getPublic()
Key objects and key specifications(KeySpecs) are two different representations of keydata.Ciphers useKey objects toinitialize their encryption algorithms, but keys may need to beconverted into a more portable format for transmission orstorage.
Atransparent representation of keys means that you canaccess each key material value individually, through one of theget methods defined in the corresponding specificationclass. For example,DSAPrivateKeySpec definesgetX,getP,getQ, andgetG methods, to access the private keyx, and the DSA algorithm parameters used to calculatethe key: the primep, the sub-primeq,and the baseg. If the key is stored on a hardwaredevice, its specification may contain information that helpsidentify the key on the device.
This representation is contrasted with anopaquerepresentation, as defined by theKey interface, in which you have no directaccess to the key material fields. In other words, an "opaque"representation gives you limited access to the key--just the threemethods defined by theKey interface:getAlgorithm,getFormat, andgetEncoded.
A key may be specified in an algorithm-specific way, or in analgorithm-independent encoding format (such as ASN.1). For example,a DSA private key may be specified by its componentsx,p,q, andg(seeDSAPrivateKeySpec),or it may be specified using its DER encoding (seePKCS8EncodedKeySpec).
TheKeyFactory andSecretKeyFactoryclasses can be used to convert between opaque and transparent keyrepresentations (that is, betweenKeys andKeySpecs, assuming that the operation is possible.(For example, private keys on smart cards might not be able leavethe card. SuchKeys are not convertible.)
In the following sections, we discuss the key specificationinterfaces and classes in thejava.security.specpackage.
KeySpecInterfaceThis interface contains no methods or constants. Its onlypurpose is to group and provide type safety for all keyspecifications. All key specifications must implement thisinterface.
KeySpecSubinterfacesLike theKey interface, there are a similar set ofKeySpec interfaces.
EncodedKeySpec ClassThis abstract class (which implements theKeySpec interface) represents a publicor private key in encoded format. ItsgetEncodedmethod returns the encoded key:
abstract byte[] getEncoded();and its
getFormat method returns the name of theencoding format:abstract String getFormat();
See the next sections for the concrete implementationsPKCS8EncodedKeySpec andX509EncodedKeySpec.
PKCS8EncodedKeySpec ClassThis class, which is a subclass ofEncodedKeySpec,represents the DER encoding of a private key, according to theformat specified in the PKCS8 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the PKCS8standard. ItsgetFormat method returns the string"PKCS#8".
X509EncodedKeySpec ClassThis class, which is a subclass ofEncodedKeySpec,represents the DER encoding of a public key, according to theformat specified in the X.509 standard. ItsgetEncodedmethod returns the key bytes, encoded according to the X.509standard. ItsgetFormat method returns the string"X.509".
Newcomers to Java and the JCA APIs in particular sometimes donot grasp the distinction between generators and factories.

Description of FigureDifferences Between Generators and Factories
Generators are used togenerate brand new objects.Generators can be initialized in either an algorithm-dependent oralgorithm-independent way. For example, to create a Diffie-Hellman(DH) keypair, an application could specify the necessary P and Gvalues, or the generator could simply be initialized with theappropriate key length, and the generator will select appropriate Pand G values. In both cases, the generator will produce brand newkeys based on the parameters.
On the other hand, factories are used toconvert data fromone existing object type to another. For example, anapplication might have available the components of a DH private keyand can package them as aKeySpec, but needs to convert them intoaPrivateKey object that can beused by aKeyAgreement object, or vice-versa. Or theymight have the byte array of a certificate, but need to use aCertificateFactory to convert it into aX509Certificate object. Applications use factoryobjects to do the conversion.
KeyFactory ClassTheKeyFactory class is anengineclass designed to perform conversions between opaquecryptographicKeys andkey specifications (transparent representations ofthe underlying key material).

Description of Figure TheKeyFactory Class
Key factories are bidirectional. They allow you to build anopaque key object from a given key specification (key material), orto retrieve the underlying key material of a key object in asuitable format.
Multiple compatible key specifications can exist for the samekey. For example, a DSA public key may be specified by itscomponentsy,p,q, andg (seejava.security.spec.DSAPublicKeySpec), or it may bespecified using its DER encoding according to the X.509 standard(seeX509EncodedKeySpec).
A key factory can be used to translate between compatible keyspecifications. Key parsing can be achieved through translationbetween compatible key specifications, e.g., when you translatefromX509EncodedKeySpec toDSAPublicKeySpec, you basically parse the encoded keyinto its components. For an example, see the end of theGenerating/Verifying Signatures Using KeySpecifications andKeyFactory section.
KeyFactory ObjectKeyFactory objects are obtained by using one of theKeyFactorygetInstance() static factorymethods.
If you have a key specification for a public key, you can obtainan opaquePublicKey object from the specification byusing thegeneratePublic method:
PublicKey generatePublic(KeySpec keySpec)
Similarly, if you have a key specification for a private key,you can obtain an opaquePrivateKey object from thespecification by using thegeneratePrivate method:
PrivateKey generatePrivate(KeySpec keySpec)
If you have aKey object, you can get acorresponding key specification object by calling thegetKeySpec method:
KeySpec getKeySpec(Key key, Class keySpec)
keySpec identifies the specification class in whichthe key material should be returned. It could, for example, beDSAPublicKeySpec.class, to indicate that the keymaterial should be returned in an instance of theDSAPublicKeySpec class.Please see theExamples section formore details.
This class represents a factory for secret keys. UnlikeKeyFactory, ajavax.crypto.SecretKeyFactory object operates only onsecret (symmetric) keys, whereas ajava.security.KeyFactory object processes the publicand private key components of a key pair.

Description of TheSecretKeyFactory Class
Key factories are used to convertKeys (opaque cryptographic keys of typejava.security.Key) intokeyspecifications (transparent representations of the underlyingkey material in a suitable format), and vice versa.
Objects of typejava.security.Key, of whichjava.security.PublicKey,java.security.PrivateKey, andjavax.crypto.SecretKey are subclasses, are opaque keyobjects, because you cannot tell how they are implemented. Theunderlying implementation is provider-dependent, and may besoftware or hardware based. Key factories allow providers to supplytheir own implementations of cryptographic keys.
For example, if you have a key specification for a DiffieHellman public key, consisting of the public valuey,the prime modulusp, and the baseg, andyou feed the same specification to Diffie-Hellman key factoriesfrom different providers, the resultingPublicKeyobjects will most likely have different underlyingimplementations.
A provider should document the key specifications supported byits secret key factory. For example, theSecretKeyFactory for DES keys supplied by theSunJCE provider supportsDESKeySpec as atransparent representation of DES keys, theSecretKeyFactory for DES-EDE keys supportsDESedeKeySpec as a transparent representation ofDES-EDE keys, and theSecretKeyFactory for PBEsupportsPBEKeySpec as a transparent representation ofthe underlying password.
The following is an example of how to use aSecretKeyFactory to convert secret key data into aSecretKey object, which can be used for a subsequentCipher operation:
// Note the following bytes are not realistic secret key data // bytes but are simply supplied as an illustration of using data // bytes (key material) you already have to build a DESedeKeySpec. byte[] desEdeKeyData = getKeyData(); DESedeKeySpec desEdeKeySpec = new DESedeKeySpec(desEdeKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey secretKey = keyFactory.generateSecret(desEdeKeySpec);In this case, the underlying implementation ofSecretKey is based on the provider ofKeyFactory.
An alternative, provider-independent way of creating afunctionally equivalentSecretKey object from the samekey material is to use thejavax.crypto.spec.SecretKeySpec class, whichimplements thejavax.crypto.SecretKey interface:
byte[] aesKeyData = getKeyData(); SecretKeySpec secretKey = new SecretKeySpec(aesKeyData, "AES");
SecretKeyFactory ObjectSecretKeyFactory objects are obtained by using oneof theSecretKeyFactorygetInstance() static factorymethods.
If you have a key specification for a secret key, you can obtainan opaqueSecretKey object from the specification byusing thegenerateSecret method:
SecretKey generateSecret(KeySpec keySpec)
If you have aSecret Key object, you can get acorresponding key specification object by calling thegetKeySpec method:
KeySpec getKeySpec(Key key, Class keySpec)
keySpec identifies the specification class in whichthe key material should be returned. It could, for example, beDESKeySpec.class, to indicate that the key materialshould be returned in an instance of theDESKeySpecclass.KeyPairGenerator ClassTheKeyPairGenerator class is anengine class used to generate pairs of public andprivate keys.

Description of TheKeyPairGenerator Class
There are two ways to generate a key pair: in analgorithm-independent manner, and in an algorithm-specific manner.The only difference between the two is the initialization of theobject.
Please see theExamples section forexamples of calls to the methods documented below.
KeyPairGeneratorAll key pair generation starts with aKeyPairGenerator.KeyPairGeneratorobjects are obtained by using one of theKeyPairGeneratorgetInstance() static factorymethods.
KeyPairGeneratorA key pair generator for a particular algorithm creates apublic/private key pair that can be used with this algorithm. Italso associates algorithm-specific parameters with each of thegenerated keys.
A key pair generator needs to be initialized before it cangenerate keys. In most cases, algorithm-independent initializationis sufficient. But in other cases, algorithm-specificinitialization can be used.
All key pair generators share the concepts of a keysize and asource of randomness. The keysize is interpreted differently fordifferent algorithms. For example, in the case of the DSAalgorithm, the keysize corresponds to the length of the modulus.(SeeJava Cryptography Architecture (JCA) Oracle Providers Documentation for JDK 8 for information about the keysizes for specificalgorithms.)
Aninitialize method takes two universally sharedtypes of arguments:
void initialize(int keysize, SecureRandom random)Another
initialize method takes only akeysize argument; it uses a system-provided source ofrandomness:void initialize(int keysize)
Since no other parameters are specified when you call the abovealgorithm-independentinitialize methods, it is up tothe provider what to do about the algorithm-specific parameters (ifany) 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 theSUN provideruses a set of precomputed values for thep,q, andg parameters. If the modulus sizeis not one of the above values, theSUN providercreates a new set of parameters. Other providers might haveprecomputed parameter sets for more than just the three modulussizes mentioned above. Still others might not have a list ofprecomputed parameters at all and instead always create newparameter sets.
For situations where a set of algorithm-specific parametersalready exists (such as "community parameters" in DSA), there aretwoinitialize methods that have anAlgorithmParameterSpecargument. One also has aSecureRandom argument, whilethe source of randomness is system-provided for the other:
void initialize(AlgorithmParameterSpec params, SecureRandom random)void initialize(AlgorithmParameterSpec params)See theExamples section for more details.
The procedure for generating a key pair is always the same,regardless of initialization (and of the algorithm). You alwayscall the following method fromKeyPairGenerator:
KeyPair generateKeyPair()Multiple calls to
generateKeyPair will yield differentkey pairs.A key generator is used to generate secret keys for symmetricalgorithms.

Description of Figure TheKeyGenerator Class
KeyGeneratorKeyGenerator objects are obtained by using one of theKeyGeneratorgetInstance() static factorymethods.A key generator for a particular symmetric-key algorithm createsa symmetric key that can be used with that algorithm. It alsoassociates algorithm-specific parameters (if any) with thegenerated key.
There are two ways to generate a key: in analgorithm-independent manner, and in an algorithm-specific manner.The only difference between the two is the initialization of theobject:
All key generators share the concepts of akeysize and asource of randomness. There is aninit methodthat takes these two universally shared types of arguments. Thereis also one that takes just akeysize argument, anduses a system-provided source of randomness, and one that takesjust a source of randomness:
public void init(SecureRandom random); public void init(int keysize); public void init(int keysize, SecureRandom random);
Since no other parameters are specified when you call the abovealgorithm-independentinit methods, it is up to theprovider what to do about the algorithm-specific parameters (ifany) to be associated with the generated key.
For situations where a set of algorithm-specific parametersalready exists, there are twoinit methods that haveanAlgorithmParameterSpec argument. One also has aSecureRandom argument, while the source of randomnessis system-provided for the other:
public void init(AlgorithmParameterSpec params); public void init(AlgorithmParameterSpec params, SecureRandom random);
In case the client does not explicitly initialize theKeyGenerator (via a call to aninit method), eachprovider must supply (and document) a default initialization.
The following method generates a secret key:
public SecretKey generateKey();
Key agreement is a protocol by which 2 or more parties canestablish the same cryptographic keys, without having to exchangeany secret information.

Description of Figure TheKeyAgreement Class
Each party initializes their key agreement object with theirprivate key, and then enters the public keys for each party thatwill participate in the communication. In most cases, there arejust two parties, but algorithms such as Diffie-Hellman allow formultiple parties (3 or more) to participate. When all the publickeys have been entered, eachKeyAgreement object willgenerate (agree upon) the same key.
The KeyAgreement class provides the functionality of a keyagreement protocol. The keys involved in establishing a sharedsecret are created by one of the key generators(KeyPairGenerator orKeyGenerator), aKeyFactory, or as a result from an intermediate phaseof the key agreement protocol.
Each party involved in the key agreement has to create aKeyAgreement object.KeyAgreement objects are obtainedby using one of theKeyAgreementgetInstance() static factorymethods.
You initialize a KeyAgreement object with your privateinformation. In the case of Diffie-Hellman, you initialize it withyour Diffie-Hellman private key. Additional initializationinformation may contain a source of randomness and/or a set ofalgorithm parameters. Note that if the requested key agreementalgorithm requires the specification of algorithm parameters, andonly a key, but no parameters are provided to initialize theKeyAgreement object, the key must contain the required algorithmparameters. (For example, the Diffie-Hellman algorithm uses a primemodulusp and a base generatorg as itsparameters.)
To initialize a KeyAgreement object, call one of itsinit methods:
public void init(Key key); public void init(Key key, SecureRandom random); public void init(Key key, AlgorithmParameterSpec params); public void init(Key key, AlgorithmParameterSpec params, SecureRandom random);
Every key agreement protocol consists of a number of phases thatneed to be executed by each party involved in the keyagreement.
To execute the next phase in the key agreement, call thedoPhase method:
public Key doPhase(Key key, boolean lastPhase);
Thekey parameter contains the key to be processedby that phase. In most cases, this is the public key of one of theother parties involved in the key agreement, or an intermediate keythat was generated by a previous phase.doPhase mayreturn an intermediate key that you may have to send to the otherparties of this key agreement, so they can process it in asubsequent phase.
ThelastPhase parameter specifies whether or notthe phase to be executed is the last one in the key agreement: Avalue ofFALSE indicates that this is not the lastphase of the key agreement (there are more phases to follow), and avalue ofTRUE indicates that this is the last phase ofthe key agreement and the key agreement is completed, i.e.,generateSecret can be called next.
In the example ofDiffie-Hellman between twoparties , you calldoPhase once, withlastPhase set toTRUE. In the example ofDiffie-Hellman between three parties, you calldoPhasetwice: the first time withlastPhase set toFALSE, the 2nd time withlastPhase set toTRUE.
After each party has executed all the required key agreementphases, it can compute the shared secret by calling one of thegenerateSecret methods:
public byte[] generateSecret(); public int generateSecret(byte[] sharedSecret, int offset); public SecretKey generateSecret(String algorithm);
A database called a "keystore" can be used to manage arepository of keys and certificates. (Acertificate is adigitally signed statement from one entity, saying that the publickey of some other entity has a particular value.)
The user keystore is by default stored in a file named.keystore in the user's home directory, as determinedby the "user.home" system property. On Solaris systems"user.home" defaults to the user's home directory. OnWin32 systems, given user nameuName, "user.home"defaults to:
Of course, keystore files can be located as desired. In someenvironments, it may make sense for multiple keystores to exist.For example, inJSSE(SSL/TLS), one keystore might hold a user's private keys, andanother might hold certificates used to establish trustrelationships.
In addition to the user's keystore, the JDK also maintains asystem-wide keystore which is used to store trusted certificatesfrom a variety of Certificate Authorities (CA's). These CAcertificates can be used to help make trust decisions. For example,in SSL/TLS when theSunJSSE provider is presented withcertificates from a remote peer, the default trustmanager willconsult the:
<java-home>/lib/ext/cacerts<java-home>\lib\ext\cacertsfile to determine if the connection is to be trusted. Instead ofusing the system-widecacerts keystore, applicationscan set up and use their own keystores, or even use the userkeystore described above.
TheKeyStore class supplieswell-defined interfaces to access and modify the information in akeystore. It is possible for there to be multiple differentconcrete implementations, where each implementation is that for aparticulartype of keystore.
Currently, there are two command-line tools that make use ofKeyStore:keytool andjarsigner, and also a GUI-based tool namedpolicytool. It is also used by thePolicy reference implementation when it processespolicy files specifying the permissions (allowed accesses to systemresources) to be granted to code from various sources. SinceKeyStore is publicly available, JDK users can writeadditional security applications that use it.
Applications can choose differenttypes of keystoreimplementations from different providers, using thegetInstance factory method in theKeyStore class. A keystore type defines the storageand data format of the keystore information, and the algorithmsused to protect private keys in the keystore and the integrity ofthe keystore itself. Keystore implementations of different typesare not compatible.
The recommended keystore implementation is "pkcs12". This is a cross-platformkeystore based on the RSA PKCS12 Personal Information Exchange Syntax Standard.This standard is primarily meant for storing or transporting a user's privatekeys, certificates, and miscellaneous secrets. Arbitrary attributes can beassociated with individual entries in a PKCS12 keystore.
The default keystore implementation type is "jks", which is specified in thefollowing line in thejava.security file:
keystore.type=jks
To have tools and other applications use a different defaultkeystore implementation, you can change that line to specify anotherdefault type. For example, to use "pkcs12" as the default keystoreimplementation, change the line to:
keystore.type=pkcs12
Some applications, such askeytool, also let youoverride the default keystore type (via the-storetypecommand-line parameter).
There are two other types of keystores that come with the JDKimplementation.
"jceks" is an alternate proprietary keystore format to "jks" that uses Password-Based Encryption with Triple-DES.
The Sun "jceks" implementation can parse and convert a "jks" keystore file to the "jceks" format. You may upgrade your keystore of type "jks" to a keystore of type "jceks" by changing the password of a private-key entry in your keystore and specifying-storetype jceks as the keystore type. To apply the cryptographically strong(er) key protection supplied to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords:
keytool -keypasswd -alias signkey -storetype jceks
SeeSecurity Tools for more information aboutkeytool and about keystores and how they are managed.
"dks" is a domain keystore. It is a collection of keystores presented as a single logical keystore. The keystores that comprise a given domain are specified by configuration data whose syntax is described inDomainLoadStoreParameter.
Keystore implementations are provider-based. Developersinterested in writing their own KeyStore implementations shouldconsultHow to Implement aProvider for the Java Cryptography Architecture for moreinformation on this topic.
KeyStoreClassTheKeyStore class is anengineclass that supplies well-defined interfaces to access andmodify the information in a keystore.

Description of Figure TheKeyStore Class
This class represents an in-memory collection of keys andcertificates.KeyStore manages two types ofentries:
This type of keystore entry holds very sensitive cryptographickey information, which is stored in a protected format to preventunauthorized access. Typically, a key stored in this type of entryis a secret key, or a private key accompanied by the certificatechain authenticating the corresponding public key.
Private keys and certificate chains are used by a given entityfor self-authentication using digital signatures. For example,software distribution organizations digitally sign JAR files aspart of releasing and/or licensing software.
This type of entry contains a single public key certificatebelonging to another party. It is called atrustedcertificate because the keystore owner trusts that the publickey in the certificate indeed belongs to the identity identified bythesubject (owner) of the certificate.
This type of entry can be used to authenticate otherparties.
Each entry in a keystore is identified by an "alias" string. Inthe case of private keys and their associated certificate chains,these strings distinguish among the different ways in which theentity may authenticate itself. For example, the entity mayauthenticate itself using different certificate authorities, orusing different public key algorithms.
Whether keystores are persistent, and the mechanisms used by thekeystore if it is persistent, are not specified here. Thisconvention allows use of a variety of techniques for protectingsensitive (e.g., private or secret) keys. Smart cards or otherintegrated cryptographic engines (SafeKeyper) are one option, andsimpler mechanisms such as files may also be used (in a variety offormats).
The mainKeyStore methods are described below.
KeyStore ObjectKeyStore objects are obtained by using one of theKeyStoregetInstance() static factorymethods.
Before aKeyStore object can be used, the actualkeystore data must be loaded into memory via theloadmethod:
final void load(InputStream stream, char[] password)
The optional password is used to check the integrity of thekeystore data. If no password is supplied, no integrity check isperformed.
To create an empty keystore, you passnull as theInputStream argument to theloadmethod.
A DKS keystore is loaded by passing aDomainLoadStoreParameterto the alternative load method:
final void load(KeyStore.LoadStoreParameter param)
All keystore entries are accessed via uniquealiases. Thealiases method returns an enumeration of the aliasnames in the keystore:
final Enumeration aliases()
As stated inTheKeyStoreClass, there are two different types of entries in a keystore.The following methods determine whether the entry specified by thegiven alias is a key/certificate or a trusted certificate entry,respectively:
final boolean isKeyEntry(String alias)final boolean isCertificateEntry(String alias)
ThesetCertificateEntry method assigns acertificate to a specified alias:
final void setCertificateEntry(String alias, Certificate cert)
Ifalias doesn't exist, a trusted certificate entrywith that alias is created. Ifalias exists andidentifies a trusted certificate entry, the certificate associatedwith it is replaced bycert.
ThesetKeyEntry methods add (ifaliasdoesn't yet exist) or set key entries:
final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)final void setKeyEntry(String alias, byte[] key, Certificate[] chain)
In the method withkey as a byte array, it is thebytes for a key in protected format. For example, in the keystoreimplementation supplied by theSUN provider, thekey byte array is expected to contain a protectedprivate key, encoded as anEncryptedPrivateKeyInfo asdefined in the PKCS8 standard. In the other method, thepassword is the password used to protect the key.
ThedeleteEntry method deletes an entry:
final void deleteEntry(String alias)
PKCS #12 keystores support entries containing arbitraryattributes. Use thejava.security.PKCS12Attributeclass to create the attributes. When creating the new keystoreentry use a constructor method that accepts attributes. Finally,use the following method to add the entry to the keystore:
final void setEntry(String alias, Entry entry, ProtectionParameter protParam)
ThegetKey method returns the key associated withthe given alias. The key is recovered using the given password:
final Key getKey(String alias, char[] password)
The following methods return the certificate, or certificatechain, respectively, associated with the given alias:
final Certificate getCertificate(String alias)final Certificate[] getCertificateChain(String alias)
You can determine the name (alias) of the firstentry whose certificate matches a given certificate via thefollowing:
final String getCertificateAlias(Certificate cert)
PKCS #12 keystores support entries containing arbitraryattributes. Use the following method to retrieve an entry that maycontain attributes:
final Entry getEntry(String alias, ProtectionParameter protParam)
and then use theKeyStore.Entry.getAttributes method to extract such attributesand use the methods of theKeyStore.Entry.Attributeinterface to examine them.
The in-memory keystore can be saved via thestoremethod:
final void store(OutputStream stream, char[] password)
The password is used to calculate an integrity checksum of thekeystore data, which is appended to the keystore data.
A DKS keystore is stored by passing aDomainLoadStoreParameterto the alternative store method:
final void store(KeyStore.LoadStoreParameter param)
LikeKeys andKeyspecs, an algorithm'sinitialization parameters are represented by eitherAlgorithmParameters orAlgorithmParameterSpecs. Depending on the usesituation, algorithms can use the parameters directly, or theparameters might need to be converted into a more portable formatfor transmission or storage.
Atransparent representation of a set of parameters (viaAlgorithmParameterSpec) means that you can access eachparameter value in the set individually. You can access thesevalues through one of theget methods defined in thecorresponding specification class (e.g.,DSAParameterSpec definesgetP,getQ, andgetG methods, to accessp,q, andg,respectively).
In contrast, theAlgorithmParameters classsupplies anopaque representation, in which you have nodirect access to the parameter fields. You can only get the name ofthe algorithm associated with the parameter set (viagetAlgorithm) and some kind of encoding for theparameter set (viagetEncoded).
AlgorithmParameterSpecInterfaceAlgorithmParameterSpec is an interface to atransparent specification of cryptographic parameters. Thisinterface contains no methods or constants. Its only purpose is togroup (and provide type safety for) all parameter specifications.All parameter specifications must implement this interface.
The algorithm parameter specification interfaces and classes inthejava.security.spec andjavax.crypto.spec packages are described in the JDK Javadoc APIdocumentation::
The following algorithm parameter specs are used specificallyfor digital signatures, as part ofJSR 105.
AlgorithmParameters ClassTheAlgorithmParameters class is anengine class that provides an opaque representationof cryptographic parameters. You can initialize theAlgorithmParameters class using a specificAlgorithmParameterSpec object, or by encoding theparameters in a recognized format. You can retrieve the resultingspecification with thegetParameterSpec method (seethe following section).
AlgorithmParameters ObjectAlgorithmParameters objects are obtained by usingone of theAlgorithmParametersgetInstance() static factorymethods.
AlgorithmParameters ObjectOnce anAlgorithmParameters object is instantiated,it must be initialized via a call toinit, using anappropriate parameter specification or parameter encoding:
void init(AlgorithmParameterSpec paramSpec)void init(byte[] params)void init(byte[] params, String format)
In theseinit methods,params is anarray containing the encoded parameters, andformat isthe name of the decoding format. In theinit methodwith aparams argument but noformatargument, the primary decoding format for parameters is used. Theprimary decoding format is ASN.1, if an ASN.1 specification for theparameters exists.
AlgorithmParameters objects can beinitialized only once. They are not reusable.A byte encoding of the parameters represented in anAlgorithmParameters object may be obtained via a calltogetEncoded:
byte[] getEncoded()
This method returns the parameters in their primary encodingformat. The primary encoding format for parameters is ASN.1, if anASN.1 specification for this type of parameters exists.
If you want the parameters returned in a specified encodingformat, use
byte[] getEncoded(String format)If
format is null, the primary encoding format forparameters is used, as in the othergetEncoded method.AlgorithmParametersimplementation, supplied by theSUN provider, theformat argument is currently ignored.AlgorithmParameters Object to aTransparent SpecificationA transparent parameter specification for the algorithmparameters may be obtained from anAlgorithmParametersobject via a call togetParameterSpec:
AlgorithmParameterSpec getParameterSpec(Class paramSpec)
paramSpec identifies the specification class inwhich the parameters should be returned. The specification classcould be, for example,DSAParameterSpec.class toindicate that the parameters should be returned in an instance oftheDSAParameterSpec class. (This class is in thejava.security.spec package.)
AlgorithmParameterGenerator ClassTheAlgorithmParameterGenerator class is anengine class used to generate a set ofbrand-new parameters suitable for a certain algorithm (thealgorithm is specified when anAlgorithmParameterGenerator instance is created). Thisobject is used when you do not have an existing set of algorithmparameters, and want to generate one from scratch.
AlgorithmParameterGeneratorObjectAlgorithmParameterGenerator objects are obtained byusing one of theAlgorithmParameterGeneratorgetInstance() static factorymethods.
AlgorithmParameterGeneratorObjectTheAlgorithmParameterGenerator object can beinitialized in two different ways: an algorithm-independent manneror an algorithm-specific manner.
The algorithm-independent approach uses the fact that allparameter generators share the concept of a "size" and a source ofrandomness. The measure of size is universally shared by allalgorithm parameters, though it is interpreted differently fordifferent algorithms. For example, in the case of parameters forthe DSA algorithm, "size" corresponds to the size of the primemodulus, in bits. (SeeJava Cryptography Architecture (JCA) Oracle Providers Documentation for JDK 8 for information about the sizes for specificalgorithms.) When using this approach, algorithm-specific parametergeneration values--if any--default to some standard values. Oneinit method that takes these two universally sharedtypes of arguments:
void init(int size, SecureRandom random);
Anotherinit method takes only asizeargument and uses a system-provided source of randomness:
void init(int size)
A third approach initializes a parameter generator object usingalgorithm-specific semantics, which are represented by a set ofalgorithm-specific parameter generation values supplied in anAlgorithmParameterSpec object:
void init(AlgorithmParameterSpec genParamSpec, SecureRandom random)void init(AlgorithmParameterSpec genParamSpec)
To generate Diffie-Hellman system parameters, for example, theparameter generation values usually consist of the size of theprime modulus and the size of the random exponent, both specifiedin number of bits.
Once you have created and initialized anAlgorithmParameterGenerator object, you can use thegenerateParameters method to generate the algorithmparameters:
AlgorithmParameters generateParameters()
CertificateFactory ClassTheCertificateFactory class is anengine class that defines the functionality of acertificate factory, which is used to generate certificate andcertificate revocation list (CRL) objects from their encodings.
A certificate factory for X.509 must return certificates thatare an instance ofjava.security.cert.X509Certificate,and CRLs that are an instance ofjava.security.cert.X509CRL.
CertificateFactory ObjectCertificateFactory objects are obtained by usingone of thegetInstance()static factory methods.
To generate a certificate object and initialize it with the dataread from an input stream, use thegenerateCertificatemethod:
final Certificate generateCertificate(InputStream inStream)
To return a (possibly empty) collection view of the certificatesread from a given input stream, use thegenerateCertificates method:
final Collection generateCertificates(InputStream inStream)
To generate a certificate revocation list (CRL) object andinitialize it with the data read from an input stream, use thegenerateCRL method:
final CRL generateCRL(InputStream inStream)To return a (possibly empty) collection view of the CRLs read froma given input stream, use the
generateCRLs method:final Collection generateCRLs(InputStream inStream)
CertPath ObjectsThe certificate path builder and validator for PKIX is definedby the Internet X.509 Public Key Infrastructure Certificate and CRLProfile,RFC3280.
A certificate store implementation for retrieving certificatesand CRLs from Collection and LDAP directories, using the PKIX LDAPV2 Schema is also available from the IETF asRFC 2587.
To generate aCertPath object and initialize itwith data read from an input stream, use one of the followinggenerateCertPath methods (with or without specifyingthe encoding to be used for the data):
final CertPath generateCertPath(InputStream inStream)final CertPath generateCertPath(InputStream inStream, String encoding)
To generate aCertPath object and initialize itwith a list of certificates, use the following method:
final CertPath generateCertPath(List certificates)
To retrieve a list of theCertPath encodingssupported by this certificate factory, you can call thegetCertPathEncodings method:
final Iterator getCertPathEncodings()The default encoding will be listed first.
With an understanding of the JCA classes, consider how theseclasses might be combined to implement an advanced network protocollike SSL/TLS. Asasymmetric (public key) cipher operations are much slower thansymmetric operations (secret key), public key cryptography is usedto establish secret keys which are then used to protect the actualapplication data. Vastly simplified, the SSL/TLS handshake involvesexchanging initialization data, performing some public keyoperations to arrive at a secret key, and then using that key toencrypt further traffic.
Assume that this SSL/TLS implementation will be made availableas a JSSE provider. A concrete implementation of theProvider class is first written that will eventuallybe registered in theSecurity class' list ofproviders. This provider mainly provides a mapping from algorithmnames to actual implementation classes. (that is:"SSLContext.TLS"->"com.foo.TLSImpl") When an applicationrequests an "TLS" instance (viaSSLContext.getInstance("TLS"), the provider's list isconsulted for the requested algorithm, and an appropriate instanceis created.
Before discussing details of the actual handshake, a quickreview of some of the JSSE's architecture is needed. The heart ofthe JSSE architecture is theSSLContext. The contexteventually creates end objects (SSLSocket andSSLEngine) which actually implement the SSL/TLSprotocol.SSLContexts are initialized with twocallback classes,KeyManager andTrustManager, which allow applications to first selectauthentication material to send and second to verify credentialssent by a peer.
A JSSEKeyManager is responsible for choosing whichcredentials to present to a peer. Many algorithms are possible, buta common strategy is to maintain a RSA or DSA public/private keypair along with aX509Certificate in aKeyStore backed by a disk file. When aKeyStore object is initialized and loaded from thefile, the file's raw bytes are converted intoPublicKey andPrivateKey objects using aKeyFactory, and a certificate chain's bytes areconverted using aCertificateFactory. When acredential is needed, theKeyManager simply consultsthisKeyStore object and determines which credentialsto present.
AKeyStore's contents might have originally beencreated using a utility such askeytool.keytool creates a RSA or DSAKeyPairGenerator and initializes it with anappropriate keysize. This generator is then used to create aKeyPair whichkeytool would store alongwith the newly-created certificate in theKeyStore,which is eventually written to disk.
A JSSETrustManager is responsible for verifyingthe credentials received from a peer. There are many ways to verifycredentials: one of them is to create aCertPathobject, and let the JDK's built-in Public Key Infrastructure (PKI)framework handle the validation. Internally, the CertPathimplementation might create aSignature object, anduse that to verify that the each of the signatures in thecertificate chain.
With this basic understanding of the architecture, we can lookat some of the steps in the SSL/TLS handshake. The client begins bysending a ClientHello message to the server. The server selects aciphersuite to use, and sends that back in a ServerHello message,and begins creating JCA objects based on the suite selection. We'lluse server-only authentication in the following examples.

Description of Figure SSLMessages
In the first example, the server tries to use a RSA-basedciphersuite such as TLS_RSA_WITH_AES_128_CBC_SHA. The server'sKeyManager is queried, and returns an appropriate RSAentry. The server's credentials (that is: certificate/public key)are sent in the server's Certificate message. The client'sTrustManager verifies the server's certificate, and ifaccepted, the client generates some random bytes using aSecureRandom object. This is then encrypted using anencrypting asymmetric RSACipher object that has beeninitialized with thePublicKey found in the server'scertificate. This encrypted data is sent in a Client Key Exchangemessage. The server would use its correspondingPrivateKey to recover the bytes using a similarCipher in decrypt mode. These bytes are then used toestablish the actual encryption keys.
In a different example, an ephemeral Diffie-Hellman keyagreement algorithm along with the DSA signature algorithm ischosen, such as TLS_DHE_DSS_WITH_AES_128_CBC_SHA. The two sidesmust each establish a new temporary DH public/private keypair usingaKeyPairGenerator. Each generator creates DH keyswhich can then be further converted into pieces using theKeyFactory andDHPublicKeySpec classes.Each side then creates aKeyAgreement object andinitializes it with their respective DHPrivateKeys.The server sends its public key pieces in a ServerKeyExchangemessage (protected by the DSA signature algorithm, and the clientsends its public key in a ClientKeyExchange message. When thepublic keys are reassembled using anotherKeyFactory,they are fed into the agreement objects. TheKeyAgreement objects then generate agreed-upon bytesthat are then used to establish the actual encryption keys.
Once the actual encryption keys have been established, thesecret key is used to initialize a symmetricCipherobject, and this cipher is used to protect all data in transit. Tohelp determine if the data has been modified, aMessageDigest is created and receives a copy of thedata destined for the network. When the packet is complete, thedigest (hash) is appended to data, and the entire packet isencrypted by theCipher. If a block cipher such as AESis used, the data must be padded to make a complete block. On theremote side, the steps are simply reversed.
Again, this is vastly simplified, but gives one an idea of howthese classes might be combined to create a higher levelprotocol.
Note: This section should be ignored by most applicationdevelopers. It is only for people whose applications may be exported to thosefew countries whose governments mandate cryptographic restrictions, if it isdesired that such applications have fewer cryptographic restrictions than thosemandated.
By default, an application can use cryptographic algorithms of any strength.However, due to import control restrictions by the governments of a fewcountries, you may have to limit those algorithms' strength. The JCA frameworkincludes an ability to enforce restrictions regarding the maximum strengths ofcryptographic algorithms available to applications in different jurisdictioncontexts (locations). You specify these restrictions in jurisdiction policyfiles. For more information about jurisdiction policy files and how to createand configure them, seeAppendix B: Jurisdiction Policy FileFormat andAppendix C: Cryptographic StrengthConfiguration.
It is possible that the governments of some or all suchcountries may allow certain applications to become exempt from someor all cryptographic restrictions. For example, they may considercertain types of applications as "special" and thus exempt. Or theymay exempt any application that utilizes an "exemption mechanism,"such as key recovery. Applications deemed to be exempt could getaccess to stronger cryptography than that allowed for non-exemptapplications in such countries.
For an application to be recognized as "exempt" at runtime, it must meet thefollowing conditions:
Below are sample steps required in order to make an application exempt fromsome cryptographic restrictions. This is a basic outline that includesinformation about what is required by JCA in order to recognize and treatapplications as being exempt. You will need to know the exemption requirementsof the particular country or countries in which you would like your applicationto be able to be run but whose governments require cryptographic restrictions.You will also need to know the requirements of a JCA framework vendor that has aprocess in place for handling exempt applications. Consult such a vendor forfurther information.
Note: TheSunJCE provider does not supply animplementation of theExemptionMechanismSpi class.
When an application has a permission policy file associated withit (in the same JAR file) and that permission policy file specifiesan exemption mechanism, then when theCipher getInstance method iscalled to instantiate aCipher, the JCA code searches the installedproviders for one that implements the specified exemption mechanism. If it findssuch a provider, JCA instantiates anExemptionMechanism objectassociated with the provider's implementation, and then associatestheExemptionMechanism object with theCipher returnedbygetInstance.
After instantiating aCipher, and prior to initializing it (viaa call to the Cipherinit method), your code must callthe following Cipher method:
public ExemptionMechanism getExemptionMechanism()
This call returns theExemptionMechanism object associated withtheCipher. You must then initialize the exemption mechanismimplementation by calling the following method on the returnedExemptionMechanism:
public final void init(Key key)
The argument you supply should be the same as the argument ofthe same types that you will subsequently supply to aCipherinit method.
Once you have initialized theExemptionMechanism, you canproceed as usual to initialize and use theCipher.
For an application to be recognized at runtime as being"exempt" from some or all cryptographic restrictions, it must havea permission policy file bundled with it in a JAR file. Thepermission policy file specifies what cryptography-relatedpermissions the application has, and under what conditions (ifany).
Note: The permission policy file bundled with anapplication must be namedcryptoPerms
The format of a permission entry in a permission policy filethat accompanies an exempt application is the same as the formatfor a jurisdiction policy file downloaded with the JDK, whichis:
permission <crypto permission class name>[ <alg_name> [[, <exemption mechanism name>][, <maxKeySize> [, <AlgorithmParameterSpec class name>, <parameters for constructing an AlgorithmParameterSpec object> ]]]];
SeeAppendix B: Jurisdiction Policy File Format.
Some applications may be allowed to be completely unrestricted.Thus, the permission policy file that accompanies such anapplication usually just needs to contain the following:
grant { // There are no restrictions to any algorithms. permission javax.crypto.CryptoAllPermission; };If an application just uses a single algorithm (or severalspecific algorithms), then the permission policy file could simplymention that algorithm (or algorithms) explicitly, rather thangrantingCryptoAllPermission. For example, if an application justuses the Blowfish algorithm, the permission policy file doesn'thave to grantCryptoAllPermission to all algorithms. It could justspecify that there is no cryptographic restriction if the Blowfishalgorithm is used. In order to do this, the permission policy filewould look like the following:
grant { permission javax.crypto.CryptoPermission "Blowfish"; };If an application is considered "exempt" if an exemptionmechanism is enforced, then the permission policy file thataccompanies the application must specify one or more exemptionmechanisms. At runtime, the application will be considered exemptif any of those exemption mechanisms is enforced. Each exemptionmechanism must be specified in a permission entry that looks likethe following:
// No algorithm restrictions if specified // exemption mechanism is enforced. permission javax.crypto.CryptoPermission *, "<ExemptionMechanismName>";
<ExemptionMechanismName> specifies thename of an exemption mechanism. The list of possible exemptionmechanism names includes:
As an example, suppose your application is exempt if either keyrecovery or key escrow is enforced. Then your permission policyfile should contain the following:
grant { // No algorithm restrictions if KeyRecovery is enforced. permission javax.crypto.CryptoPermission *, "KeyRecovery"; // No algorithm restrictions if KeyEscrow is enforced. permission javax.crypto.CryptoPermission *, "KeyEscrow"; };Note: Permission entries that specify exemption mechanismsshouldnot also specify maximum key sizes. The allowed keysizes are actually determined from the installed exemptjurisdiction policy files, as described in the next section.
At runtime, when an application instantiates aCipher (via acall to itsgetInstance method) and that applicationhas an associated permission policy file, the JCA checks to see whetherthe permission policy file has an entry that applies to thealgorithm specified in thegetInstance call. If itdoes, and the entry grantsCryptoAllPermission or does not specifythat an exemption mechanism must be enforced, it means there is nocryptographic restriction for this particular algorithm.
If the permission policy file has an entry that applies to thealgorithm specified in thegetInstance call and theentrydoes specify that an exemption mechanism must beenforced, then the exempt jurisdiction policy file(s) are examined.If the exempt permissions include an entry for the relevantalgorithm and exemption mechanism, and that entry is implied by thepermissions in the permission policy file bundled with theapplication, and if there is an implementation of the specifiedexemption mechanism available from one of the registered providers,then the maximum key size and algorithm parameter values for theCipher are determined from the exempt permission entry.
If there is no exempt permission entry implied by the relevantentry in the permission policy file bundled with the application,or if there is no implementation of the specified exemptionmechanism available from any of the registered providers, then theapplication is only allowed the standard default cryptographicpermissions.
Here are some short examples which illustrate use of several ofthe JCA mechanisms. In addition, complete working examples can befound inAppendix D.
MessageDigestObjectFirst create themessage digestobject, as in the following example:
MessageDigest sha = MessageDigest.getInstance("SHA-256");This call assigns a properly initialized message digest object tothesha variable. The implementation implements theSecure Hash Algorithm (SHA-256), as defined in the National Institutefor Standards and Technology's (NIST)FIPS 180-2document. SeeAppendix A for a completediscussion of standard names and algorithms.Next, suppose we have three byte arrays,i1,i2 andi3, which form the total inputwhose message digest we want to compute. This digest (or "hash")could be calculated via the following calls:
sha.update(i1);sha.update(i2);sha.update(i3);byte[] hash = sha.digest();
An equivalent alternative series of calls would be:
sha.update(i1);sha.update(i2);byte[] hash = sha.digest(i3);After the message digest has been calculated, the message digestobject is automatically reset and ready to receive new data andcalculate its digest. All former state (i.e., the data supplied to
update calls) is lost.Some hash implementations may support intermediate hashesthrough cloning. Suppose we want to calculate separate hashesfor:
i1i1 and i2i1, i2, and i3A way to do it is:
/* compute the hash for i1 */sha.update(i1);byte[] i1Hash = sha.clone().digest();/* compute the hash for i1 and i2 */sha.update(i2);byte[] i12Hash = sha.clone().digest();/* compute the hash for i1, i2 and i3 */sha.update(i3);byte[] i123hash = sha.digest();
This code works only if the SHA-256 implementation is cloneable.While some implementations of message digests are cloneable, othersare not. To determine whether or not cloning is possible, attemptto clone theMessageDigest object and catch thepotential exception as follows:
try { // try and clone it /* compute the hash for i1 */ sha.update(i1); byte[] i1Hash = sha.clone().digest(); // ... byte[] i123hash = sha.digest();} catch (CloneNotSupportedException cnse) { // do something else, such as the code shown below}If a message digest is not cloneable, the other, less elegant wayto compute intermediate digests is to create several digests. Inthis case, the number of intermediate digests to be computed mustbe known in advance:
MessageDigest md1 = MessageDigest.getInstance("SHA-256"); MessageDigest md2 = MessageDigest.getInstance("SHA-256"); MessageDigest md3 = MessageDigest.getInstance("SHA-256"); byte[] i1Hash = md1.digest(i1); md2.update(i1); byte[] i12Hash = md2.digest(i2); md3.update(i1); md3.update(i2); byte[] i123Hash = md3.digest(i3);In this example we will generate a public-private key pair forthe algorithm named "DSA" (Digital Signature Algorithm), and usethis keypair in future examples. We will generate keys with a2048-bit modulus. We don't care which provider supplies thealgorithm implementation.
The first step is to get a key pair generator object forgenerating keys for the DSA algorithm:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");The next step is to initialize the key pair generator. In mostcases, algorithm-independent initialization is sufficient, but insome cases, algorithm-specific initialization is used.
All key pair generators share the concepts of a keysize and asource of randomness. TheKeyPairGenerator classinitialization methods at a minimum needs a keysize. If the sourceof randomness is not explicitly provided, aSecureRandom implementation of the highest-priorityinstalled provider will be used. Thus to generate keys with akeysize of 2048, simply call:
keyGen.initialize(2048);The following code illustrates how to use a specific, additionallyseeded
SecureRandomobject:SecureRandom random = SecureRandom.getInstance("DRBG", "SUN");random.setSeed(userSeed);keyGen.initialize(2048, random);Since no other parameters are specified when you call the abovealgorithm-independentinitialize method, it is up tothe provider what to do about the algorithm-specific parameters (ifany) to be associated with each of the keys. The provider may useprecomputed parameter values or may generate new values.For situations where a set of algorithm-specific parametersalready exists (such as "community parameters" in DSA), there aretwoinitialize methods that have anAlgorithmParameterSpecargument. Suppose your key pair generator is for the "DSA"algorithm, and you have a set of DSA-specific parameters,p,q, andg, that you wouldlike to use to generate your key pair. You could execute thefollowing code to initialize your key pair generator (recall thatDSAParameterSpec is an AlgorithmParameterSpec):
DSAParameterSpec dsaSpec = new DSAParameterSpec(p, q, g);keyGen.initialize(dsaSpec);
p is a primenumber whose length is the modulus length ("size"). Therefore, youdon't need to call any other method to specify the moduluslength.The final step is actually generating the key pair. No matterwhich type of initialization was used (algorithm-independent oralgorithm-specific), the same code is used to generate thekey pair:
KeyPair pair = keyGen.generateKeyPair();
The following signature generation and verification examples usetheKeyPair generated in thekey pairexample above.
We first create asignature object:
Signature dsa = Signature.getInstance("SHA256withDSA");Next, using the key pair generated in the key pair example, weinitialize the object with the private key, then sign a byte arraycalleddata.
/* Initializing the object with a private key */PrivateKey priv = pair.getPrivate();dsa.initSign(priv);/* Update and sign the data */dsa.update(data);byte[] sig = dsa.sign();
Verifying the signature is straightforward. (Note that here wealso use the key pair generated in the key pair example.)
/* Initializing the object with the public key */PublicKey pub = pair.getPublic();dsa.initVerify(pub);/* Update and verify the data */dsa.update(data);boolean verifies = dsa.verify(sig);System.out.println("signature verifies: " + verifies);KeyFactorySuppose that, rather than having a public/private key pair (as,for example, was generated in thekey pairexample above), you simply have the components of your DSAprivate key:x (the private key),p (theprime),q (the sub-prime), andg (thebase).
Further suppose you want to use your private key to digitallysign some data, which is in a byte array namedsomeData. You would do the following steps, which alsoillustrate creating a key specification and using a key factory toobtain aPrivateKey from the key specification(initSign requires aPrivateKey):
DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(x, p, q, g);KeyFactory keyFactory = KeyFactory.getInstance("DSA");PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec);Signature sig = Signature.getInstance("SHA256withDSA");sig.initSign(privKey);sig.update(someData);byte[] signature = sig.sign();Suppose Alice wants to use the data you signed. In order for herto do so, and to verify your signature, you need to send her threethings:
You can store thesomeData bytes in one file, andthesignature bytes in another, and send those toAlice.
For the public key, assume, as in the signing example above, youhave the components of the DSA public key corresponding to the DSAprivate key used to sign the data. Then you can create aDSAPublicKeySpec from those components:
DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(y, p, q, g);
You still need to extract the key bytes so that you can put themin a file. To do so, you can first call thegeneratePublic method on the DSA key factory alreadycreated in the example above:
PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);Then you can extract the (encoded) key bytes via the following:
byte[] encKey = pubKey.getEncoded();
You can now store these bytes in a file, and send it to Alicealong with the files containing the data and the signature.
Now, assume Alice has received these files, and she copied thedata bytes from the data file to a byte array nameddata, the signature bytes from the signature file to abyte array namedsignature, and the encoded public keybytes from the public key file to a byte array namedencodedPubKey.
Alice can now execute the following code to verify thesignature. The code also illustrates how to use a key factory inorder to instantiate a DSA public key from its encoding(initVerify requires aPublicKey).
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedPubKey); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); Signature sig = Signature.getInstance("SHA256withDSA"); sig.initVerify(pubKey); sig.update(data); sig.verify(signature);NOTE: In the above, Alice needed to generate aPublicKey from the encoded key bits, sinceinitVerify requires aPublicKey. Once shehas aPublicKey, she could also use theKeyFactorygetKeySpec method to convertit to aDSAPublicKeySpec so that she can access thecomponents, if desired, as in:DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keyFactory.getKeySpec(pubKey, DSAPublicKeySpec.class)
Now she can access the DSA public key componentsy,p,q, andg through thecorresponding "get" methods on theDSAPublicKeySpecclass (getY,getP,getQ, andgetG).
In many cases you would like to know if two keys are equal;however, the default methodjava.lang.Object.equalsmay not give the desired result. The most provider-independentapproach is to compare the encoded keys. If this comparison isn'tappropriate (for example, when comparing anRSAPrivateKey and anRSAPrivateCrtKey),you should compare each component. The following code demonstratesthis idea:
static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) { return true; } // More code for different types of keys here. // For example, the following code can check if // an RSAPrivateKey and an RSAPrivateCrtKey are equal: // if ((key1 instanceof RSAPrivateKey) && // (key2 instanceof RSAPrivateKey)) { // if ((key1.getModulus().equals(key2.getModulus())) && // (key1.getPrivateExponent().equals( // key2.getPrivateExponent()))) { // return true; // } // } return false;}The following example reads a file with Base64-encodedcertificates, which are each bounded at the beginning by
-----BEGIN CERTIFICATE-----and at the end by
-----END CERTIFICATE-----We convert the
FileInputStream (which does not supportmark andreset) to aByteArrayInputStream (which supports those methods),so that each call togenerateCertificate consumes onlyone certificate, and the read position of the input stream ispositioned to the next certificate in the file:FileInputStream fis = new FileInputStream(filename);BufferedInputStream bis = new BufferedInputStream(fis);CertificateFactory cf = CertificateFactory.getInstance("X.509");while (bis.available() > 0) { Certificate cert = cf.generateCertificate(bis); System.out.println(cert.toString());}The following example parses a PKCS7-formatted certificate replystored in a file and extracts all the certificates from it:
FileInputStream fis = new FileInputStream(filename);CertificateFactory cf = CertificateFactory.getInstance("X.509");Collection c = cf.generateCertificates(fis);Iterator i = c.iterator();while (i.hasNext()) { Certificate cert = (Certificate)i.next(); System.out.println(cert);}This section takes the user through the process of generating akey, creating and initializing a cipher object, encrypting a file,and then decrypting it. Throughout this example, we use theAdvanced Encryption Standard (AES).
To create an AES key, we have to instantiate a KeyGenerator forAES. We do not specify a provider, because we do not care about aparticular AES key generation implementation. Since we do notinitialize the KeyGenerator, a system-provided source of randomnessand a default keysize will be used to create the AES key:
KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecretKey aesKey = keygen.generateKey();After the key has been generated, the same KeyGenerator objectcan be re-used to create further keys.
The next step is to create a Cipher instance. To do this, we useone of thegetInstance factory methods of the Cipherclass. We must specify the name of the requested transformation,which includes the following components, separated by slashes(/):
In this example, we create an AES cipher in Cipher Block Chaining mode, withPKCS5-style padding. We do not specify a provider, because we do not care abouta particular implementation of the requested transformation.
The standard algorithm name for AES is "AES", the standard name for theCipher Block Chaining mode is "CBC", and the standard name for PKCS5-stylepadding is "PKCS5Padding":
Cipher aesCipher; // Create the cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");We use the generatedaesKey from above toinitialize the Cipher object for encryption:
// Initialize the cipher for encryption aesCipher.init(Cipher.ENCRYPT_MODE, aesKey); // Our cleartext byte[] cleartext = "This is just an example".getBytes(); // Encrypt the cleartext byte[] ciphertext = aesCipher.doFinal(cleartext); // Initialize the same cipher for decryption aesCipher.init(Cipher.DECRYPT_MODE, aesKey); // Decrypt the ciphertext byte[] cleartext1 = aesCipher.doFinal(ciphertext);
cleartext andcleartext1 areidentical.
In this example, we prompt the user for a password from which wederive an encryption key.
It would seem logical to collect and store the password in anobject of typejava.lang.String. However, here's thecaveat: Objects of typeString are immutable, i.e.,there are no methods defined that allow you to change (overwrite)or zero out the contents of aString after usage. Thisfeature makesString objects unsuitable for storingsecurity sensitive information such as user passwords. You shouldalways collect and store security sensitive information in a chararray instead.
For that reason, thejavax.crypto.spec.PBEKeySpecclass takes (and returns) a password as a char array. See theReadPassword class in the sample codeinAppendix D for one possible way of readingcharacter array passwords from an input stream.
In order to use Password-Based Encryption (PBE) as defined inPKCS5, we have to specify asalt and aniterationcount. The same salt and iteration count that are used forencryption must be used for decryption. Newer PBE algorithms use an iterationcount of at least 1000.
PBEKeySpec pbeKeySpec; PBEParameterSpec pbeParamSpec; SecretKeyFactory keyFac; // Salt byte[] salt = new SecureRandom().nextBytes(salt); // Iteration count int count = 1000; // Create PBE parameter set pbeParamSpec = new PBEParameterSpec(salt, count); // Prompt user for encryption password. // Collect user password as char array, and convert // it into a SecretKey object, using a PBE key // factory. char[] password = System.console.readPassword("Enter encryption password: "); pbeKeySpec = new PBEKeySpec(password); keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); // Create PBE Cipher Cipher pbeCipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256"); // Initialize PBE Cipher with key and parameters pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); // Our cleartext byte[] cleartext = "This is another example".getBytes(); // Encrypt the cleartext byte[] ciphertext = pbeCipher.doFinal(cleartext);Please refer toAppendix D for sampleprograms exercising the Diffie-Hellman key exchange between 2 and 3parties.
The JDK Security API requires and uses a set of standard namesfor algorithms, certificate and keystore types. The specificationnames previously found here in Appendix A and in the other securityspecifications (JSSE/CertPath/etc.) have been combined inJava Cryptography Architecture (JCA) Oracle Providers Documentation for JDK 8. Thisdocument also contains more information about the algorithmspecifications. Specific provider information can be found inJava Cryptography Architecture (JCA) Oracle Providers Documentation for JDK 8.
Cryptographic implementations in the JDK are distributed throughseveral different providers primarily for historical reasons(Sun,SunJSSE,SunJCE,SunRsaSign). Note these providers may not be availableon all JDK implementations, and therefore, truly portableapplications should callgetInstance() withoutspecifying specific providers. Applications specifying a particularprovider may not be able to take advantage of native providerstuned for an underlying operating environment (such as PKCS orMicrosoft's CAPI).
TheSunPKCS11 provider itself does not contain anycryptographic algorithms, but instead, directs requests into anunderlying PKCS11 implementation. ThePKCS11 Reference Guide and the underlyingPKCS11 implementation should be consulted to determine if a desiredalgorithm will be available through the PKCS11 provider. Likewise,on Windows systems, theSunMSCAPI provider does notprovide any cryptographic functionality, but instead routesrequests to the underlying Operating System for handling.
JCA represents its jurisdiction policy files as Java stylepolicy files with corresponding permission statements. As describedinDefault Policy Implementation andPolicy File Syntax, a Java policy file specifies whatpermissions are allowed for code from specified code sources. Apermission represents access to a system resource. In the case ofJCA, the "resources" are cryptography algorithms, and code sourcesdo not need to be specified, because the cryptographic restrictionsapply to all code.
A jurisdiction policy file consists of a very basic "grantentry" containing one or more "permission entries."
grant {
<permission entries>;
};
The format of a permission entry in a jurisdiction policy fileis:
permission <crypto permission class name>[ <alg_name> [[, <exemption mechanism name>][, <maxKeySize> [, <AlgorithmParameterSpec class name>, <parameters for constructing an AlgorithmParameterSpec object>]]]];
A sample jurisdiction policy file that includes restricting the"Blowfish" algorithm to maximum key sizes of 64 bits is:
grant { permission javax.crypto.CryptoPermission "Blowfish", 64; // ... };A permission entry must begin with the wordpermission. The<crypto permission classname> in the template above would actually be a specificpermission class name, such asjavax.crypto.CryptoPermission. A crypto permissionclass reflects the ability of an application/applet to use certainalgorithms with certain key sizes in certain environments. Thereare two crypto permission classes:CryptoPermissionandCryptoAllPermission. The specialCryptoAllPermission class implies allcryptography-related permissions, that is, it specifies that thereare no cryptography-related restrictions.
The <alg_name>, when utilized, is a quoted stringspecifying the standard name (seeAppendix A)of a cryptography algorithm, such as "AES" or "RSA".
The <exemption mechanism name>, when specified, is aquoted string indicating an exemption mechanism which, if enforced,enables a reduction in cryptographic restrictions. Exemptionmechanism names that can be used include "KeyRecovery" "KeyEscrow",and "KeyWeakening".
<maxKeySize> is an integer specifying the maximum key size(in bits) allowed for the specified algorithm.
For some algorithms it may not be sufficient to specify thealgorithm strength in terms of just a key size. For example, in thecase of the "RC5" algorithm, the number of rounds must also beconsidered. For algorithms whose strength needs to be expressed asmore than a key size, the permission entry should also specify anAlgorithmParameterSpec class name (such asjavax.crypto.spec.RC5ParameterSpec) and a list ofparameters for constructing the specified AlgorithmParameterSpecobject.
Items that appear in a permission entry must appear in thespecified order. An entry is terminated with a semicolon.
Case is unimportant for the identifiers (grant,permission) but is significant for the<crypto permission class name> or for any stringthat is passed in as a value.
NOTE: An "*" can be used as a wildcard for any permission entryoption. For example, an "*" (without the quotes) for an<alg_name> option means "all algorithms."
You can configure the cryptographic strength of the Java CryptographyExtension (JCE) architecture using jurisdiction policy files (seeAppendix B: Jurisdiction Policy File Format) and thesecurity properties file.
By default, the cryptographic strength allowed by Oracle implementations isunlimited. However, administrators and users must still continue to follow allimport/export guidelines for their geographical locations. The activecryptographic strength is determined using a Security Property (typically set inthejava.security properties file), in combination with thejurisdiction policy files found in the configuration directory.
All the necessary JCE policy files to provide either unlimited cryptographicstrength or strong but limited cryptographic strength are bundled with theJDK.
Beginning with JDK 8u161, 7u171 and 6u181, each subdirectory of<java_home>/jre/lib/security/policy represents a policyconfiguration that is defined by the jurisdiction policy files that it contains. By default, this directory contains two subdirectories,limitedandunlimited, each containing a complete set of policy files,packaged in a JAR file.
You can activate a particular policy configuration contained in<java_home>jre/lib/security/policy by setting the valueof thecrypto.policy Security Property (in the file<java_home>/jre/lib/security/java.security) to thename of the subdirectory that contains the policy configuration. By default,thecrypto.policy Security Property is not defined.
The JDK determines the policy configuration to use as follows:
crypto.policy Security Property is defined, then the JDKuses the policy configuration specified by this Security Property.crypto.policy Security Property is not set, and thetraditionalUS_export_policy.jar andlocal_policy.jarfiles (which correspond to strong but limited cryptographic strength andunlimited cryptographic strength, respectively) are found in thelegacy<java_home>/lib/security directory, then the JDKuses the policy configuration specified in these JAR files. This helps preservecompatibility for users upgrading from an older version of the JDK.crypto.policy Security Property is not set, and theUS_export_policy.jar andlocal_policy.jar files don'texist in the<java_home>/lib/security directory,then the JDK uses unlimited cryptographic strength, which is equivalent tocryto.policy=unlimited.The policy configuration setting is VM-wide and affects all applicationsrunning on this VM. If you want to override cryptographic strength at theapplication level, seeHow to Make Applications "Exempt"from Cryptographic Restrictions.
Theunlimited directory contains the following policy files,which provide unlimited cryptographic strength:
<java_home>/jre/lib/security/unlimited/local_policy.jar
default_local.policy: Depending on the country,there may be local restrictions, but as this policy file is located in theunlimited directory, there are no restrictions listed here.
// Country-specific policy file for countries with no limits on crypto strength.grant { // There is no restriction to any algorithms. permission javax.crypto.CryptoAllPermission; };<java_home>/jre/lib/security/unlimited/US_export_policy.jar
default_US_export.policy: As there are nocurrent restrictions on export of cryptography from the United States, this file is set with no restrictions.
// Manufacturing policy file.grant { // There is no restriction to any algorithms. permission javax.crypto.CryptoAllPermission; };Thelimited directory contains the following policy files,which provide strong but limited cryptographic strength:
<java_home>/jre/lib/security/limited/local_policy.jar
default_local.policy: This local policyfile specifies default restrictions. It should be allowed by any country,including those that have import restrictions, but please obtain legalguidance.
// Some countries have import limits on crypto strength. This policy file// is worldwide importable.grant { permission javax.crypto.CryptoPermission "DES", 64; permission javax.crypto.CryptoPermission "DESede", *; permission javax.crypto.CryptoPermission "RC2", 128, "javax.crypto.spec.RC2ParameterSpec", 128; permission javax.crypto.CryptoPermission "RC4", 128; permission javax.crypto.CryptoPermission "RC5", 128, "javax.crypto.spec.RC5ParameterSpec", *, 12, *; permission javax.crypto.CryptoPermission "RSA", *; permission javax.crypto.CryptoPermission *, 128;};exempt_local.policy: Countries that haveimport restrictions should use "limited", but these restrictions could berelaxed if the exemption mechanism can be employed. SeeHow to Make Applications "Exempt" from CryptographicRestrictions. Ensure that you obtain legal guidance for your situation.
// Some countries have import limits on crypto strength. So this file// will be useful.grant { // There is no restriction to any algorithms if KeyRecovery is enforced. permission javax.crypto.CryptoPermission *, "KeyRecovery"; // There is no restriction to any algorithms if KeyEscrow is enforced. permission javax.crypto.CryptoPermission *, "KeyEscrow"; // There is no restriction to any algorithms if KeyWeakening is enforced. permission javax.crypto.CryptoPermission *, "KeyWeakening";};<java_home>/jre/lib/security/limited/US_export_policy.jar
default_US_export.policy: Even though this is in thelimited directory, as there are no current restrictions on exportof cryptography from the United States, this file is set with norestrictions.
// Manufacturing policy file.grant { // There is no restriction to any algorithms. permission javax.crypto.CryptoAllPermission; };To configure cryptographic strength restrictions that differ from thesettings in the policy files in thelimited orunlimited directories, you can create a new subdirectory in<java_home>/jre/lib/security and place your policyfiles there. For example, you can create a directory called<java_home>/jre/lib/security/custom. Inthiscustom directory, you include the filesdefault_*export.policy and/orexempt_*local.policy.
To select the cryptographic strength as defined in the files in thecustom directory, setcrypto.policy=custom in the<java_home>/jre/lib/security/java.securityfile.
/* * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */import java.io.*;import java.math.BigInteger;import java.security.*;import java.security.spec.*;import java.security.interfaces.*;import javax.crypto.*;import javax.crypto.spec.*;import javax.crypto.interfaces.*;import com.sun.crypto.provider.SunJCE;public class DHKeyAgreement2 { private DHKeyAgreement2() {} public static void main(String argv[]) throws Exception { /* * Alice creates her own DH key pair with 2048-bit key size */ System.out.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(2048); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // Alice creates and initializes her DH KeyAgreement object System.out.println("ALICE: Initialization ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Alice encodes her public key, and sends it over to Bob. byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded(); /* * Let's turn over to Bob. Bob has received Alice's public key * in encoded format. * He instantiates a DH public key from the encoded key material. */ KeyFactory bobKeyFac = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(alicePubKeyEnc); PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec); /* * Bob gets the DH parameters associated with Alice's public key. * He must use the same parameters when he generates his own key * pair. */ DHParameterSpec dhParamFromAlicePubKey = ((DHPublicKey)alicePubKey).getParams(); // Bob creates his own DH key pair System.out.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamFromAlicePubKey); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Bob creates and initializes his DH KeyAgreement object System.out.println("BOB: Initialization ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Bob encodes his public key, and sends it over to Alice. byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded(); /* * Alice uses Bob's public key for the first (and only) phase * of her version of the DH * protocol. * Before she can do so, she has to instantiate a DH public key * from Bob's encoded key material. */ KeyFactory aliceKeyFac = KeyFactory.getInstance("DH"); x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc); PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec); System.out.println("ALICE: Execute PHASE1 ..."); aliceKeyAgree.doPhase(bobPubKey, true); /* * Bob uses Alice's public key for the first (and only) phase * of his version of the DH * protocol. */ System.out.println("BOB: Execute PHASE1 ..."); bobKeyAgree.doPhase(alicePubKey, true); /* * At this stage, both Alice and Bob have completed the DH key * agreement protocol. * Both generate the (same) shared secret. */ try { byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); int aliceLen = aliceSharedSecret.length; byte[] bobSharedSecret = new byte[aliceLen]; int bobLen; } catch (ShortBufferException e) { System.out.println(e.getMessage()); } // provide output buffer of required size bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) throw new Exception("Shared secrets differ"); System.out.println("Shared secrets are the same"); /* * Now let's create a SecretKey object using the shared secret * and use it for encryption. First, we generate SecretKeys for the * "AES" algorithm (based on the raw shared secret data) and * Then we use AES in CBC mode, which requires an initialization * vector (IV) parameter. Note that you have to use the same IV * for encryption and decryption: If you use a different IV for * decryption than you used for encryption, decryption will fail. * * If you do not specify an IV when you initialize the Cipher * object for encryption, the underlying implementation will generate * a random one, which you have to retrieve using the * javax.crypto.Cipher.getParameters() method, which returns an * instance of java.security.AlgorithmParameters. You need to transfer * the contents of that object (e.g., in encoded format, obtained via * the AlgorithmParameters.getEncoded() method) to the party who will * do the decryption. When initializing the Cipher for decryption, * the (reinstantiated) AlgorithmParameters object must be explicitly * passed to the Cipher.init() method. */ System.out.println("Use shared secret as SecretKey object ..."); SecretKeySpec bobAesKey = new SecretKeySpec(bobSharedSecret, 0, 16, "AES"); SecretKeySpec aliceAesKey = new SecretKeySpec(aliceSharedSecret, 0, 16, "AES"); /* * Bob encrypts, using AES in CBC mode */ Cipher bobCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); bobCipher.init(Cipher.ENCRYPT_MODE, bobAesKey); byte[] cleartext = "This is just an example".getBytes(); byte[] ciphertext = bobCipher.doFinal(cleartext); // Retrieve the parameter that was used, and transfer it to Alice in // encoded format byte[] encodedParams = bobCipher.getParameters().getEncoded(); /* * Alice decrypts, using AES in CBC mode */ // Instantiate AlgorithmParameters object from parameter encoding // obtained from Bob AlgorithmParameters aesParams = AlgorithmParameters.getInstance("AES"); aesParams.init(encodedParams); Cipher aliceCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aliceCipher.init(Cipher.DECRYPT_MODE, aliceAesKey, aesParams); byte[] recovered = aliceCipher.doFinal(ciphertext); if (!java.util.Arrays.equals(cleartext, recovered)) throw new Exception("AES in CBC mode recovered text is " + "different from cleartext"); System.out.println("AES in CBC mode recovered text is " "same as cleartext"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private static String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); }}/* * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */import java.security.*;import java.security.spec.*;import javax.crypto.*;import javax.crypto.spec.*;import javax.crypto.interfaces.*; /* * This program executes the Diffie-Hellman key agreement protocol between * 3 parties: Alice, Bob, and Carol using a shared 2048-bit DH parameter. */ public class DHKeyAgreement3 { private DHKeyAgreement3() {} public static void main(String argv[]) throws Exception { // Alice creates her own DH key pair with 2048-bit key size System.out.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(2048); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // This DH parameters can also be constructed by creating a // DHParameterSpec object using agreed-upon values DHParameterSpec dhParamShared = ((DHPublicKey)aliceKpair.getPublic()).getParams(); // Bob creates his own DH key pair using the same params System.out.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamShared); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Carol creates her own DH key pair using the same params System.out.println("CAROL: Generate DH keypair ..."); KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH"); carolKpairGen.initialize(dhParamShared); KeyPair carolKpair = carolKpairGen.generateKeyPair(); // Alice initialize System.out.println("ALICE: Initialize ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Bob initialize System.out.println("BOB: Initialize ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Carol initialize System.out.println("CAROL: Initialize ..."); KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH"); carolKeyAgree.init(carolKpair.getPrivate()); // Alice uses Carol's public key Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false); // Bob uses Alice's public key Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); // Carol uses Bob's public key Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false); // Alice uses Carol's result from above aliceKeyAgree.doPhase(cb, true); // Bob uses Alice's result from above bobKeyAgree.doPhase(ac, true); // Carol uses Bob's result from above carolKeyAgree.doPhase(ba, true); // Alice, Bob and Carol compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); System.out.println("Carol secret: " + toHexString(carolSharedSecret)); // Compare Alice and Bob if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) throw new Exception("Alice and Bob differ"); System.out.println("Alice and Bob are the same"); // Compare Bob and Carol if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret)) throw new Exception("Bob and Carol differ"); System.out.println("Bob and Carol are the same"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private static String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } }/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */import java.security.*;import javax.crypto.*;import javax.crypto.spec.*;/** * This program generates a Blowfish key, retrieves its raw bytes, and * then reinstantiates a Blowfish key from the key bytes. * The reinstantiated key is used to initialize a Blowfish cipher for * encryption. */public class BlowfishKey { public static void main(String[] args) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("Blowfish"); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal("This is just an example".getBytes()); }}/* * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */import java.security.*;import javax.crypto.*; /** * This program demonstrates how to generate a secret-key object for * HMACSHA256, and initialize an HMACSHA256 object with it. */ public class initMac { public static void main(String[] args) throws Exception { // Generate secret key for HmacSHA256 KeyGenerator kg = KeyGenerator.getInstance("HmacSHA256"); SecretKey sk = kg.generateKey(); // Get instance of Mac object implementing HmacSHA256, and // initialize it with the above secret key Mac mac = Mac.getInstance("HmacSHA256"); mac.init(sk); byte[] result = mac.doFinal("Hi There".getBytes()); } }/* * @(#)ReadPassword.java 1.1 06/06/07 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */import java.util.*;import java.io.*;import java.security.*;public class ReadPassword { /** * Read a password from the InputStream "in". * <p> * As Strings are immutable, passwords should be stored as an array * of characters, which can be blanked out when no longer needed. * <p> * If the provided InputStream is the System's Console, this method * uses the non-echoing readPassword() method of java.io.Console * (new to JDK 6). If not, a fallback implementation is used. * <p> * NOTE: For expository purposes, and because some applications do * not understand multi-byte characters, only 8-bit ASCII passwords * are handled here. * <p> * NOTE: If a SecurityManager is used, the default standard * java.policy file found in the JDK (i.e. * <java-home>/lib/security/java.policy) allows reading the * line.separator property. If your environment is different, this * code will need to be granted the appropriate privilege. * * @param in * the InputStream used to obtain the password. * * @return A character array containing the password or passphrase, * not including the line-termination characters, * ornull if an end of stream has been reached. * * @throws IOException * if an I/O problem occurs */ public static final char[] readPassword(InputStream in) throws IOException { /* * If available, directly use the java.io.Console class to * avoid character echoing. */ if (in == System.in && System.console() != null) { // readPassword returns "" if you just print ENTER, return System.console().readPassword(); } /* * If a console is not available, read the InputStream * directly. This approach may cause password echoing. * * Since different operating systems have different End-Of-Line * (EOL) sequences, this algorithm should allow for * platform-independent implementations. Typical EOL sequences * are a single line feed ('\n'), or a carriage return/linefeed * combination ('\r\n'). However, some OS's use a single * a carriage return ('\r'), which complicates portability. * * Since we may not have the ability to push bytes back into the * InputStream, another approach is used here. The javadoc for * <code>java.lang.System.getProperties()</code> specifies that * the set of system properties will contain a system-specific * value for the "line.separator". Scan for this character * sequence instead of hard-coding a particular sequence. */ /* * Enclose the getProperty in a doPrivileged block to minimize * the call stack permission required. */ char [] EOL = AccessController.doPrivileged( new PrivilegedAction<char[]>() { public char[] run() { String s = System.getProperty("line.separator"); // Shouldn't happen. if (s == null) { throw new RuntimeException( "line.separator not defined"); } return s.toCharArray(); } }); char [] buffer = new char[128]; try { int len = 0; // len of data in buffer. boolean done = false; // found the EOL sequence int b; // byte read while (!done) { /* * realloc if necessary */ if (len >= buffer.length) { char [] newbuffer = new char[len + 128]; System.arraycopy(buffer, 0, newbuffer, 0, len); Arrays.fill(buffer, ' '); buffer = newbuffer; } /* * End-of-Stream? */ if ((b = in.read()) == -1) { // Return as much as we have, null otherwise. if (len == 0) { return null; } break; } else { /* * NOTE: In the simple PBE example here, * only 8 bit ASCII characters are handled. */ buffer[len++] = (char) b; } /* * check for the EOL sequence. Do we have enough bytes? */ if (len >= EOL.length) { int i = 0; for (i = 0; i < EOL.length; i++) { if (buffer[len - EOL.length + i] != EOL[i]) { break; } } done = (i == EOL.length); } } /* * If we found the EOL, strip the EOL chars. */ char [] result = new char[done ? len - EOL.length : len]; System.arraycopy(buffer, 0, result, 0, result.length); return result; } finally { /* * Zero out the buffer. */ if (buffer != null) { Arrays.fill(buffer, ' '); } } }}