for JavaTM Platform StandardEdition 6
Design Principles
Architecture
JCA Concepts
TheHow the JCA Might Be Used in aSSL/TLS ImplementationProvider
Class
How ProviderImplementations are Requested and SuppliedThe
InstallingProviders
Security
Class
TheSecureRandom
Class
TheMessageDigest
Class
TheSignature
Class
TheCipher
Class
OtherCipher
-basedClasses
The Cipher StreamClassesThe
TheTheCipherInputStream
Class
TheCipherOutputStream
Class
SealedObject
Class
Mac
Class
Key
Interfaces
TheKeyPair
Class
Key
Specification Interfacesand Classes
TheOf Factories andGeneratorsKeySpec
Interface
TheKeySpec
Subinterfaces
TheEncodedKeySpec
Class
ThePKCS8EncodedKeySpec
Class
TheX509EncodedKeySpec
Class
TheKeyFactory
Class
TheSecretKeyFactory
Class
TheKeyPairGenerator
Class
TheKeyGenerator
Class
TheKeyAgreement
Class
Key Management
KeystoreLocationAlgorithm Parameters Classes
KeystoreImplementation
TheKeyStore
Class
TheTheAlgorithmParameterSpec
Interface
TheAlgorithmParameters
Class
TheAlgorithmParameterGenerator
Class
CertificateFactory
Class
How to MakeApplications "Exempt" from CryptographicRestrictions
Computing aAppendix A: StandardNamesMessageDigest
Object
Generating a Pair of Keys
Generating and Verifying a Signature UsingGenerated Keys
Generating/Verifying Signatures UsingKey
Specifications andKeyFactory
Determining If Two Keys Are Equal
Reading Base64-EncodedCertificates
Parsing a Certificate Reply
Using Encryption
Using Password-Based Encryption
Using KeyAgreement
Appendix B: JurisdictionPolicy File Format
Appendix C: Maximum Key SizesAllowed by "Strong" Jurisdiction Policy Files
Diffie-Hellman Key Exchange between2 Parties
Diffie-Hellman Key Exchange between 3Parties
Blowfish Cipher Example
HMAC-MD5 Example
Reading ASCII Passwords From anInputStream Example
The 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 (hashs), 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 to implement security algorithms.Rather, they can request security services from the Java platform.Security services are implemented in providers (see below), whichare plugged into the Java platform via a standard interface. Anapplication may rely on multiple independent providers for securityfunctionality.
Implementation interoperability
- Providers are interoperable across applications. Specifically,an application is not bound to a specific provider, and a provideris not bound to a specific application.
Algorithm extensibility
- The Java platform includes a number of built-in providers thatimplement a basic set of security services that are widely usedtoday. However, some applications may rely on emerging standardsnot yet implemented, or on proprietary services. The Java platformsupports the installation of custom providers that implement suchservices.
Other cryptographic communication libraries available in the JDKuse the JCA provider architecture, but are described elsewhere. TheJavaTM Secure Socket Extension (JSSE) providesaccess to Secure Socket Layer (SSL) and Transport Layer Security(TLS) implementations. The Java Generic Security Services(JGSS) (via Kerberos) APIs, and the Simple Authentication and SecurityLayer (SASL) can also be used for securely exchanging messagesbetween communicating applications.
Notes onTerminology
- Prior to JDK 1.4, the JCE was an unbundled product, and assuch, the JCA and JCE were regularly referred to as separate,distinct components. As JCE is now bundled in the JDK, thedistinction is becoming less apparent. Since the JCE uses the samearchitecture as the JCA, the JCE should be more properly thought ofas a part of the JCA.
- The JCA within the JDK includes two software components:
- the framework that defines and supports cryptographic servicesfor which providers supply implementations. This framework includespackages such as
java.security
,javax.crypto
,javax.crypto.spec
, andjavax.crypto.interfaces
.- the actual providers such as
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.
Design Principles
The JCA was designed around these principles:
- implementation independence and interoperability
- algorithm independence and extensibility
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 called engine classes, and examples are the
MessageDigest
,Signature
,KeyFactory
,KeyPairGenerator
, andCipher
classes.Implementation independence is achieved using a "provider"-basedarchitecture. The term CryptographicService 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 a
Signature
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.
Architecture
Cryptographic ServiceProviders
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 the Provider and Securityclasses). Clients may configure their runtime environment tospecify the provider preference 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 a
MessageDigest
) and a particularalgorithm or service (such as the "MD5" 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("MD5"); md = MessageDigest.getInstance("MD5", "ProviderC");The following figure illustrates requesting an "MD5" messagedigest implementation. The figure show three different providersthat implement various message digest algorithms ("SHA-1", "MD5","SHA-256", and "SHA-512"). The providers are ordered by preferencefrom left to right (1-3). In the first illustration, an applicationrequests an MD5 algorithm implementation without 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 MD5 algorithm implementation from aspecific provider, ProviderC. This time the implementation fromProviderC is returned, even though a provider with a higherpreference order, ProviderB, also supplies an MD5implementation.
![]()
Cryptographic implementations in the Sun 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. See The
Provider
Class for more information on howproviders are written, installed, and registered.How Providers Are Actually Implemented
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 by
Spi
. 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 the
getInstance()
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);![]()
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.
Key Management
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 the
KeyStore
class, which is in thejava.security
package. A defaultKeyStore
implementation is provided by Sun Microsystems. It implements thekeystore as a file, using a proprietary keystore type (format)named "jks". Other keystore formats are available, such as "jceks"which is an alternate proprietary keystore format with muchstronger encryption than "jks", and "pkcs12", which is based on theRSA PKCS12Personal Information Exchange Syntax Standard.Applications can choose different keystore implementations fromdifferent providers, using the same provider mechanism describedabove.
See the Key Management section formore information.
JCA Concepts
This section introduces the major JCA APIs.
Engine Classes andAlgorithms
An engine class provides the interface to a specific type ofcryptographic service, independent of a particular cryptographicalgorithm or provider. The engines either provide:
- cryptographic operations (encryption, digital signatures,message digests, etc.),
- generators or converters of cryptographic material (keys andalgorithm parameters), or
- objects (keystores or certificates) that encapsulate thecryptographic data and can be used at higher layers ofabstraction.
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
: initilializedwith keys, these are used to sign data and verify digitalsignatures.Cipher
: initialized withkeys, these used for encrypting/decrypting data. There are varioustypes of algorithms: symmetric bulk encryption (e.g. AES, DES,DESede, Blowfish, IDEA), stream encryption (e.g. RC4), asymmetricencryption (e.g. RSA), and password-based encryption (PBE).- Message Authentication Codes (MAC): like
MessageDigest
s, 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.SecretKeyFactory
s are specializedKeyFactory
s 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 a keystore. 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 retrieveCertificate
s andCRL
sfrom a repository.
NOTE: A generator creates objects with brand-newcontents, whereas a factory creates objects from existingmaterial (for example, an encoding).
This section discusses the core classes and interfaces providedin the JCA:
The guide will cover the most useful high-level classes first(
- the
Provider
andSecurity
classes,- the
SecureRandom
,MessageDigest
,Signature
,Cipher
,Mac
,KeyFactory
,SecretKeyFactory
,KeyPairGenerator
,KeyGenerator
,KeyAgreement
,AlgorithmParameters
,AlgorithmParameterGenerator
,KeyStore
, andCertificateFactory
, engineclasses,- the
Key
interfaces andclasses,- the Algorithm Parameter SpecificationInterfaces and Classes and the KeySpecification Interfaces and Classes, and
- miscellaneous support and convenience interfaces andclasses.
NOTE: For more information on theCertPathBuilder
,CertPathValidator
,andCertStore
engine classes, please see the Java(TM) PKI Programmer'sGuide.
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 corresponding Examplessections.The complete reference documentation for the relevant SecurityAPI packages can be found in the package summaries:
The
Provider
ClassThe 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. The
Provider
class 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 the
Provider
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.![]()
There are several types of services that can be implemented byprovider packages; for more information, see Engine 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, see theguide How To Implement a Providerfor the Java Cryptography Architecture.
How ProviderImplementations Are Requested and Supplied
For each engine class in the API,a implementation 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.where EngineClassName is the desired engine type(MessageDigest/Cipher/etc). For example:static EngineClassName getInstance(String algorithm) throws NoSuchAlgorithmException static EngineClassName getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException static EngineClassName getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmExceptionMessageDigest md = MessageDigest.getInstance("MD5"); KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");return an instance of the "MD5" MessageDigest and "DH" KeyAgreementobjects, 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 "SHA-1" algorithm might bereferred to as "SHA1". 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. For example,all the following calls are equivalent:MessageDigest.getInstance("SHA-1") MessageDigest.getInstance("sha-1") MessageDigest.getInstance("sHa-1")
If no provider is specified,
getInstance
searchesthe registered providers for an implementation of the requestedcryptographic service associated with the named algorithm. In anygiven Java Virtual Machine (JVM), providers are installed in a given preferenceorder, 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:Now let's look at three scenarios:
PROVIDER_1
implements SHA1withDSA, SHA-1, MD5,DES, and DES3.
PROVIDER_1
has preference order 1 (the highestpriority).PROVIDER_2
implements SHA1withDSA, MD5withRSA,MD2withRSA, MD2, MD5, RC4, RC5, DES, and RSA.
PROVIDER_2
has preference order 2.
- If we are looking for an MD5 implementation. Both providerssupply such an implementation. The
PROVIDER_1
implementation is returned sincePROVIDER_1
has thehighest priority and is searched first.- If we are looking for an MD5withRSA signature algorithm,
PROVIDER_1
is first searched for it. No implementationis found, soPROVIDER_2
is searched. Since animplementation is found, it is returned.- Suppose we are looking for a SHA1withRSA signature algorithm.Since no installed provider implements it, a
NoSuchAlgorithmException
is thrown.The
getInstance
methods that include a 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 SHA1withDSA 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,specifying
PROVIDER_2
since it has the certifiedimplementation:Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");In this case, if
PROVIDER_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 the
getProviders
method intheSecurity
class) andchoosing one from the list.
NOTE: General purpose applications SHOULD NOT requestcryptographic 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.
InstallingProviders
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.Installing the Provider Classes
There are two possible ways to install the provider classes:
- On the normal Java classpath
Place a zip or JAR file containing the classes anywhere in yourclasspath. Some algorithms types (Ciphers) require the provider bea signed Jar file.
- As an Installed/Bundled Extension
The provider will be considered an installed extensionif it is placed in the standard extension directory. In Sun's JDK,that would be located in:
Here <java-home> refers to the directory where theruntime software is installed, which is the top-level directory ofthe JavaTM Runtime Environment(JRE) or the jre directory in the JavaTM JDK software. For example, if you have JDK 6installed on Solaris in a directory named<java-home>/lib/ext [Unix] <java-home>\lib\ext [Windows]/home/user1/JDK1.6.0
, or on Microsoft Windows in adirectory namedC:\Java\JDK1.6.0
, then you need toinstall the JAR file in the following directory:/home/user1/JDK1.6.0/jre/lib/ext [Unix] C:\JDK1.6.0\jre\lib\ext [Windows]Similarly, if you have the JRE 6 installed on Solaris in 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:For more information on how to deploy an extension, see How is an extensiondeployed?/home/user1/jre1.6.0/lib/ext [Unix] C:\jre1.6.0\lib\ext [Windows]Registering the Provider
The next step is to add the provider to your list of 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.
Static Registration
The configuration file is located in the following location:For each registered provider, this file should have a statement ofthe following form:<java-home>/lib/security/java.security [Unix] <java-home>\lib\security\java.security [Windows]security.provider.n=masterClassNameThis declares a provider, and specifies its preference 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 the
SUN
class in thesun.security.provider
package, and the correspondingjava.security file entry is as follows:security.provider.5=sun.security.provider.SunTo 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 is
com.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.ProviderXDynamic Registration
To register providers dynamically, applications call either theaddProvider
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. See Security.Setting ProviderPermissions
Whenever encryption providers are used (that is, those thatsupply implementations of Cipher, KeyAgreement, KeyGenerator, Mac,or SecretKeyFactory), and the provider is not an installedextension Permissions 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 defaultsystem policy configuration filegrants all permissions to installed extensions (that is, installedin the extensions 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 in
myjce_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 MethodsEach
Provider
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()The
Security
ClassThe
Security
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" iseitherThe determination that code is considered trusted to perform anattempted action (such as adding a provider) requires that theapplet is granted the proper permission(s) for that particularaction. The policy configuration file(s) for a JDK installationspecify what permissions (which types of system resource accesses)are allowed by code from specified code sources. (See below and the "Default Policy Implementation andPolicy File Syntax" and "Java Security ArchitectureSpecification" files for more information.)
- a local application not running under a security manager,or
- an applet or application with permission to execute thespecified method (see below).
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's keystore.
In a policy configuration file, a code source is represented bytwo components: a code base (URL), and an alias name (preceded by
signedBy
), 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:
This configuration file specifies that code loaded from a signedJAR file from beneath thegrant codeBase "file:/home/sysadmin/", signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; permission java.security.SecurityPermission "putProviderProperty.*"; };/home/sysadmin/
directory 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 the
codeBase
is omitted:If this policy is in effect, code that comes in a JAR File signedbygrant signedBy "sysadmin" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };sysadmin
can add/remove providers--regardless ofwhere the JAR File originated.Here's an example without a signer:
In this case, code that comes from anywhere within thegrant codeBase "file:/home/sysadmin/" { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };/home/sysadmin/
directory on the local filesystem canadd/remove providers. The code does not need to be signed.An example where neither
codeBase
norsignedBy
is included is:Here, with both code source components missing, any code(regardless of where it originates, or whether or not it is signed,or who signed it) can add/remove providers. Obviously, this isdefinitely NOT 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 roguegrant { permission java.security.SecurityPermission "insertProvider.*"; permission java.security.SecurityPermission "removeProvider.*"; };Cipher
objectmight capture and store the sensitive information it receives.)Managing Providers
The following tables summarize the methods in the
Security
class you can use to query whichProvider
s are installed, as well as to install orremove providers at runtime.
Quering Providers Method Description static Provider[] getProviders()
Returns an array containing all the installedproviders (technically, the Provider
subclass for eachpackage provider). The order of theProvider
s in thearray is their preference order.static Provider getProvider
(String providerName)Returns the Provider
namedproviderName
. It returnsnull
if theProvider
is not found.
Adding Providers Method Description static int addProvider(Provider provider)
Adds a Provider
to the end of the list ofinstalledProvider
s. 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, int position)Adds a new
Provider
at a specified position. If thegiven provider is installed at the requested position, the providerformerly at that position and all providers with a position greaterthanposition
are shifted up one position (towards theend of the list). This method returns the preference position inwhich theProvider
was added, or-1
iftheProvider
was not added because it was alreadyinstalled.
Removing Providers Method Description static void removeProvider(Stringname)
Removes the Provider
with thespecified name. It returns silently if the provider is notinstalled. When the specified provider is removed, all providerslocated at a position greater than where the specified provider wasare shifted down one position (towards the head of the list ofinstalled providers).
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.
Security Properties
The
Security
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:Note: the list of security providers is established during VMstartup, therefore the methods described above must be used toalter the provider list.static String getProperty(String key) static void setProperty(String key, String datum)As a reminder, the configuration file is located in thefollowing location:
<java-home>/lib/security/java.security [Unix] <java-home>\lib\security\java.security [Windows]The
SecureRandom
ClassThe
SecureRandom
class is an engine class that provides the functionality of aRandom Number Generator (RNG). It differs from theRandom
class in that it produces cryptographicallystrong random numbers. If there is insufficient randomness in agenerator, it makes it much easier to compromise your protectionmechanisms. Random numbers are used throughout cryptography, suchas generating cryptographic keys or algorithmic parameters.![]()
Creating a
SecureRandom
ObjectAs with all engine classes, the way to get aSecureRandom
object is to call one of thegetInstance()
static factorymethods in theSecureRandom
class.Seeding or Re-Seeding the
SecureRandom
ObjectThe
SecureRandom
implementation attempts tocompletely randomize the internal state of the generator itselfunless the caller follows the call to agetInstance
method with a call to one of thesetSeed
methods:Once thesynchronized public void setSeed(byte[] seed) public void setSeed(long seed)SecureRandom
object has been seeded, it willproduce bits as random as the original seeds.At any time a
SecureRandom
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.Using a
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)Generating Seed 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)The
MessageDigest
ClassThe
MessageDigest
class is an engine class designed to provide the functionality ofcryptographically secure message digests such as SHA-1 or MD5. Acryptographically secure message digest takes arbitrary-sized input(a byte array), and generates a fixed-size output, called adigest or hash.![]()
For example, the MD5 algorithm produces a 16 byte digest, andSHA1's is 20 bytes.
A digest has two properties:
- It should be computationally infeasible to find two messagesthat hash to the same value.
- The digest should not reveal anything about the input that wasused to generate it.
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.
Creating a
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.Updating a Message Digest Object
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 the
update
methods:void update(byte input) void update(byte[] input) void update(byte[] input, int offset, int len)Computing the Digest
After the data chunks have been supplied by calls to
update
, the digest is computed using a call to one 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 final
update(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 inbuf
allotted 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 the Computing a
MessageDigest
example in the Code Examples section for more details.The
Signature
ClassTheSignature
class is an engine class designed to provide the functionality ofa cryptographic digital signature algorithm such as DSA orRSAwithMD5. A cryptographically secure signature algorithm takesarbitrary-sized input and a private key and generates a relativelyshort (often fixed-size) string of bytes, called the signature, with the following properties:It can also be used to verify whether or not an alleged signatureis in fact the authentic signature of the data associated with it.
- Only the owner of a private/public key pair is able to create asignature. It should be computationally infeasible for anyonehaving a public key to recover the private key.
- Given the public key corresponding to the private key used togenerate the signature, it should be possible to verify theauthenticity and integrity of the input.
- The signature and the public key do not reveal anything aboutthe private key.
![]()
A
Signature
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 "SHA1WithRSA" use the messagedigest "SHA1" to initially "compress" the large data sets into amore manageable form, then sign the resulting 20 byte messagedigest with the "RSA" algorithm.
Please see the Examples section for anexample of signing and verifying data.
Signature
Object StatesSignature
objects are modal objects. Thismeans that aSignature
object is always in a givenstate, where it may only do one type of operation. States arerepresented as final integer constants defined in their respectiveclasses.The three states a
Signature
object may haveare:When it is first created, a
UNINITIALIZED
SIGN
VERIFY
Signature
object is in theUNINITIALIZED
state. TheSignature
classdefines two initialization methods,initSign
andinitVerify
, which change the state toSIGN
andVERIFY
,respectively.Creating a
Signature
ObjectThe first step for signing or verifying a signature isto create aSignature
instance.Signature
objects are obtained by using one of theSignature
getInstance()
staticfactory methods.Initializing a
Signature
ObjectA
Signature
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:
This method puts thefinal void initSign(PrivateKey privateKey)Signature
object in theSIGN
state.If instead the
Signature
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 the
Signature
object in theVERIFY
state.Signing
If the
Signature
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 the
update
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 the
sign
methods:final byte[] sign() final int sign(byte[] outbuf, int offset, int len)The first method returns the signature result in a byte array.The second stores the signature result in the provided bufferoutbuf, starting at offset. len is the numberof bytes in outbuf allotted for the signature. The methodreturns the number of bytes actually stored.
Signature encoding is algorithm specific. See the Standard Names document for moreinformation about the use of ASN.1 encoding in the JavaCryptography Architecture.
A call to a
sign
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 to
initSign
specifying a different private key, or toinitVerify
(to initialize theSignature
object to verify asignature).Verifying
If the
Signature
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 the
update
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. Theargument must be a byte array containing the signature. This bytearray would hold the signature bytes which were returned by aprevious call to one of the
sign
methods.The
verify
method returns aboolean
indicating whether or not the encoded signature is the authenticsignature of the data supplied to theupdate
method(s).A call to the
verify
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 to
initVerify
specifying 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).The Cipher Class
The
Cipher
class provides the functionality of acryptographic cipher used for encryption and decryption. Encryptionis the process of taking data (called cleartext) 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.![]()
Symmetric vs. Asymmetric Cryptography
There are two major types of encryption: symmetric (also known as secret key), and asymmetric (or public key cryptography). In symmetriccryptography, the same secret key to both encrypt and decrypt thedata. Keeping the key private is critical to keeping the dataconfidential. On the other hand, asymmetric cryptography uses apublic/private key pair to encrypt data. Data encrypted with onekey is decrypted with the other. A user first generates apublic/private key pair, and then publishes the public key in atrusted database that anyone can access. A user who wishes tocommunicate securely with that user encrypts the data using theretrieved public key. Only the holder of the private key will beable to decrypt. Keeping the private key confidential is criticalto 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.
Stream vs. Block Ciphers
There are two major types of ciphers: block and stream. Block ciphers process entire blocks at a time,usually many bytes in length. If there is not enough data to make acomplete input block, the data must be padded: 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.Modes Of Operation
When encrypting using a simple block cipher, twoidentical blocks of plaintext will always produce an identicalblock of cipher text. Cryptanalysts trying to break the ciphertextwill have an easier job if they note blocks of repeating text. Inorder to add more complexity to the text, feedback modes use theprevious block of output to alter the input blocks before applyingthe encryption algorithm. The first block will need an initialvalue, and this value is called the initialization vector(IV). Since the IV simply alters the data before anyencryption, the IV should be random but does not necessarily needto be kept secret. There are a variety of modes, such as CBC(Cipher Block Chaining), CFB (Cipher Feedback Mode), and OFB(Output Feedback Mode). ECB (Electronic Cookbook Mode) is a modewith no feedback.Some algorithms such as AES and RSA allow for keys of differentlengths, but others are fixed, such as DES and 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.
Creating a Cipher Object
Cipher
objects are obtained by using oneof theCipher
getInstance()
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 the operation(or set of operations) to be performed on the given input toproduce some output. A transformation always includes the name of acryptographic algorithm (e.g.,DES
), and may befollowed by a mode and padding scheme.
A transformation is of the form:
- "algorithm/mode/padding" or
- "algorithm"
For example, the following are valid transformations:
"DES/CBC/PKCS5Padding" "DES"If just a transformation name is specified, the system 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.
If no mode or padding is specified, provider-specific defaultvalues for the mode and padding scheme are used. For example, the
SunJCE
provider usesECB
as the defaultmode, andPKCS5Padding
as the default padding schemeforDES
,DES-EDE
andBlowfish
ciphers. This means that in the case of theSunJCE
provider:Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");andCipher c1 = Cipher.getInstance("DES");are equivalent statements.
Using modes such as CFB and OFB, block ciphers can encrypt 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 "DES/CFB8/NoPadding" and"DES/OFB32/PKCS5Padding" transformations. If no such numberis specified, a provider-specific default is used. (For example,the
SunJCE
provider uses a default of 64 bits forDES.) 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.
Initializing a CipherObject
A Cipher object obtained via
getInstance
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:ENCRYPT_MODE
- Encryption of data.
DECRYPT_MODE- Decryption of data.
WRAP_MODE- Wrapping a
UNWRAP_MODEjava.security.Key
into bytes so thatthe key can be securely transported.- Unwrapping of a previously wrapped key into a
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 following
init
methods:public void init(int opmode, Key key); public void init(int opmode, Certificate certificate); public void init(int opmode, Key key, SecureRandom random); public void init(int opmode, Certificate certificate, SecureRandom random); public void init(int opmode, Key key, AlgorithmParameterSpec params); public void init(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random); public void init(int opmode, Key key, AlgorithmParameters params); public void init(int opmode, Key key, AlgorithmParameters params, SecureRandom random);If a Cipher object that requires parameters (e.g., aninitialization vector) is initialized for encryption, and noparameters are supplied to the
init
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 the
init
method, anInvalidKeyException
orInvalidAlgorithmParameterException
exception will beraised, depending on theinit
method that has beenused.See the section about ManagingAlgorithm 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.
Encrypting and DecryptingData
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 the
doFinal
methods:public byte[] doFinal(byte[] input); public byte[] doFinal(byte[] input, int inputOffset, int inputLen); public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output); public int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)To encrypt or decrypt data in multiple steps, call one of the
update
methods:public byte[] update(byte[] input); public byte[] update(byte[] input, int inputOffset, int inputLen); public int update(byte[] input, int inputOffset, int inputLen, byte[] output); public int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)A multiple-part operation must be terminated by one of the above
doFinal
methods (if there is still some input 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 the
doFinal
methods take care of any necessarypadding (or unpadding), if padding (or unpadding) has beenrequested as part of the specified transformation.A call to
doFinal
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 and UnwrappingKeys
Wrapping a key enables secure transfer of the key from one placeto another.
The
wrap/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.To wrap 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 ofcalling
wrap
) to someone else who will unwrap them, besure to also send additional information the recipient will need inorder to do theunwrap
:
- the name of the key algorithm, and
- the type of the wrapped key (one of
Cipher.SECRET_KEY
,Cipher.PRIVATE_KEY
, orCipher.PUBLIC_KEY
).The key algorithm name can be determined by calling the
getAlgorithm
method from the Key interface:public String getAlgorithm();To unwrap the bytes returned by a previous call to
wrap
, first initialize a Cipher object 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
.ManagingAlgorithm Parameters
The parameters being used by the underlying Cipherimplementation, which were either explicitly passed to the
init
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 - a salt 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("PBEWithMD5AndDES"); // initialize cipher for encryption, without supplying // any parameters. Here, "myKey" is assumed to refer // to an already-generated key. c.init(Cipher.ENCRYPT_MODE, myKey); // encrypt some data and store away ciphertext // for later decryption byte[] cipherText = c.doFinal("This is just an example".getBytes()); // retrieve parameters generated by underlying cipher // implementation AlgorithmParameters algParams = c.getParameters(); // get parameter encoding and store it away byte[] encodedAlgParams = algParams.getEncoded();The same parameters that were used for encryption must be 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("PBEWithMD5AndDES"); // initialize with parameter encoding from above algParams.init(encodedAlgParams); // get cipher object for password-based encryption Cipher c = Cipher.getInstance("PBEWithMD5AndDES"); // initialize cipher for decryption, using one of the // init() methods that takes an AlgorithmParameters // object, and pass it the algParams object from above c.init(Cipher.DECRYPT_MODE, myKey, algParams);If you did not specify any parameters when you initialized aCipher object, and you are not sure whether or not the underlyingimplementation uses any parameters, you can find out by simplycalling the
getParameters
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 the
SunJCE
provider use parameters:
- DES, DES-EDE, and Blowfish, when used in feedback (i.e., CBC,CFB, OFB, or PCBC) mode, use an initialization vector (IV). The
javax.crypto.spec.IvParameterSpec
class can be used toinitialize a Cipher object with a given IV.- PBEWithMD5AndDES uses a set of parameters, comprising a saltand an iteration count. The
javax.crypto.spec.PBEParameterSpec
class can be usedto initialize a Cipher object implementing PBEWithMD5AndDES 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 the
SealedObject
class. This class attaches the parameters used for sealing(encryption) to the encrypted object contents, and uses the sameparameters for unsealing (decryption).Cipher Output Considerations
Some of the
update
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)Other
Cipher
-based ClassesThere are some helper classes which interally useCipher
s to provide easy access to common cipher uses.The Cipher StreamClasses
A simple, secure, stream-based communication object can becreated by combining existing
InputStream/OutputStream
s withCipher
objects.The CipherInputStreamClass
This class is a
FilterInputStream
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 classes
java.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, suppose
cipher1
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 that
cipher1
andcipher2
have 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 the
CipherInputStream
will 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.The CipherOutputStreamClass
This class is a
FilterOutputStream
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 classes
java.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, suppose
cipher1
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 that
cipher1
andcipher2
have 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 using block cipheralgorithms is that a full block of plaintext data must be given tothe
CipherOutputStream
before the data will beencrypted and sent to the underlying output stream.There is one other important difference between the
flush
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 will not 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 itsflush
method.The SealedObjectClass
This class enables a programmer to create an object and protectits confidentiality with a cryptographic algorithm.
Given any object that implements the
java.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 DES,to protect its confidentiality. The encrypted content can later bedecrypted (with the corresponding algorithm using the correctdecryption key) and de-serialized, yielding the originalobject.A typical usage is illustrated in the following code segment: Inorder to seal an object, you create a
SealedObject
from 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 DES 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 DES key. Cipher c = Cipher.getInstance("DES"); c.init(Cipher.ENCRYPT_MODE, sKey); // do the sealing SealedObject so = new SealedObject("This is a secret", c);The original object that was sealed can be recovered in twodifferent ways:
- by using a
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.
- by using the appropriate decryption key (since DES is asymmetric encryption algorithm, we use the same key for sealing andunsealing):
try { String s = (String)so.getObject(sKey); } catch (Exception e) { // do something };In this approach, the
getObject
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.The Mac Class
Similar to a
MessageDigest
, 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.![]()
A MAC mechanism that is based on cryptographic hash functions isreferred to as HMAC. HMAC can be used with any cryptographic hashfunction, e.g., MD5 or SHA-1, in combination with a secret sharedkey.
The
Mac
class provides the functionality of aMessage Authentication Code (MAC). Please refer to the code example.Creating a
Mac
ObjectMac
objects are obtained by using one oftheMac
getInstance()
static factorymethods.Initializing a Mac Object
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 its
init
methods:public void init(Key key); public void init(Key key, AlgorithmParameterSpec params);You can initialize your Mac object with any (secret-)key objectthat implements the
javax.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 the
SunJCE
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.Computing a MAC
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 thefollowing
doFinal
method:public byte[] doFinal(byte[] input);To compute the MAC of some data in multiple steps, call one ofthe
update
methods:public void update(byte input); public void update(byte[] input); public void update(byte[] input, int inputOffset, int inputLen);A multiple-part operation must be terminated by the above
doFinal
method (if there is still some input data leftfor the last step), or by one of the followingdoFinal
methods (if there is no input data left for the last step):public byte[] doFinal(); public void doFinal(byte[] output, int outOffset);
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.
The
java.security.Key
interface is the top-levelinterface for all opaque keys. It defines the functionality sharedby all opaque key objects.An opaque 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 the
Key
interface (see below):getAlgorithm
,getFormat
, andgetEncoded
.This is in contrast to a transparent representation, inwhich you can access each key material value individually, throughone of the
get
methods defined in the correspondingspecification class.All opaque keys have three characteristics:
Keys are generally obtained through key generators such asAn Algorithm
- The key algorithm for that key. The key algorithm is usually anencryption or asymmetric operation algorithm (such as
An Encoded FormAES
,DSA
orRSA
), which willwork with those algorithms and with related algorithms (such asMD5withRSA
,SHA1withRSA
, etc.) The nameof the algorithm of a key is obtained using this method:String getAlgorithm()- The external encoded form for the key used when a standardrepresentation of the key is needed outside the Java VirtualMachine, as when transmitting the key to some other party. The keyis encoded according to a standard format (such as X.509 or PKCS8),and is returned using the method:
A Formatbyte[] getEncoded()- The name of the format of the encoded key. It is returned bythe method:
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 a
CertificateFactory
.Here is a list of interfaces which extend the
Key
interface in thejava.security.interfaces
andjavax.crypto.interfaces
packages:
The
PublicKey
andPrivateKey
InterfacesThe
PublicKey
andPrivateKey
interfaces (which both extend theKey
interface) aremethodless interfaces, used for type-safety andtype-identification.The
KeyPair
ClassThe
KeyPair
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 Specification Interfacesand Classes
Key
objects and key specifications(KeySpec
s) are two different representations of keydata.Cipher
s useKey
objects toinitialize their encryption algorithms, but keys may need to beconverted into a more portable format for transmission orstorage.A transparent representation of keys means that you canaccess each key material value individually, through one of the
get
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 an opaquerepresentation, as defined by the
Key
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 components
x
,p
,q
, andg
(seeDSAPrivateKeySpec
),or it may be specified using its DER encoding (seePKCS8EncodedKeySpec
).The
KeyFactory
andSecretKeyFactory
classes can be used to convert between opaque and transparent keyrepresentations (that is, betweenKey
s andKeySpec
s, assuming that the operation is possible.(For example, private keys on smart cards might not be able leavethe card. SuchKey
s are not convertible.)In the following sections, we discuss the key specificationinterfaces and classes in the
java.security.spec
package.The
KeySpec
InterfaceThis interface contains no methods or constants. Its onlypurpose is to group and provide type safety for all keyspecifications. All key specifications must implement thisinterface.
The
KeySpec
SubinterfacesLike theKey
interface, there are asimilar set ofKeySpec
interfaces.
The
EncodedKeySpec
ClassThis abstract class (which implements theKeySpec
interface) represents a publicor private key in encoded format. ItsgetEncoded
method returns the encoded key:and itsabstract byte[] getEncoded();getFormat
method returns the name of theencoding format:abstract String getFormat();See the next sections for the concrete implementations
PKCS8EncodedKeySpec
andX509EncodedKeySpec
.The
PKCS8EncodedKeySpec
ClassThis class, which is a subclass ofEncodedKeySpec
, represents the DER encoding of aprivate key, according to the format specified in the PKCS8standard. ItsgetEncoded
method returns the key bytes,encoded according to the PKCS8 standard. ItsgetFormat
method returns the string "PKCS#8".The
X509EncodedKeySpec
ClassThis class, which is a subclass ofEncodedKeySpec
, represents the DER encoding of apublic key, according to the format specified in the X.509standard. ItsgetEncoded
method returns the key bytes,encoded according to the X.509 standard. ItsgetFormat
method returns the string "X.509".Of Generatorsand Factories
Newcomers to Java and the JCA APIs in particularsometimes do not grasp the distinction between generators andfactories.![]()
Generators are used to generate 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 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 to convert data fromone existing object type to another. For example, anapplication might have available the components of a DH private keyand can package them as a
KeySpec
, 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.The
KeyFactory
ClassTheKeyFactory
class is an engine class designed to perform conversions betweenopaque cryptographicKey
s and key specifications (transparentrepresentations of the underlying key material).![]()
Key factories are bi-directional. 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 itscomponents
y
,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 translatefrom
X509EncodedKeySpec
toDSAPublicKeySpec
, you basically parse the encoded keyinto its components. For an example, see the end of the Generating/Verifying Signatures Using KeySpecifications andKeyFactory
section.Creating a
KeyFactory
Object
KeyFactory
objects are obtained by using one of theKeyFactory
getInstance()
static factorymethods.Converting Between a Key Specification and a Key Object
If you have a key specification for a public key, you can obtainan opaque
PublicKey
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 opaque
PrivateKey
object from thespecification by using thegeneratePrivate
method:PrivateKey generatePrivate(KeySpec keySpec)Converting Between a Key Object and a Key Specification
If you have a
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, beDSAPublicKeySpec.class
, to indicate that the keymaterial should be returned in an instance of theDSAPublicKeySpec
class.Please see the Examples section formore details.
TheSecretKeyFactory Class
This class represents a factory for secret keys. Unlike
KeyFactory
, ajavax.crypto.SecretKeyFactory
object operates only onsecret (symmetric) keys, whereas ajava.security.KeyFactory
object processes the publicand private key components of a key pair.![]()
Key factories are used to convert
Key
s (opaque cryptographic keys of typejava.security.Key
) into keyspecifications (transparent representations of the underlyingkey material in a suitable format), and vice versa.Objects of type
java.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 value
y
,the prime modulusp
, and the baseg
, andyou feed the same specification to Diffie-Hellman key factoriesfrom different providers, the resultingPublicKey
objects will most likely have different underlyingimplementations.A provider should document the key specifications supported byits secret key factory. For example, the
SecretKeyFactory
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 a
SecretKeyFactory
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 DESKeySpec. byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 }; DESKeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);In this case, the underlying implementation of
SecretKey
is based on the provider ofKeyFactory
.An alternative, provider-independent way of creating afunctionally equivalent
SecretKey
object from the samekey material is to use thejavax.crypto.spec.SecretKeySpec
class, whichimplements thejavax.crypto.SecretKey
interface:byte[] desKeyData = { (byte)0x01, (byte)0x02, ...}; SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");Creating a
SecretKeyFactory
Object
SecretKeyFactory
objects are obtained by using oneof theSecretKeyFactory
getInstance()
static factorymethods.Converting Between a Key Specification and a Secret KeyObject
If you have a key specification for a secret key, you can obtainan opaque
SecretKey
object from the specification byusing thegenerateSecret
method:SecretKey generateSecret(KeySpec keySpec)Converting Between a Secret Key Object and a KeySpecification
If you have a
Secret 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 theDESKeySpec
class.The
KeyPairGenerator
ClassThe
KeyPairGenerator
class is an engine class used to generate pairs of public andprivate keys.![]()
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 the Examples section forexamples of calls to the methods documented below.
Creating a
KeyPairGenerator
All key pair generation starts with a
KeyPairGenerator
.KeyPairGenerator
objects are obtained by using one of theKeyPairGenerator
getInstance()
static factorymethods.Initializing a
KeyPairGenerator
A key pair generator for a particular algorithm createsa public/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.
Algorithm-Independent Initialization
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.(See the Standard Namesdocument for information about the keysizes for specificalgorithms.)
An
initialize
method takes two universally sharedtypes of arguments:Anothervoid initialize(int keysize, SecureRandom random)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-independent
initialize
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 the
SUN
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.Algorithm-Specific Initialization
For situations where a set of algorithm-specific parametersalready exists (such as "community parameters" in DSA), there aretwo
initialize
methods that have anAlgorithmParameterSpec
argument. One also has aSecureRandom
argument, whilethe source of randomness is system-provided for the other:See the Examples section for moredetails.void initialize(AlgorithmParameterSpec params, SecureRandom random) void initialize(AlgorithmParameterSpec params)Generating a Key Pair
The procedure for generating a key pair is always the same,regardless of initialization (and of the algorithm). You alwayscall the following method from
KeyPairGenerator
:Multiple calls toKeyPair generateKeyPair()generateKeyPair
will yield differentkey pairs.The KeyGeneratorClass
A key generator is used to generate secret keys for symmetricalgorithms.
![]()
Creating a
KeyGenerator
KeyGenerator
objects are obtained by usingone of theKeyGenerator
getInstance()
static factorymethods.Initializing a KeyGenerator Object
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:
- Algorithm-Independent Initialization
All key generators share the concepts of a keysize and asource of randomness. There is an
init
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-independent
init
methods, it is up to theprovider what to do about the algorithm-specific parameters (ifany) to be associated with the generated key.- Algorithm-Specific Initialization
For situations where a set of algorithm-specific parametersalready exists, there are two
init
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 an
init
method), eachprovider must supply (and document) a default initialization.Creating a Key
The following method generates a secret key:public SecretKey generateKey();The KeyAgreementClass
Key agreement is a protocol by which 2 or more partiescan establish the same cryptographic keys, without having toexchange any secret information.![]()
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, each
KeyAgreement
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.Creating a KeyAgreement Object
Each party involved in the key agreement has to create aKeyAgreement object.
KeyAgreement
objects are obtainedby using one of theKeyAgreement
getInstance()
static factorymethods.Initializing a KeyAgreement Object
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 primemodulus
p
and a base generatorg
as itsparameters.)To initialize a KeyAgreement object, call one of its
init
methods:public void init(Key key); public void init(Key key, SecureRandom random); public void init(Key key, AlgorithmParameterSpec params); public void init(Key key, AlgorithmParameterSpec params, SecureRandom random);Executing a KeyAgreement Phase
Every key agreement protocol consists of a number of phases thatneed to be executed by each party involved in the keyagreement.
To execute the next phase in the key agreement, call the
doPhase
method:public Key doPhase(Key key, boolean lastPhase);The
key
parameter contains the key to be 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.The
lastPhase
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 of Diffie-Hellman between twoparties , you call
doPhase
once, withlastPhase
set toTRUE
. In the example ofDiffie-Hellman between three parties, you calldoPhase
twice: the first time withlastPhase
set toFALSE
, the 2nd time withlastPhase
set toTRUE
.Generating the Shared Secret
After each party has executed all the required key agreementphases, it can compute the shared secret by calling one of the
generateSecret
methods:public byte[] generateSecret(); public int generateSecret(byte[] sharedSecret, int offset); public SecretKey generateSecret(String algorithm);KeyManagement
A database called a "keystore" can be used to manage arepository of keys and certificates. (A certificate is adigitally signed statement from one entity, saying that the publickey of some other entity has a particular value.)KeystoreLocation
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 name uName, "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, in JSSE(SSL/TLS), one keystore might hold a user's private keys, andanother might hold certificates used to establish trustrelationships.
- C:\Winnt\Profiles\uName on multi-user Windows NTsystems
- C:\Windows\Profiles\uName on multi-user Windows95/98/2000 systems
- C:\Windows on single-user Windows 95/98/2000systems
In addition to the user's keystore, the Sun 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 the
SunJSSE
provider is presented withcertificates from a remote peer, the default trustmanager willconsult the:<java-home>/lib/ext/cacerts [Unix], or <java-home>\lib\ext\cacerts [Windows]file 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.Keystore Implementation
TheKeyStore
classsupplies well-defined interfaces to access and modify theinformation in a keystore. It is possible for there to be multipledifferent concrete implementations, where each implementation isthat for a particular type of keystore.Currently, there are two command-line tools that make use of
KeyStore
: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 different types of keystoreimplementations from different providers, using the
getInstance
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.There is a built-in default keystore implementation type knownas "
jks
" that is provided by Sun Microsystems. Itimplements the keystore as a file, utilizing a proprietary keystoretype (format). It protects each private key with its own individualpassword, and also protects the integrity of the entire keystorewith a (possibly different) password. The default is specified bythe following line in the security properties file:keystore.type=jksTo have tools and other applications use a different defaultkeystore implementation, you can change that line to specify adefault type. If you have a provider package that supplies akeystore implementation for a keystore type called "jceks", changethe line to:
keystore.type=jceksSome applications, such askeytool
, also let youoverride the default keystore type (via the-storetype
command-line parameter).There are two other types of keystores that come with the Sun JDKimplementation.
NOTE: Keystore type designations are not case-sensitive. Forexample, "jks" would be considered the same as "jks".
- "jceks" is analternate proprietary keystore format to "jks" that uses muchstronger encryption in the form of Password-Based Encryption withTriple-DES.
The Sun "jceks" implementation can parse and convert a "jks"keystore file to the "jceks" format. You may upgrade your keystoreof type "jks" to a keystore of type "jceks" by changing thepassword of a private-key entry in your keystore and specifying
"-storetype jceks"
as the keystore type. To apply thecryptographically strong(er) key protection supplied to a privatekey named "signkey" in your default keystore, use the followingcommand, which will prompt you for the old and new keypasswords:See Security Toolsfor more information aboutkeytool -keypasswd -alias signkey -storetype jcekskeytool
and about keystoresand how they are managed.- "pkcs12" is another option. This is a cross platformkeystore based on the RSA PKCS12 PersonalInformation Exchange Syntax Standard. This standard isprimarily meant for storing or transporting a user's private keys,certificates, and miscellaneous secrets. As of JDK 6, standards forstoring Trusted Certificates in "pkcs12" have not been establishedyet, and thus "jks" or "jceks" should be used for trustedcertificates.
Keystore implementations are provider-based. Developersinterested in writing their own KeyStore implementations shouldconsult How to Implement aProvider for the Java Cryptography Architecture for moreinformation on this topic.
The
KeyStore
ClassTheKeyStore
class is an engine class that supplies well-defined interfaces toaccess and modify the information in a keystore.![]()
This class represents an in-memory collection of keys andcertificates.
KeyStore
manages two types ofentries:Each entry in a keystore is identified by an "alias" string. In thecase of private keys and their associated certificate chains, thesestrings distinguish among the different ways in which the entitymay authenticate itself. For example, the entity may authenticateitself using different certificate authorities, or using differentpublic key algorithms.Key Entry
- Trusted Certificate Entry
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 a trustedcertificate because the keystore owner trusts that the publickey in the certificate indeed belongs to the identity identified bythe subject (owner) of the certificate.
This type of entry can be used to authenticate otherparties.
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 main
KeyStore
methods are described below.Creating a
KeyStore
Object
KeyStore
objects are obtained by using one of theKeyStore
getInstance()
static factorymethods.Loading a Particular Keystore into Memory
Before aKeyStore
object can be used, theactual keystore data must be loaded into memory via theload
method:The optional password is used to check the integrity of thekeystore data. If no password is supplied, no integrity check isperformed.final void load(InputStream stream, char[] password)To create an empty keystore, you pass
null
as theInputStream
argument to theload
method.Getting a List of the Keystore Aliases
All keystore entries are accessed via unique aliases. The
aliases
method returns an enumeration of the aliasnames in the keystore:final Enumeration aliases()Determining Keystore Entry Types
As stated in TheKeyStore
Class, there are two different types ofentries in a keystore.The following methods determine whether the entry specified bythe given alias is a key/certificate or a trusted certificateentry, respectively:
final boolean isKeyEntry(String alias) final boolean isCertificateEntry(String alias)Adding/Setting/Deleting Keystore Entries
ThesetCertificateEntry
method assigns acertificate to a specified alias:Iffinal void setCertificateEntry(String alias, Certificate cert)alias
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
.The
setKeyEntry
methods add (ifalias
doesn't yet exist) or set key entries:In the method withfinal void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain) final void setKeyEntry(String alias, byte[] key, Certificate[] chain)key
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.The
deleteEntry
method deletes an entry:final void deleteEntry(String alias)Getting Information from the Keystore
ThegetKey
method returns the keyassociated with the given alias. The key is recovered using thegiven password:The following methods return the certificate, or certificate chain,respectively, associated with the given alias:final Key getKey(String alias, char[] password)You can determine the name (final Certificate getCertificate(String alias) final Certificate[] getCertificateChain(String alias)alias
) of the first entrywhose certificate matches a given certificate via the following:final String getCertificateAlias(Certificate cert)Saving the KeyStore
The in-memory keystore can be saved via thestore
method:The password is used to calculate an integrity checksum of thekeystore data, which is appended to the keystore data.final void store(OutputStream stream, char[] password)Algorithm ParametersClasses
LikeKey
s andKeyspec
s, analgorithm's initialization parameters are represented by eitherAlgorithmParameter
s orAlgorithmParameterSpec
s. 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.A transparent representation of a set of parameters (via
AlgorithmParameterSpec
) 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, the
AlgorithmParameters
classsupplies an opaque 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
).The
AlgorithmParameterSpec
InterfaceAlgorithmParameterSpec
is an interface toa transparent 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 inthe
java.security.spec
andjavax.crypto.spec
packages are described in the JDKjavadocs:
The following algorithm parameter specs are used specificallyfor digital signatures, as part of JSR 105.
The
AlgorithmParameters
ClassTheAlgorithmParameters
class is an engine class that provides an opaquerepresentation of 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).Creating an
AlgorithmParameters
Object
AlgorithmParameters
objects are obtained by usingone of theAlgorithmParameters
getInstance()
static factorymethods.Initializing an
AlgorithmParameters
ObjectOnce an
AlgorithmParameters
object is instantiated,it must be initialized via a call toinit
, using anappropriate parameter specification or parameter encoding:In thesevoid init(AlgorithmParameterSpec paramSpec) void init(byte[] params) void init(byte[] params, String format)init
methods,params
is an arraycontaining the encoded parameters, andformat
is thename of the decoding format. In theinit
method with aparams
argument but noformat
argument,the primary decoding format for parameters is used. The primarydecoding format is ASN.1, if an ASN.1 specification for theparameters exists.
NOTE:AlgorithmParameters
objects can beinitialized only once. They are not reusable.
Obtaining the Encoded Parameters
A byte encoding of the parameters represented in an
AlgorithmParameters
object may be obtained via a calltogetEncoded
: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.byte[] getEncoded()If you want the parameters returned in a specified encodingformat, use
Ifbyte[] getEncoded(String format)format
is null, the primary encoding format forparameters is used, as in the othergetEncoded
method.
NOTE: In the defaultAlgorithmParameters
implementation, supplied by theSUN
provider, theformat
argument is currently ignored.
Converting an
AlgorithmParameters
Object to aTransparent SpecificationA transparent parameter specification for the algorithmparameters may be obtained from an
AlgorithmParameters
object via a call togetParameterSpec
:AlgorithmParameterSpec getParameterSpec(Class paramSpec)paramSpec
identifies the specification class in whichthe parameters should be returned. The specification class couldbe, for example,DSAParameterSpec.class
to indicatethat the parameters should be returned in an instance of theDSAParameterSpec
class. (This class is in thejava.security.spec
package.)The
AlgorithmParameterGenerator
ClassTheAlgorithmParameterGenerator
class isan engine class used to generate a set of brand-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.Creating an
AlgorithmParameterGenerator
Object
AlgorithmParameterGenerator
objects are obtained byusing one of theAlgorithmParameterGenerator
getInstance()
static factorymethods.Initializing an
AlgorithmParameterGenerator
ObjectThe
AlgorithmParameterGenerator
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. (See the StandardNames document for information about the sizes for specificalgorithms.) When using this approach, algorithm-specific parametergeneration values--if any--default to some standard values. One
init
method that takes these two universally sharedtypes of arguments:Anothervoid init(int size, SecureRandom random);init
method takes only asize
argument 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 an
AlgorithmParameterSpec
object: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.void init(AlgorithmParameterSpec genParamSpec, SecureRandom random) void init(AlgorithmParameterSpec genParamSpec)Generating Algorithm Parameters
Once you have created and initialized anAlgorithmParameterGenerator
object, you can use thegenerateParameters
method to generate the algorithmparameters:AlgorithmParameters generateParameters()The
CertificateFactory
ClassTheCertificateFactory
class is an engine class that defines the functionalityof a certificate 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 of
java.security.cert.X509Certificate
,and CRLs that are an instance ofjava.security.cert.X509CRL
.Creating a
CertificateFactory
Object
CertificateFactory
objects are obtained by usingone of thegetInstance()
static factory methods.Generating Certificate Objects
To generate a certificate object and initialize it withthe data read from an input stream, use thegenerateCertificate
method:To return a (possibly empty) collection view of the certificatesread from a given input stream, use thefinal Certificate generateCertificate(InputStream inStream)generateCertificates
method:final Collection generateCertificates(InputStream inStream)Generating CRL Objects
To generate a certificate revocation list (CRL) objectand initialize it with the data read from an input stream, use thegenerateCRL
method:To return a (possibly empty) collection view of the CRLs read froma given input stream, use thefinal CRL generateCRL(InputStream inStream)generateCRLs
method:final Collection generateCRLs(InputStream inStream)Generating
CertPath
ObjectsThe certificate path builder and validator for PKIX isdefined by the Internet X.509 Public Key Infrastructure Certificateand CRL Profile, 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 as RFC 2587.
To generate a
CertPath
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):To generate afinal CertPath generateCertPath(InputStream inStream) final CertPath generateCertPath(InputStream inStream, String encoding)CertPath
object and initialize it with alist of certificates, use the following method:To retrieve a list of thefinal CertPath generateCertPath(List certificates)CertPath
encodings supportedby this certificate factory, you can call thegetCertPathEncodings
method:The default encoding will be listed first.final Iterator getCertPathEncodings()
With an understanding of the JCA classes, consider howthese classes might be combined to implement an advanced networkprotocol like SSL/TLS. The SSL/TLS Overviewsection in the JSSE ReferenceGuide describes at a high level how the protocols work. 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.
NOTE: The details presented here simply show how some of theabove classes might be employed. This section will not presentsufficient information for building a SSL/TLS implementation. Formore details, please see the JSSE Reference Guide and RFC 2246: The TLSProtocol.
Assume that this SSL/TLS implementation will be made availableas a JSSE provider. A concrete implementation of the
Provider
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 the
SSLContext
. The contexteventually creates end objects (SSLSocket
andSSLEngine
) which actually implement the SSL/TLSprotocol.SSLContext
s 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 JSSE
KeyManager
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.A
KeyStore
'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 JSSE
TrustManager
is responsible for verifyingthe credentials received from a peer. There are many ways to verifycredentials: one of them is to create aCertPath
object, 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.
![]()
In the first example, the server tries to use a RSA-basedciphersuite such as TLS_RSA_WITH_AES_128_CBC_SHA. The server's
KeyManager
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 usinga
KeyPairGenerator
. 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 DHPrivateKey
s.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 symmetric
Cipher
object, 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.
Header Data Digest Padding (if any) Again, this is vastly simplied, but gives one an idea of howthese classes might be combined to create a higher levelprotocol.
Note 1: This section should be ignored by most applicationdevelopers. It is only for people whose applications may beexported to those few countries whose governments mandatecryptographic restrictions, if it is desired that such applicationshave fewer cryptographic restrictions than those mandated. Note2: Throughout this section, the term "application" is meant toencompass both applications and applets.]
The JCA framework includes an ability to enforce restrictionsregarding the cryptographic algorithms and maximum cryptographicstrengths available to applets/applications in differentjurisdiction contexts (locations). Any such restrictions arespecified in "jurisdiction policy files".
Due to import control restrictions by the governments of a fewcountries, the jurisdiction policy files shipped with the Java SEDevelopment Kit 6 from Sun Microsystems specify that "strong" butlimited cryptography may be used. An "unlimited strength" versionof these files indicating no restrictions on cryptographicstrengths is available for those living in eligible countries(which is most countries). But only the "strong" version can beimported into those countries whose governments mandaterestrictions. The JCA framework will enforce the restrictionsspecified in the installed jurisdiction policy files.
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.
In order for an application to be recognized as "exempt" atruntime, it must meet the following conditions:
- It must have a permission policy file bundled with it in a JARfile. The permission policy file specifies whatcryptography-related permissions the application has, and underwhat conditions (if any).
- The JAR file containing the application and the permissionpolicy file must have been signed using a code-signing certificateissued after the application was accepted as exempt.
Below are sample steps required in order to make an applicationexempt from some or all cryptographic restrictions. This is a basicoutline that includes information about what is required by JCA inorder to recognize and treat applications as being exempt. You willneed to know the exemption requirements of the particular countryor countries in which you would like your application to be able tobe run but whose governments require cryptographic restrictions.You will also need to know the requirements of a JCA frameworkvendor that has a process in place for handling exemptapplications. Consult such a vendor for further information. (NOTE:The
SunJCE
provider does not supply an implementationof the ExemptionMechanismSpi class.)
- Step 1: Write and Compile Your Application Code
- Step 2: Create a Permission Policy File Granting AppropriateCryptographic Permissions
- Step 3: Prepare for Testing
- Step 3a: Apply for Government Approval From the GovernmentMandating Restrictions.
- Step 3b: Get a Code-Signing Certificate
- Step 3c: Bundle the Application and Permission Policy File intoa JAR file
- Step 3d: Sign the JARfile
- Step 3e: Set Up Your Environment Like That of a User in aRestricted Country
- Step 3f: (only for apps using exemption mechanisms) Install aProvider Implementing the Exemption Mechanism Specified by theentry in the Permission Policy File
- Step 4: Test Your Application
- Step 5: Apply for U.S. Government Export Approval IfRequired
- Step 6: Deploy Your Application
Special Code Requirements for Applications that Use ExemptionMechanisms
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 the Cipher
getInstance
method is called to instantiate a Cipher,the JCA code searches the installed providers for one thatimplements the specified exemption mechanism. If it finds such aprovider, JCA instantiates an ExemptionMechanism API objectassociated with the provider's implementation, and then associatesthe ExemptionMechanism object with the Cipher returned bygetInstance
.After instantiating a Cipher, and prior to initializing it (viaa call to the Cipher
init
method), your code must callthe following Cipher method:public ExemptionMechanism getExemptionMechanism()This call returns the ExemptionMechanism object associated withthe Cipher. 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 a Cipher
init
method.Once you have initialized the ExemptionMechanism, you canproceed as usual to initialize and use the Cipher.
Permission Policy Files
In order for an application to be recognized at runtime as being"exempt" from some or all cryptographic restrictions, it must 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 an applicationmust 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> ]]]];See Appendix B for more information aboutthe jurisdiction policy file format.
Permission Policy Files for Exempt Applications
Some applications may be allowed to be completely unrestricted.Thus, the permission policy file that accompanies such 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 thangranting CryptoAllPermission. For example, if an application justuses the Blowfish algorithm, the permission policy file doesn'thave to grant CryptoAllPermission 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"; };Permission Policy Files for Applications Exempt Due toExemption Mechanisms
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>";where
<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:
- KeyRecovery
- KeyEscrow
- KeyWeakening
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 mechanismsshould not also specify maximum key sizes. The allowed keysizes are actually determined from the installed exemptjurisdiction policy files, as described in the next section.
How Bundled Permission Policy Files Affect CryptographicPermissions
At runtime, when an application instantiates a Cipher (via acall to its
getInstance
method) and that applicationhas an associated permission policy file, JCA checks to see whetherthe permission policy file has an entry that applies to thealgorithm specified in thegetInstance
call. If itdoes, and the entry grants CryptoAllPermission 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 the
getInstance
call and theentry does 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 ofseveral of the JCA mechanisms. In addition, complete workingexamples can be found in Appendix D.Computing a
MessageDigest
ObjectFirst create the message digestobject, as in the following example:
This call assigns a properly initialized message digest object totheMessageDigest sha = MessageDigest.getInstance("SHA-1");sha
variable. The implementation implements theSecure Hash Algorithm (SHA-1), as defined in the National Institutefor Standards and Technology's (NIST) FIPS 180-2document. See Appendix 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:
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 tosha.update(i1); sha.update(i2); byte[] hash = sha.digest(i3);update
calls) is lost.Some hash implementations may support intermediate hashesthrough cloning. Suppose we want to calculate separate hashesfor:
i1
i1 and i2
i1, i2, and i3
A way to do it is:
This code works only if the SHA-1 implementation is cloneable.While some implementations of message digests are cloneable, othersare not. To determine whether or not cloning is possible, attemptto clone the/* 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();MessageDigest
object and catch thepotential exception as follows: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: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 }MessageDigest
sha1 = MessageDigest.getInstance("SHA-1");MessageDigest
sha12 = MessageDigest.getInstance("SHA-1");MessageDigest
sha123 = MessageDigest.getInstance("SHA-1"); byte[] i1Hash = sha1.digest(i1); sha12.update(i1); byte[] i12Hash = sha12.digest(i2); sha123.update(i1); sha123.update(i2); byte[] i123Hash = sha123.digest(i3);Generating a Pair of Keys
In this example we will generate a public-private key pair forthe algorithm named "DSA" (Digital Signature Algorithm), and usethis keypair in future examples. We will generate keys with a1024-bit modulus. We don't care which provider supplies thealgorithm implementation.
Creating the Key PairGenerator
The first step is to get a key pair generator object forgenerating keys for the DSA algorithm:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");Initializing the Key Pair Generator
The next step is to initialize the key pair generator.In most cases, algorithm-independent initialization is sufficient,but in some cases, algorithm-specific initialization is used.Algorithm-Independent Initialization
All key pair generators share the concepts of a keysize and asource of randomness. The
KeyPairGenerator
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 1024, simply call:The following code illustrates how to use a specific, additionallyseededSecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random);SecureRandom
object:Since no other parameters are specified when you call the abovealgorithm-independentSecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.setSeed(userSeed); keyGen.initialize(1024, random);initialize
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.Algorithm-Specific Initialization
For situations where a set of algorithm-specific parametersalready exists (such as "community parameters" in DSA), there aretwo
initialize
methods that have anAlgorithmParameterSpec
argument. 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); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.setSeed(userSeed); keyGen.initialize(dsaSpec, random);
NOTE: The parameter namedp
is a prime numberwhose length is the modulus length ("size"). Therefore, you don'tneed to call any other method to specify the modulus length.
Generating the Pair of Keys
The final step is actually generating the key pair. Nomatter which type of initialization was used (algorithm-independentor algorithm-specific), the same code is used to generate the key pair:KeyPair pair = keyGen.generateKeyPair();Generating and Verifying a SignatureUsing Generated Keys
The following signature generation and verification examples usethe
KeyPair
generated in the key pairexample above.Generating a Signature
We first create a signature object:
Next, using the key pair generated in the key pair example, weinitialize the object with the private key, then sign a byte arraycalledSignature dsa = Signature.getInstance("SHA1withDSA");data
./* Initializing the object with a private key */ PrivateKey priv = pair.getPrivate(); dsa.initSign(priv); /* Update and sign the data */ dsa.update(data); byte[] sig = dsa.sign();Verifying a Signature
Verifying the signature is straightforward. (Note thathere we also use the key pair generated in the key pair example.)/* Initializing the object with the public key */ PublicKey pub = pair.getPublic(); dsa.initVerify(pub); /* Update and verify the data */ dsa.update(data); boolean verifies = dsa.verify(sig); System.out.println("signature verifies: " + verifies);Generating/VerifyingSignatures Using Key Specifications and
KeyFactory
Suppose that, rather than having a public/private keypair (as, for example, was generated in the keypair example 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 named
someData
. 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
):Suppose Alice wants to use the data you signed. In order for her todo so, and to verify your signature, you need to send her threethings:DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(x, p, q, g); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec); Signature sig = Signature.getInstance("SHA1withDSA"); sig.initSign(privKey); sig.update(someData); byte[] signature = sig.sign();You can store the
- the data,
- the signature, and
- the public key corresponding to the private key you used tosign the data.
someData
bytes in one file, and thesignature
bytes in another, and send those to Alice.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 a
DSAPublicKeySpec
from those components:You still need to extract the key bytes so that you can put them ina file. To do so, you can first call theDSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(y, p, q, g);generatePublic
method on the DSA key factory alreadycreated in the example above:Then you can extract the (encoded) key bytes via the following:PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);You can now store these bytes in a file, and send it to Alice alongwith the files containing the data and the signature.byte[] encKey = pubKey.getEncoded();Now, assume Alice has received these files, and she copied thedata bytes from the data file to a byte array named
data
, 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("SHA1withDSA"); 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 theKeyFactory
getKeySpec
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 theDSAPublicKeySpec
class (getY
,getP
,getQ
, andgetG
).Determining If Two Keys Are Equal
In many cases you would like to know if two keys are equal;however, the default method
java.lang.Object.equals
may not give the desired result. The most provider-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; }Reading Base64-EncodedCertificates
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 theFileInputStream
(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()); }Parsing a CertificateReply
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); }UsingEncryption
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).
Generating a Key
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.
Creating a Cipher
The next step is to create a Cipher instance. To do this, we useone of the
getInstance
factory methods of the Cipherclass. We must specify the name of the requested transformation,which includes the following components, separated by slashes(/):
- the algorithm name
- the mode (optional)
- the padding scheme (optional)
In this example, we create an AES cipher in Electronic Codebookmode, with PKCS5-style padding. We do not specify a provider,because we do not care about a particular implementation of therequested transformation.
The standard algorithm name for AES is "AES", the standard namefor the Electronic Codebook mode is "ECB", and the standard namefor PKCS5-style padding is "PKCS5Padding":
Cipher aesCipher; // Create the cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");We use the generated
aesKey
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.Using Password-BasedEncryption
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 type
java.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, the
javax.crypto.spec.PBEKeySpec
class takes (and returns) a password as a char array. See theReadPassword class in the sample codein Appendix 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 a salt and an iterationcount. The same salt and iteration count that are used forencryption must be used for decryption:
PBEKeySpec pbeKeySpec; PBEParameterSpec pbeParamSpec; SecretKeyFactory keyFac; // Salt byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 }; // Iteration count int count = 20; // Create PBE parameter set pbeParamSpec = new PBEParameterSpec(salt, count); // Prompt user for encryption password. // Collect user password as char array (using the // "readPassword" method from above), and convert // it into a SecretKey object, using a PBE key // factory. System.out.print("Enter encryption password: "); System.out.flush(); pbeKeySpec = new PBEKeySpec(readPassword(System.in)); keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); // Create PBE Cipher Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); // Initialize PBE Cipher with key and parameters pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); // Our cleartext byte[] cleartext = "This is another example".getBytes(); // Encrypt the cleartext byte[] ciphertext = pbeCipher.doFinal(cleartext);Using KeyAgreement
Please refer to Appendix 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 in theStandard Names document. Thisdocument also contains more information about the algorithmspecifications. Specific provider information can be found in theSun Provider Documentation.
Cryptographic implementations in the Sun JDK are distributedthrough several different providers primarily for historicalreasons (
Sun
,SunJSSE
,SunJCE
,SunRsaSign
). Note these providersmay not be available on all JDK implementations, and therefore,truly portable applications should callgetInstance()
without specifying specific providers. Applications specifying aparticular provider may not be able to take advantage of nativeproviders tuned for an underlying operating environment (such asPKCS or Microsoft's CAPI).The
SunPKCS11
provider itself does not contain anycryptographic algorithms, but instead, directs requests into anunderlying PKCS11 implementation. The PKCS11 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 describedin Default 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 word
permission
. 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:CryptoPermission
andCryptoAllPermission
. 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 (see Appendix A)of a cryptography algorithm, such as "DES" 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 as
javax.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."
Due to import control restrictions, the jurisdiction policyfiles shipped with the Java SE Development Kit 6 allow "strong" butlimited cryptography to be used. Here are the maximum key sizesallowed by this "strong" version of the jurisdiction policyfiles:
Algorithm Maximum Keysize DES 64 DESede * RC2 128 RC4 128 RC5 128 RSA * all others 128
-
Diffie-Hellman Key Exchange between2 Parties
/* /* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import java.security.interfaces.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import com.sun.crypto.provider.SunJCE; /** * This program executes the Diffie-Hellman key agreement protocol * between 2 parties: Alice and Bob. * * By default, preconfigured parameters (1024-bit prime modulus and base * generator used by SKIP) are used. * If this program is called with the "-gen" option, a new set of * parameters is created. */ public class DHKeyAgreement2 { private DHKeyAgreement2() {} public static void main(String argv[]) { try { String mode = "USE_SKIP_DH_PARAMS"; DHKeyAgreement2 keyAgree = new DHKeyAgreement2(); if (argv.length > 1) { keyAgree.usage(); throw new Exception("Wrong number of command options"); } else if (argv.length == 1) { if (!(argv[0].equals("-gen"))) { keyAgree.usage(); throw new Exception("Unrecognized flag: " + argv[0]); } mode = "GENERATE_DH_PARAMS"; } keyAgree.run(mode); } catch (Exception e) { System.err.println("Error: " + e); System.exit(1); } } private void run(String mode) throws Exception { DHParameterSpec dhSkipParamSpec; if (mode.equals("GENERATE_DH_PARAMS")) { // Some central authority creates new DH parameters System.out.println ("Creating Diffie-Hellman parameters (takes VERY long) ..."); AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH"); paramGen.init(512); AlgorithmParameters params = paramGen.generateParameters(); dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec (DHParameterSpec.class); } else { // use some pre-generated, default DH parameters System.out.println("Using SKIP Diffie-Hellman parameters"); dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base); } /* * Alice creates her own DH key pair, using the DH parameters from * above */ System.out.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(dhSkipParamSpec); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // Alice creates and initializes her DH KeyAgreement object System.out.println("ALICE: Initialization ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Alice encodes her public key, and sends it over to Bob. byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded(); /* * Let's turn over to Bob. Bob has received Alice's public key * in encoded format. * He instantiates a DH public key from the encoded key material. */ KeyFactory bobKeyFac = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec (alicePubKeyEnc); PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec); /* * Bob gets the DH parameters associated with Alice's public key. * He must use the same parameters when he generates his own key * pair. */ DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams(); // Bob creates his own DH key pair System.out.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Bob creates and initializes his DH KeyAgreement object System.out.println("BOB: Initialization ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Bob encodes his public key, and sends it over to Alice. byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded(); /* * Alice uses Bob's public key for the first (and only) phase * of her version of the DH * protocol. * Before she can do so, she has to instantiate a DH public key * from Bob's encoded key material. */ KeyFactory aliceKeyFac = KeyFactory.getInstance("DH"); x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc); PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec); System.out.println("ALICE: Execute PHASE1 ..."); aliceKeyAgree.doPhase(bobPubKey, true); /* * Bob uses Alice's public key for the first (and only) phase * of his version of the DH * protocol. */ System.out.println("BOB: Execute PHASE1 ..."); bobKeyAgree.doPhase(alicePubKey, true); /* * At this stage, both Alice and Bob have completed the DH key * agreement protocol. * Both generate the (same) shared secret. */ byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); int aliceLen = aliceSharedSecret.length; byte[] bobSharedSecret = new byte[aliceLen]; int bobLen; try { // show example of what happens if you // provide an output buffer that is too short bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1); } catch (ShortBufferException e) { System.out.println(e.getMessage()); } // provide output buffer of required size bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) throw new Exception("Shared secrets differ"); System.out.println("Shared secrets are the same"); /* * Now let's return the shared secret as a SecretKey object * and use it for encryption. First, we generate SecretKeys for the * "DES" algorithm (based on the raw shared secret data) and * then we use DES in ECB mode * as the encryption algorithm. DES in ECB mode does not require any * parameters. * * Then we use DES in CBC mode, which requires an initialization * vector (IV) parameter. In CBC mode, you need to initialize the * Cipher object with an IV, which can be supplied using the * javax.crypto.spec.IvParameterSpec class. Note that you have to use * the same IV for encryption and decryption: If you use a different * IV for decryption than you used for encryption, decryption will * fail. * * NOTE: If you do not specify an IV when you initialize the * Cipher object for encryption, the underlying implementation * will generate a random one, which you have to retrieve using the * javax.crypto.Cipher.getParameters() method, which returns an * instance of java.security.AlgorithmParameters. You need to transfer * the contents of that object (e.g., in encoded format, obtained via * the AlgorithmParameters.getEncoded() method) to the party who will * do the decryption. When initializing the Cipher for decryption, * the (reinstantiated) AlgorithmParameters object must be passed to * the Cipher.init() method. */ System.out.println("Return shared secret as SecretKey object ..."); // Bob // NOTE: The call to bobKeyAgree.generateSecret above reset the key // agreement object, so we call doPhase again prior to another // generateSecret call bobKeyAgree.doPhase(alicePubKey, true); SecretKey bobDesKey = bobKeyAgree.generateSecret("DES"); // Alice // NOTE: The call to aliceKeyAgree.generateSecret above reset the key // agreement object, so we call doPhase again prior to another // generateSecret call aliceKeyAgree.doPhase(bobPubKey, true); SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES"); /* * Bob encrypts, using DES in ECB mode */ Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey); byte[] cleartext = "This is just an example".getBytes(); byte[] ciphertext = bobCipher.doFinal(cleartext); /* * Alice decrypts, using DES in ECB mode */ Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey); byte[] recovered = aliceCipher.doFinal(ciphertext); if (!java.util.Arrays.equals(cleartext, recovered)) throw new Exception("DES in CBC mode recovered text is " + "different from cleartext"); System.out.println("DES in ECB mode recovered text is " + "same as cleartext"); /* * Bob encrypts, using DES in CBC mode */ bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey); cleartext = "This is just an example".getBytes(); ciphertext = bobCipher.doFinal(cleartext); // Retrieve the parameter that was used, and transfer it to Alice in // encoded format byte[] encodedParams = bobCipher.getParameters().getEncoded(); /* * Alice decrypts, using DES in CBC mode */ // Instantiate AlgorithmParameters object from parameter encoding // obtained from Bob AlgorithmParameters params = AlgorithmParameters.getInstance("DES"); params.init(encodedParams); aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params); recovered = aliceCipher.doFinal(ciphertext); if (!java.util.Arrays.equals(cleartext, recovered)) throw new Exception("DES in CBC mode recovered text is " + "different from cleartext"); System.out.println("DES in CBC mode recovered text is " + "same as cleartext"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } /* * Prints the usage of this test. */ private void usage() { System.err.print("DHKeyAgreement usage: "); System.err.println("[-gen]"); } // The 1024 bit Diffie-Hellman modulus values used by SKIP private static final byte skip1024ModulusBytes[] = { (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58, (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD, (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4, (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B, (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D, (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C, (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C, (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6, (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0, (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B, (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB, (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D, (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD, (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43, (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C, (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C, (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C, (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40, (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C, (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72, (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03, (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29, (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C, (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB, (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B, (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08, (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D, (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C, (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22, (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB, (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55, (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7 }; // The SKIP 1024 bit modulus private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes); // The base used with the SKIP 1024 bit modulus private static final BigInteger skip1024Base = BigInteger.valueOf(2); }
-
-
Diffie-Hellman Key Exchange between3 Parties
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import java.security.interfaces.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import com.sun.crypto.provider.SunJCE; /** * This program executes the Diffie-Hellman key agreement protocol * between 3 parties: Alice, Bob, and Carol. * * We use the same 1024-bit prime modulus and base generator that are * used by SKIP. */ public class DHKeyAgreement3 { private DHKeyAgreement3() {} public static void main(String argv[]) { try { DHKeyAgreement3 keyAgree = new DHKeyAgreement3(); keyAgree.run(); } catch (Exception e) { System.err.println("Error: " + e); System.exit(1); } } private void run() throws Exception { DHParameterSpec dhSkipParamSpec; System.out.println("Using SKIP Diffie-Hellman parameters"); dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base); // Alice creates her own DH key pair System.out.println("ALICE: Generate DH keypair ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(dhSkipParamSpec); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // Bob creates his own DH key pair System.out.println("BOB: Generate DH keypair ..."); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhSkipParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Carol creates her own DH key pair System.out.println("CAROL: Generate DH keypair ..."); KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH"); carolKpairGen.initialize(dhSkipParamSpec); KeyPair carolKpair = carolKpairGen.generateKeyPair(); // Alice initialize System.out.println("ALICE: Initialize ..."); KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); aliceKeyAgree.init(aliceKpair.getPrivate()); // Bob initialize System.out.println("BOB: Initialize ..."); KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); bobKeyAgree.init(bobKpair.getPrivate()); // Carol initialize System.out.println("CAROL: Initialize ..."); KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH"); carolKeyAgree.init(carolKpair.getPrivate()); // Alice uses Carol's public key Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false); // Bob uses Alice's public key Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); // Carol uses Bob's public key Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false); // Alice uses Carol's result from above aliceKeyAgree.doPhase(cb, true); // Bob uses Alice's result from above bobKeyAgree.doPhase(ac, true); // Carol uses Bob's result from above carolKeyAgree.doPhase(ba, true); // Alice, Bob and Carol compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); System.out.println("Carol secret: " + toHexString(carolSharedSecret)); // Compare Alice and Bob if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) throw new Exception("Alice and Bob differ"); System.out.println("Alice and Bob are the same"); // Compare Bob and Carol if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret)) throw new Exception("Bob and Carol differ"); System.out.println("Bob and Carol are the same"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } /* * Prints the usage of this test. */ private void usage() { System.err.print("DHKeyAgreement usage: "); System.err.println("[-gen]"); } // The 1024 bit Diffie-Hellman modulus values used by SKIP private static final byte skip1024ModulusBytes[] = { (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58, (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD, (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4, (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B, (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D, (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C, (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C, (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6, (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0, (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B, (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB, (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D, (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD, (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43, (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C, (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C, (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C, (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40, (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C, (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72, (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03, (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29, (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C, (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB, (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B, (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08, (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D, (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C, (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22, (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB, (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55, (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7 }; // The SKIP 1024 bit modulus private static final BigInteger skip1024Modulus = new BigInteger(1, skip1024ModulusBytes); // The base used with the SKIP 1024 bit modulus private static final BigInteger skip1024Base = BigInteger.valueOf(2); }
-
-
Blowfish CipherExample
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; /** * This program generates a Blowfish key, retrieves its raw bytes, and * then reinstantiates a Blowfish key from the key bytes. * The reinstantiated key is used to initialize a Blowfish cipher for * encryption. */ public class BlowfishKey { public static void main(String[] args) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("Blowfish"); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal("This is just an example".getBytes()); } }
-
-
HMAC-MD5 Example
/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.security.*; import javax.crypto.*; /** * This program demonstrates how to generate a secret-key object for * HMAC-MD5, and initialize an HMAC-MD5 object with it. */ public class initMac { public static void main(String[] args) throws Exception { // Generate secret key for HMAC-MD5 KeyGenerator kg = KeyGenerator.getInstance("HmacMD5"); SecretKey sk = kg.generateKey(); // Get instance of Mac object implementing HMAC-MD5, and // initialize it with the above secret key Mac mac = Mac.getInstance("HmacMD5"); mac.init(sk); byte[] result = mac.doFinal("Hi There".getBytes()); } }
-
-
Reading ASCIIPasswords From an InputStream Example
//* * 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.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 Sun's 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, * or null if an end of stream has been reached. * * @throws IOException * if an I/O problem occurs */ public static final char[] readPassword(InputStream in) throws IOException { /* * If available, directly use the java.io.Console class to * avoid character echoing. */ if (in == System.in && System.console() != null) { // readPassword returns "" if you just print ENTER, return System.console().readPassword(); } /* * If a console is not available, read the InputStream * directly. This approach may cause password echoing. * * Since different operating systems have different End-Of-Line * (EOL) sequences, this algorithm should allow for * platform-independent implementations. Typical EOL sequences * are a single line feed ('\n'), or a carriage return/linefeed * combination ('\r\n'). However, some OS's use a single * a carriage return ('\r'), which complicates portability. * * Since we may not have the ability to push bytes back into the * InputStream, another approach is used here. The javadoc for *
java.lang.System.getProperties()
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, ' '); } } } }