Professional Documents
Culture Documents
The S c e K y a t r Class erteFcoy The K y a r e e a o Class ePiGnrtr The K y e e a o Class eGnrtr The K y g e m n Class eAreet Key Management
Keystore Location Keystore Implementation The K y t r Class eSoe Algorithm Parameters Classes
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 1/63
5/24/12
The A g r t m a a e e S e Interface loihPrmtrpc The A g r t m a a e e s l o i h P r m t r Class The C r i i a e a t r Class etfctFcoy How the JCA Might Be Used in a SSL/TLS Implementation
The A g r t m a a e e G n r t r l o i h P r m t r e e a o Class
How to Make Applications "Exempt" from Cryptographic Restrictions Code Examples Computing a M s a e i e t e s g D g s Object Generating a Pair of Keys Generating and Verifying a Signature Using Generated Keys Generating/Verifying Signatures Using K y e Specifications and K y a t r eFcoy Determining If Two Keys Are Equal Reading Base64-Encoded Certificates Parsing a Certificate Reply Using Encryption Using Password-Based Encryption Using Key Agreement Appendix A: Standard Names Appendix B: Jurisdiction Policy File Format Appendix C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files Appendix D: Sample Programs Diffie-Hellman Key Exchange between 2 Parties Diffie-Hellman Key Exchange between 3 Parties Blowfish Cipher Example HMAC-MD5 Example Reading ASCII Passwords From an InputStream Example
Introduction
The Java platform strongly emphasizes security, including language safety, cryptography, public key infrastructure, authentication, secure communication, and access control. The JCA is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashs), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few. These APIs allow developers to easily integrate security into their application code. The architecture was designed around the following principles: 1. Implementation independence Applications do not need to implement security algorithms. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality. 2. Implementation interoperability Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application. 3. Algorithm extensibility The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services. Other cryptographic communication libraries available in the JDK use the JCA provider architecture, but are described elsewhere. The JavaTM Secure Socket Extension (JSSE) provides access to Secure Socket Layer (SSL) and Transport Layer Security (TLS) implementations. The Java Generic Security Services (JGSS) (via Kerberos) APIs, and the Simple Authentication and Security Layer (SASL) can also be used for securely exchanging messages between communicating applications.
Notes on Terminology
Prior to JDK 1.4, the JCE was an unbundled product, and as such, the JCA and JCE were regularly referred to as separate,
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 2/63
5/24/12
distinct components. As JCE is now bundled in the JDK, the distinction is becoming less apparent. Since the JCE uses the same architecture as the JCA, the JCE should be more properly thought of as a part of the JCA. The JCA within the JDK includes two software components: the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as j v . e u i yj v x c y t , aascrt, aa.rpo j v x c y t . p cand j v x c y t . n e f c s aa.rpose, aa.rpoitrae. the actual providers such as S nS n s S g , S n C , which contain the actual cryptographic u, uRain uJE implementations. Whenever a specific JCA provider is mentioned, it will be referred to explicitly by the provider's name. WARNING: The JCA makes it easy to incorporate security features into your application. However, this document does not cover the theory of security/cryptography beyond an elementary introduction to concepts necessary to discuss the APIs. This document also does not cover the strengths/weaknesses of specific algorithms, not does it cover protocol design. Cryptography is an advanced topic and one should consult a solid, preferably recent, reference in order to make best use of these tools. You should always understand what you are doing and why: DO NOT simply copy random code and expect it to fully solve your usage scenario. Many applications have been deployed that contain significant security or performance problems because the wrong tool or algorithm was selected.
Design Principles
The JCA was designed around these principles: implementation independence and interoperability algorithm independence and extensibility Implementation independence and algorithm independence are complementary; you can use cryptographic services, such as digital signatures and message digests, without worrying about the implementation details or even the algorithms that form the basis for these concepts. While complete algorithm-independence is not possible, the JCA provides standardized, algorithm-specific APIs. When implementation-independence is not desirable, the JCA lets developers indicate a specific implementation. Algorithm independence is achieved by defining types of cryptographic "engines" (services), and defining classes that provide the functionality of these cryptographic engines. These classes are called engine classes, and examples are the M s a e i e t esgDgs, S g a u eK y a t r , K y a r e e a o , and C p e classes. intr, eFcoy ePiGnrtr ihr Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Provider (CSP) (used interchangeably with "provider" in this document) refers to a package or set of packages that implement one or more cryptographic services, such as digital signature algorithms, message digest algorithms, and key conversion services. A program may simply request a particular type of object (such as a S g a u e i n t r object) implementing a particular service (such as the DSA signature algorithm) and get an implementation from one of the installed providers. If desired, a program may instead request an implementation from a specific provider. Providers may be updated transparently to the application, for example when faster or more secure versions are available. Implementation interoperability means that various implementations can work with each other, use each other's keys, or verify each other's signatures. This would mean, for example, that for the same algorithms, a key generated by one provider would be usable by another, and a signature generated by one provider would be verifiable by another. Algorithm extensibility means that new algorithms that fit in one of the supported engine classes can be added easily.
Architecture
Cryptographic Service Providers
j v . e u i y P o i e is the base class for all security providers. Each CSP contains an instance of this class aascrt.rvdr
which contains the provider's name and lists all of the security services/algorithms it implements. When an instance of a particular algorithm is needed, the JCA framework consults the provider's database, and if a suitable match is found, the instance is created. Providers contain a package (or a set of packages) that supply concrete implementations for the advertised cryptographic algorithms. Each JDK installation has one or more providers installed and configured by default. Additional providers may be added statically or dynamically (see the Provider and Security classes). Clients may configure their runtime environment to specify the provider preference order. The preference order is the order in which providers are searched for requested services when no specific provider is requested. To use the JCA, an application simply requests a particular type of object (such as a M s a e i e t and a particular esgDgs) algorithm or service (such as the "M D5" algorithm), and gets an implementation from one of the installed providers. Alternatively, the program can request the objects from a specific provider. Each provider has a name used to refer to it.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
3/63
5/24/12
m =Msaeietgtntne"D"; d esgDgs.eIsac(M5) m =Msaeietgtntne"D" "rvdr"; d esgDgs.eIsac(M5, PoieC) The following figure illustrates requesting an "M D5" message digest implementation. The figure show three different providers that implement various message digest algorithms ("SHA-1", "M D5", "SHA-256", and "SHA-512"). The providers are ordered by preference from left to right (1-3). In the first illustration, an application requests an M D5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In the second figure, the application requests the M D5 algorithm implementation from a specific provider, ProviderC. This time the implementation from ProviderC is returned, even though a provider with a higher preference order, ProviderB, also supplies an M D5 implementation.
Cryptographic implementations in the Sun JDK are distributed via several different providers (S nS n S ES n C , u, uJS, uJE S n s S g ) primarily for historical reasons, but to a lesser extent by the type of functionality and algorithms they provide. uRain Other Java runtime environments may not necessarily contain these Sun providers, so applications should not request an providerspecific implementation unless it is known that a particular provider will be available. The JCA offers a set of APIs that allow users to query which providers are installed and what services they support. This architecture also makes it easy for end-users to add additional providers. M any third party provider implementations are already available. See The P o i e Class for more information on how providers are written, installed, and registered. rvdr
5/24/12
engine object. Each instance of the engine class encapsulates (as a private field) the instance of the corresponding SPI class, known as the SPI object. All API methods of an API object are declared final and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. To make this clearer, review the following code and illustration: ipr jvxcyt.; mot aa.rpo* Cpe c=Cpe.eIsac(AS) ihr ihrgtntne"E"; cii(NRP_OE ky; .ntECYTMD, e)
Here an application wants an "AES" j v x c y t . i h r a a . r p o C p e instance, and doesn't care which provider is used. The application calls the g t n t n e ) e I s a c ( factory methods of the C p e engine class, which in turn asks the JCA ihr framework to find the first provider instance that supports "AES". The framework consults each installed provider, and obtains the provider's instance of the P o i e class. (Recall that the P o i e class is a database of available algorithms.) The rvdr rvdr framework searches each provider, finally finding a suitable entry in CSP3. This database entry points to the implementation class c m f o A S i h rwhich extends C p e S iand is thus suitable for use by the C p e engine class. An o.o.ECpe ihrp, ihr instance of c m f o A S i h r created, and is encapsulated in a newly-created instance of o . o . E C p e is
j v x c y t . i h rwhich is returned to the application. When the application now does the i i ( aa.rpoCpe, nt) operation on the C p e instance, the C p e engine class routes the request into the corresponding e g n I i ( ihr ihr nient) backing method in the c m f o A S i h r o . o . E C p e class.
Appendix A lists the Standard Names defined for the Java environment. Other third-party providers may define their own implementations of these services, or even additional services.
Key Management
A database called a "keystore" can be used to manage a repository of keys and certificates. Keystores are available to applications that need data for authentication, encryption, or signing purposes. Applications can access a keystore via an implementation of the K y t r class, which is in the j v . e u i y eSoe aascrt package. A default K y t r implementation is provided by Sun M icrosystems. It implements the keystore as a file, using a eSoe proprietary keystore type (format) named "jks". Other keystore formats are available, such as "jceks" which is an alternate proprietary keystore format with much stronger encryption than "jks", and "pkcs12", which is based on the RSA PKCS12 Personal Information Exchange Syntax Standard. Applications can choose different keystore implementations from different providers, using the same provider mechanism described above. See the Key M anagement section for more information.
JCA Concepts
This section introduces the major JCA APIs.
5/24/12
An engine class provides the interface to a specific type of cryptographic service, independent of a particular cryptographic algorithm or provider. The engines either provide: cryptographic operations (encryption, digital signatures, message digests, etc.), generators or converters of cryptographic material (keys and algorithm parameters), or objects (keystores or certificates) that encapsulate the cryptographic data and can be used at higher layers of abstraction. The following engine classes are available:
S c r R n o : used to generate random or pseudo-random numbers. eueadm M s a e i e tused to calculate the message digest (hash) of specified data. esgDgs: S g a u einitilialized with keys, these are used to sign data and verify digital signatures. intr: C p e : initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric ihr
bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA), stream encryption (e.g. RC4), asymmetric encryption (e.g. RSA), and password-based encryption (PBE). M essage Authentication Codes (M AC): like M s a e i e t these also generate hash values, but are first initialized e s g D g s s, with keys to protect the integrity of messages.
K y a t r : used to convert existing opaque cryptographic keys of type K yinto key specifications (transparent eFcoy e
representations of the underlying key material), and vice versa. S c e K y a t r : used to convert existing opaque cryptographic keys of type S c e K yinto key erteFcoy erte specifications (transparent representations of the underlying key material), and vice versa. S c e K y a t r s are erteFcoy specialized K y a t r s that create secret (symmetric) keys only. eFcoy
K y a r e e a o : used to generate a new pair of public and private keys suitable for use with a specified ePiGnrtr
algorithm.
K y e e a o : used to generate new secret keys for use with a specified algorithm. eGnrtr K y g e m n : used by two or more parties to agree upon and establish a specific key to use for a particular eAreet
cryptographic operation.
A g r t m a a e e sused to store the parameters for a particular algorithm, including parameter encoding and loihPrmtr:
decoding.
K y t r : used to create and manage a keystore. A keystore is a database of keys. Private keys in a keystore have a eSoe
certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.
C r i i a e a t r : used to create public key certificates and Certificate Revocation Lists (CRLs). etfctFcoy C r P t B i d rused to build certificate chains (also known as certification paths). etahule: C r P t V l d t rused to validate certificate chains. etahaiao: C r S o eused to retrieve C r i i a e and C L from a repository. ettr: etfcts Rs
NOTE: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).
the S c r R n o , M s a e i e tS g a u eC p e , M cK y a t r , eueadm esgDgs, intr, ihr a, eFcoy S c e K y a t r ,K y a r e e a o ,K y e e a o ,K y g e m n , erteFcoy ePiGnrtr eGnrtr eAreet
A g r t m a a e e sA g r t m a a e e G n r t r, K y t r , and loihPrmtr, loihPrmtreeao eSoe C r i i a e a t r , engine classes, etfctFcoy the K y e interfaces and classes,
the Algorithm Parameter Specification Interfaces and Classes and the Key Specification Interfaces and Classes, and miscellaneous support and convenience interfaces and classes.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
6/63
5/24/12
NOTE: For more information on the C r P t B i d rC r P t V l d t rand C r S o e etahule, etahaiao, e t t r engine classes, please see the Java(TM ) PKI Programmer's Guide. The guide will cover the most useful high-level classes first (P o i e , S c r t , S c r R n o , rvdr euiy eueadm
M s a e i e tS g a u eC p e , and M c then delve into the various support classes. For now, it is sufficient esgDgs, intr, ihr a ),
to simply say that Keys (public, private, and secret) are generated and represented by the various JCA classes, and are used by the high-level classes as part of their operation. This section shows the signatures of the main methods in each class and interface. Examples for some of these classes (M s a e i e t esgDgs, corresponding Examples sections. The complete reference documentation for the relevant Security API packages can be found in the package summaries:
S g a u eK y a r e e a o , S c r R n o , K y a t r , and key specification classes) are supplied in the intr, ePiGnrtr eueadm eFcoy
The term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) refers to a package or set of packages that supply a concrete implementation of a subset of the JDK Security API cryptography features. The P o i e rvdr class is the interface to such a package or set of packages. It has methods for accessing the provider name, version number, and other information. Please note that in addition to registering implementations of cryptographic services, the P o i e class can also be rvdr used to register implementations of other security services that might get defined as part of the JDK Security API or one of its extensions. To supply implementations of cryptographic services, an entity (e.g., a development group) writes the implementation code and creates a subclass of the P o i e class. The constructor of the P o i e subclass sets the values of various properties; rvdr rvdr the JDK Security API uses these values to look up the services that the provider implements. In other words, the subclass specifies the names of the classes implementing the services.
There are several types of services that can be implemented by provider packages; for more information, see Engine Classes and Algorithms. The different implementations may have different characteristics. Some may be software-based, while others may be hardware-based. Some may be platform-independent, while others may be platform-specific. Some provider source code may be available for review and evaluation, while some may not. The JCA lets both end-users and developers decide what their needs are. In this section we explain how end-users install the cryptography implementations that fit their needs, and how developers request the implementations that fit theirs. NOTE: For information about implementing a provider, see the guide How To Implement a Provider for the Java Cryptography Architecture.
5/24/12
of the g t n t n e e I s a c methods on the engine class, specifying the name of the desired algorithm
and, optionally, the name of the provider (or the P o i e class) whose implementation is desired. rvdr sai EgnCasaegtntneSrn agrtm ttc nielsNm eIsac(tig loih) trw NScAgrtmxeto hos ouhloihEcpin sai EgnCasaegtntneSrn agrtm Srn poie) ttc nielsNm eIsac(tig loih, tig rvdr trw NScAgrtmxeto,NScPoieEcpin hos ouhloihEcpin ouhrvdrxeto sai EgnCasaegtntneSrn agrtm Poie poie) ttc nielsNm eIsac(tig loih, rvdr rvdr trw NScAgrtmxeto hos ouhloihEcpin where EngineClassName is the desired engine type (MessageDigest/Cipher/etc). For example: Msaeietm =Msaeietgtntne"D"; esgDgs d esgDgs.eIsac(M5) Kygemn k =Kygemn.eIsac(D" "uJE) eAreet a eAreetgtntne"H, SnC"; return an instance of the "MD5" MessageDigest and "DH" KeyAgreement objects, respectively. Appendix A contains the list of names that have been standardized for use with the Java environment. Some providers may choose to also include alias names that also refer to the same algorithm. For example, the "SHA-1" algorithm might be referred to as "SHA1". Applications should use standard names instead of an alias, as not all providers may alias algorithm names in the same way. NOTE: The algorithm name is not case-sensitive. For example, all the following calls are equivalent: Msaeietgtntne"H-" esgDgs.eIsac(SA1) Msaeietgtntne"h-" esgDgs.eIsac(sa1) Msaeietgtntne"H-" esgDgs.eIsac(sa1) If no provider is specified, g t n t n e e I s a c searches the registered providers for an implementation of the requested cryptographic service associated with the named algorithm. In any given Java Virtual M achine (JVM ), providers are installed in a given preference order, the order in which the provider list is searched if a specific provider is not requested. For example, suppose there are two providers installed in a JVM , P O I E _ and RVDR1
P O I E _ implements SHA1withDSA, SHA-1, M D5, DES, and DES3. RVDR1 P O I E _ has preference order 1 (the highest priority). RVDR1 P O I E _ implements SHA1withDSA, M D5withRSA, M D2withRSA, M D2, M D5, RC4, RC5, RVDR2
DES, and RSA.
P O I E _ implementation is returned since P O I E _ has the highest priority and is RVDR1 RVDR1
searched first. 2. If we are looking for an M D5withRSA signature algorithm, P O I E _ is first searched for it. No RVDR1 implementation is found, so P O I E _ is searched. Since an implementation is found, it is returned. RVDR2 3. Suppose we are looking for a SHA1withRSA signature algorithm. Since no installed provider implements it, a N S c A g r t m x e t o is thrown. ouhloihEcpin The g t n t n e e I s a c methods that include a provider argument are for developers who want to specify which provider they want an algorithm from. A federal agency, for example, will want to use a provider implementation that has received federal certification. Let's assume that the SHA1withDSA implementation from P O I E _ has RVDR1 not received such certification, while the DSA implementation of P O I E _ has received it. RVDR2 A federal agency program would then have the following call, specifying P O I E _ since it has the certified RVDR2 implementation: Sgaueda=Sgauegtntne"H1ihS" "RVDR2) intr s intr.eIsac(SAwtDA, POIE_"; In this case, if P O I E _ was not installed, a N S c P o i e E c p i n RVDR2 o u h r v d r x e t o would be thrown, even if another installed provider implements the algorithm requested. A program also has the option of getting a list of all the installed providers (using the g t r v d r method ePoies in the S c r t class) and choosing one from the list. euiy
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 8/63
5/24/12
NOTE: General purpose applications SHOULD NOT request cryptographic services from specific providers. Otherwise, applications are tied to specific providers which may not be available on other Java implementations. They also might not be able to take advantage of available optimized providers (for example hardware accelerators via PKCS11 or native OS implementations such as Microsoft's MSCAPI) that have a higher preference order than the specific requested provider.
Installing Providers
In order to be used, a cryptographic provider must first be installed, then registered either statically or dynamically. There are a variety of Sun providers shipped with this release (S NS n C , S n S E U, uJE uJS, S n s S g , etc.) that are already installed and registered. The following sections describe how to install and uRain register additional providers.
Here < a a h m >refers to the directory where the runtime software is installed, which is the top-level jv-oe directory of the JavaTM Runtime Environment (JRE) or the j edirectory in the JavaTM JDK software. For r example, if you have JDK 6 installed on Solaris in a directory named / o e u e 1 J K . . , hm/sr/D160 or on M icrosoft Windows in a directory named C \ a a J K . . , then you need to install the :Jv\D160 JAR file in the following directory: /oeue1JK../r/i/x hm/sr/D160jelbet C\D160jelbet :JK..\r\i\x [nx Ui] [idw] Wnos
Similarly, if you have the JRE 6 installed on Solaris in a directory named / o e u e 1 j e . . , or on M icrosoft Windows in a directory named hm/sr/r160
C \ r 1 6 0you need to install the JAR file in the following directory: :je..,
/oeue1je../i/x hm/sr/r160lbet C\r160lbet :je..\i\x
For more information on how to deploy an extension, see How is an extension deployed?
Static Registration
The configuration file is located in the following location: <aahm>lbscrt/aascrt jv-oe/i/euiyjv.euiy <aahm>lbscrt\aascrt jv-oe\i\euiyjv.euiy [nx Ui] [idw] Wnos
For each registered provider, this file should have a statement of the following form: scrt.rvdrnmseCasae euiypoie.=atrlsNm This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms (when no specific provider is requested). The order is 1-based: 1 is the most preferred, followed by 2, and so on.
m s e C a s a emust specify the fully qualified name of provider's master class. The provider's atrlsNm documentation will specify its master class. This class is always a subclass of the P o i e class. The subclass rvdr
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 9/63
5/24/12
constructor sets the values of various properties that are required for the Java Cryptography API to look up the algorithms or other facilities the provider implements. The JDK comes standard with automatically installed and configured providers such as "SUN" and "SunJCE". The "SUN" provider's master class is the S N U class in the s n s c r t . r v d rpackage, and the u.euiypoie corresponding java.security file entry is as follows: scrt.rvdr5snscrt.rvdrSn euiypoie.=u.euiypoie.u To utilize another JCA provider, add a line referencing the alternate provider, specify the preference order ( making corresponding adjustments to the other providers' orders, if needed). Suppose that the master class of CompanyX's provider is
c m c m a y . r v d r P o i e Xand that you would like to configure this provider as o.opnxpoie.rvdr, the eighth most-preferred. To do so, you would add the following line to the j v . e u i y a a s c r t file:
scrt.rvdr8cmcmay.rvdrPoieX euiypoie.=o.opnxpoie.rvdr
Dynamic Registration
To register providers dynamically, applications call either the a d r v d r d P o i e or
jv.euiyScrtPriso "uPoiePoet. aascrt.euiyemsin ptrvdrrpry { a e "to set provider properties, where { a e is replaced by the actual provider name. nm} nm}
For example, a sample statement granting permissions to a provider whose name is "M yJCE" and whose code is in m j e p o i e . a appears below. Such a statement could appear in a policy file. In this example, yc_rvdrjr the m j e p o i e . a file is assumed to be in the / o a W r directory. yc_rvdrjr lclok
gatcdBs "ie/oaWr/yc_rvdrjr { rn oeae fl:lclokmjepoie.a" priso jv.agRnieemsin"ePoetoDmi" emsin aaln.utmPriso gtrtcinoan; priso jv.euiyScrtPriso emsin aascrt.euiyemsin "uPoiePoet.yC" ptrvdrrpryMJE; } ;
5/24/12
a local application not running under a security manager, or an applet or application with permission to execute the specified method (see below). The determination that code is considered trusted to perform an attempted action (such as adding a provider) requires that the applet is granted the proper permission(s) for that particular action. The policy configuration file(s) for a JDK installation specify what permissions (which types of system resource accesses) are allowed by code from specified code sources. (See below and the "Default Policy Implementation and Policy File Syntax" and "Java Security Architecture Specification" files for more information.) Code being executed is always considered to come from a particular "code source". The code source includes not only the location (URL) where the code originated from, but also a reference to any public key(s) corresponding to the private key(s) that may have been used to sign the code. Public keys in a code source are referenced by (symbolic) alias names from the user's keystore. In a policy configuration file, a code source is represented by two components: a code base (URL), and an alias name (preceded by
s g e B ), where the alias name identifies the keystore entry containing the public key that must be used to verify the code's indy
signature. Each "grant" statement in such a file grants a specified code source a set of permissions, specifying which actions are allowed. Here is a sample policy configuration file: gatcdBs "ie/oessdi/,sgeB "yamn { rn oeae fl:hm/yamn" indy ssdi" priso jv.euiyScrtPriso "netrvdr*; emsin aascrt.euiyemsin isrPoie." priso jv.euiyScrtPriso "eoervdr*; emsin aascrt.euiyemsin rmvPoie." priso jv.euiyScrtPriso "uPoiePoet." emsin aascrt.euiyemsin ptrvdrrpry*; } ; This configuration file specifies that code loaded from a signed JAR file from beneath the / o e s s d i / hm/yamn directory on the local file system can add or remove providers or set provider properties. (Note that the signature of the JAR file can be verified using the public key referenced by the alias name s s d i in the user's keystore.) yamn Either component of the code source (or both) may be missing. Here's an example of a configuration file where the c d B s is oeae omitted: gatsgeB "yamn { rn indy ssdi" priso jv.euiyScrtPriso "netrvdr*; emsin aascrt.euiyemsin isrPoie." priso jv.euiyScrtPriso "eoervdr*; emsin aascrt.euiyemsin rmvPoie." } ; If this policy is in effect, code that comes in a JAR File signed by s s d i can add/remove providers--regardless yamn of where the JAR File originated. Here's an example without a signer: gatcdBs "ie/oessdi/ { rn oeae fl:hm/yamn" priso jv.euiyScrtPriso "netrvdr*; emsin aascrt.euiyemsin isrPoie." priso jv.euiyScrtPriso "eoervdr*; emsin aascrt.euiyemsin rmvPoie." } ; In this case, code that comes from anywhere within the / o e s s d i / h m / y a m n directory on the local filesystem can add/remove providers. The code does not need to be signed. An example where neither c d B s nor s g e B is included is: oeae indy gat{ rn priso jv.euiyScrtPriso "netrvdr*; emsin aascrt.euiyemsin isrPoie." priso jv.euiyScrtPriso "eoervdr*; emsin aascrt.euiyemsin rmvPoie." } ; Here, with both code source components missing, any code (regardless of where it originates, or whether or not it is signed, or who signed it) can add/remove providers. Obviously, this is definitely NOT recommended, as this grant could open a security hole. Untrusted code could install a Provider, thus affecting later code that is depending on a properly functioning implementation. (For example, a rogue C p e object might capture and store the sensitive information ihr it receives.)
Managing Providers
The following tables summarize the methods in the S c r t class you can use to query which euiy
Description Returns an array containing all the installed providers (technically, the
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
11/63
5/24/12
sai Poie[ ttc rvdr] P o i e subclass for each package provider). The order of the rvdr gtrvdr( ePoies) P o i e s in the array is their preference order. rvdr s a i P o i e g t r v d r Returns the P o i e named p o i e N m . It returns n l ttc rvdr ePoie rvdr rvdrae ul (tigpoieNm) Srn rvdrae if the P o i e is not found. rvdr
Method Adding Providers Adds a P o i e to the end of the list of installed P o i e s. rvdr rvdr sai it ttc n It returns the preference position in which the P o i e was rvdr a d r v d r P o i e p o i e )added, or - if the P o i e was not added because it was dPoie(rvdr rvdr 1 rvdr already installed. Adds a new P o i e at a specified position. If the given provider is rvdr installed at the requested position, the provider formerly at that position and all providers with a position greater than p s t o are shifted up one oiin position (towards the end of the list). This method returns the preference position in which the P o i e was added, or - if the P o i e rvdr 1 rvdr was not added because it was already installed. Description Removes the P o i e with the specified name. It returns silently if rvdr the provider is not installed. When the specified provider is removed, all providers located at a position greater than where the specified provider was are shifted down one position (towards the head of the list of installed providers). Description
NOTE: If you want to change the preference position of a provider, you must first remove it, and then insert it back in at the new preference position.
Security Properties
The S c r t class maintains a list of system-wide security properties. These properties are similar to the euiy S s e properties, but are security-related. These properties can be set statically or dynamically. We have ytm already seen an example of static security properties (that is, registering a provider statically via the
" e u i y p o i e . "security property). If you want to set properties dynamically, trusted scrt.rvdri
programs can use the following methods: sai Srn gtrprySrn ky ttc tig ePoet(tig e) sai vi strprySrn ky Srn dtm ttc od ePoet(tig e, tig au) Note: the list of security providers is established during VM startup, therefore the methods described above must be used to alter the provider list. As a reminder, the configuration file is located in the following location: <aahm>lbscrt/aascrt jv-oe/i/euiyjv.euiy <aahm>lbscrt\aascrt jv-oe\i\euiyjv.euiy [nx Ui] [idw] Wnos
S c r R n o Object eueadm
12/63
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
5/24/12
The S c r R n o implementation attempts to completely randomize the internal state of the generator eueadm itself unless the caller follows the call to a g t n t n e e I s a c method with a call to one of the s t e d eSe methods: snhoie pbi vi stedbt[ se) ycrnzd ulc od eSe(ye] ed pbi vi stedln se) ulc od eSe(og ed Once the S c r R n o object has been seeded, it will produce bits as random as the original eueadm seeds. At any time a S c r R n o object may be re-seeded using one of the s t e d eueadm e S e methods. The given seed supplements, rather than replaces, the existing seed; therefore, repeated calls are guaranteed never to reduce randomness.
The M s a e i e t e s g D g s Class
The M s a e i e t e s g D g s class is an engine class designed to provide the functionality of cryptographically secure message digests such as SHA-1 or M D5. A cryptographically secure message digest takes arbitrary-sized input (a byte array), and generates a fixed-size output, called a digest or hash.
For example, the M D5 algorithm produces a 16 byte digest, and SHA1's is 20 bytes. A digest has two properties: It should be computationally infeasible to find two messages that hash to the same value. The digest should not reveal anything about the input that was used to generate it. M essage digests are used to produce unique and reliable identifiers of data. They are sometimes called "checksums" or the "digital fingerprints" of the data. Changes to just one bit of the message should produce a different digest value. M essage digests have many uses and can determine when data has been modified, intentionally or not. Recently, there has been considerable effort to determine if there are any weaknesses in popular algorithms, with mixed results. When selecting a digest algorithm, one should always consult a recent reference to determine its status and appropriateness for the task at hand.
Creating a M s a e i e t e s g D g s Object
The first step for computing a digest is to create a message digest instance. M s a e i e t e s g D g s objects are obtained by using one of the g t n t n e ) e I s a c ( static factory methods in the M s a e i e tclass. esgDgs The factory method returns an initialized message digest object. It thus does not need further initialization.
5/24/12
d g s methods: iet
bt[ dgs( ye] iet) bt[ dgs(ye]ipt ye] ietbt[ nu) itdgs(ye]bf itofe,itln n ietbt[ u, n fst n e) The first method return the computed digest. The second method does a final u d t ( n u ) p a e i p t with the
input byte array before calling d g s ( , which returns the digest byte array. The last method stores the iet) computed digest in the provided buffer b fstarting at o f e . l n the number of bytes in b f u, f s t e is u allotted for the digest, the method returns the number of bytes actually stored in b fIf there is not enough room in the u. buffer, the method will throw an exception. Please see the Computing a M s a e i e t e s g D g s example in the Code Examples section for more details.
The S g a u e i n t r Class
The S g a u e i n t r class is an engine class designed to provide the functionality of a cryptographic digital signature algorithm such as DSA or RSAwithMD5. A cryptographically secure signature algorithm takes arbitrary-sized input and a private key and generates a relatively short (often fixed-size) string of bytes, called the signature, with the following properties: Only the owner of a private/public key pair is able to create a signature. It should be computationally infeasible for anyone having a public key to recover the private key. Given the public key corresponding to the private key used to generate the signature, it should be possible to verify the authenticity and integrity of the input. The signature and the public key do not reveal anything about the private key. It can also be used to verify whether or not an alleged signature is in fact the authentic signature of the data associated
with it. ASgaue i n t r object is initialized for signing with a Private Key and is given the data to be signed. The resulting signature bytes are typically kept with the signed data. When verification is needed, another S g a u e i n t r object is created and initialized for verification and given the corresponding Public Key. The data and the signature bytes are fed to the signature object, and if the data and signature match, the S g a u e i n t r object reports success. Even though a signature seems similar to a message digest, they have very different purposes in the type of protection they provide. In fact, algorithms such as "SHA1WithRSA" use the message digest "SHA1" to initially "compress" the large data sets into a more manageable form, then sign the resulting 20 byte message digest with the "RSA" algorithm. Please see the Examples section for an example of signing and verifying data.
Creating a S g a u e i n t r Object
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 14/63
5/24/12
The first step for signing or verifying a signature is to create a S g a u e i n t r instance. S g a u e intr objects are obtained by using one of the S g a u e e I s a c ( static factory methods. intr gtntne)
Initializing a S g a u e i n t r Object
ASgaue i n t r object must be initialized before it is used. The initialization method depends on whether the object is going to be used for signing or for verification. If it is going to be used for signing, the object must first be initialized with the private key of the entity whose signature is going to be generated. This initialization is done by calling the method: fnlvi iiSg(rvtKypiaee) ia od ntinPiaee rvtKy This method puts the S g a u e i n t r object in the S G state. IN If instead the S g a u e i n t r object is going to be used for verification, it must first be initialized with the public key of the entity whose signature is going to be verified. This initialization is done by calling either of these methods: fnlvi iiVrf(ulce pbiKy ia od nteiyPbiKy ulce) fnlvi iiVrf(etfct criiae ia od nteiyCriiae etfct) This method puts the S g a u e i n t r object in the V R F state. EIY
Signing
If the S g a u e i n t r object has been initialized for signing (if it is in the S G state), the data to be signed can IN then be supplied to the object. This is done by making one or more calls to one of the u d t methods: pae fnlvi udt(yeb ia od paebt ) fnlvi udt(ye]dt) ia od paebt[ aa fnlvi udt(ye]dt,itof itln ia od paebt[ aa n f, n e) Calls to the u d t method(s) should be made until all the data to be signed has been supplied to the pae
S g a u eobject. intr
To generate the signature, simply call one of the s g methods: in fnlbt[ sg( ia ye] in) fnlitsg(ye]otu,itofe,itln ia n inbt[ ubf n fst n e) The first method returns the signature result in a byte array. The second stores the signature result in the provided buffer outbuf, starting at offset. len is the number of bytes in outbuf allotted for the signature. The method returns the number of bytes actually stored. Signature encoding is algorithm specific. See the Standard Names document for more information about the use of ASN.1 encoding in the Java Cryptography Architecture. A call to a s g method resets the signature object to the state it was in when previously initialized for signing via a in call to i i S g . That is, the object is reset and available to generate another signature with the same private ntin key, if desired, via new calls to u d t and s g . pae in
Alternatively, a new call can be made to i i S g specifying a different private key, or to i i V r f ntin nteiy (to initialize the S g a u e i n t r object to verify a signature).
Verifying
If the S g a u e i n t r object has been initialized for verification (if it is in the V R F state), it can then verify EIY if an alleged signature is in fact the authentic signature of the data associated with it. To start the process, the data to be verified (as opposed to the signature itself) is supplied to the object. The data is passed to the object by calling one of the u d t methods: pae fnlvi udt(yeb ia od paebt ) fnlvi udt(ye]dt) ia od paebt[ aa fnlvi udt(ye]dt,itof itln ia od paebt[ aa n f, n e) Calls to the u d t method(s) should be made until all the data to be verified has been supplied to the pae S g a u eobject. The signature can now be verified by calling one of the v r f methods: intr eiy
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 15/63
5/24/12
fnlboenvrf(ye]sgaue ia ola eiybt[ intr) fnlboenvrf(ye]sgaue itofe,itlnt) ia ola eiybt[ intr, n fst n egh The argument must be a byte array containing the signature. The argument must be a byte array containing the signature. This byte array would hold the signature bytes which were returned by a previous call to one of the s g in methods. The v r f method returns a b o e n eiy o l a indicating whether or not the encoded signature is the authentic signature of the data supplied to the u d t method(s). pae A call to the v r f method resets the signature object to its state when it was initialized for verification via a call eiy to i i V r f . That is, the object is reset and available to verify another signature from the identity whose nteiy public key was specified in the call to i i V r f . nteiy Alternatively, a new call can be made to i i V r f specifying a different public key (to initialize the nteiy S g a u eobject for verifying a signature from a different entity), or to i i S g (to initialize the intr ntin
The C p e class provides the functionality of a cryptographic cipher used for encryption and decryption. Encryption is the ihr process of taking data (called cleartext) and a key, and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a key and producing cleartext.
Modes Of Operation
When encrypting using a simple block cipher, two identical blocks of plaintext will always produce an identical block of cipher text. Cryptanalysts trying to break the ciphertext will have an easier job if they note blocks of repeating text. In order to add more complexity to the text, feedback modes use the previous block of output to alter the input blocks before applying the encryption algorithm. The first block will need an initial value, and this value is called the initialization vector (IV). Since the IV simply alters the data before any encryption, the IV should be random but does not necessarily need to be kept secret. There are a variety of modes, such as CBC (Cipher Block Chaining), CFB (Cipher Feedback Mode), and OFB (Output Feedback Mode). ECB (Electronic Cookbook Mode) is a mode with no feedback.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 16/63
5/24/12
Some algorithms such as AES and RSA allow for keys of different lengths, but others are fixed, such as DES and 3DES. Encryption using a longer key generally implies a stronger resistance to message recovery. As usual, there is a trade off between security and time, so choose the key length appropriately. M ost algorithms use binary keys. M ost humans do not have the ability to remember long sequences of binary numbers, even when represented in hexadecimal. Character passwords are much easier to recall. Because character passwords are generally chosen from a small number of characters (for example, [a-zA-Z0-9]), protocols such as "Password-Based Encryption" (PBE) have been defined which take character passwords and generate strong binary keys. In order to make the task of getting from password to key very timeconsuming for an attacker (via so-called "dictionary attacks" where common dictionary word->value mappings are precomputed), most PBE implementations will mix in a random number, known as a salt, to increase the key randomness.
C p e objects are obtained by using one of the C p e g t n t n e )static factory ihr ihr eIsac(
methods. Here, the algorithm name is slightly different than with other engine classes, in that it specifies not just an algorithm name, but a "transformation". A transformation is a string that describes the operation (or set of operations) to be performed on the given input to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., D S and may be followed E ), by a mode and padding scheme. A transformation is of the form: "algorithm/mode/padding" or "algorithm" For example, the following are valid transformations: "E/B/KSPdig DSCCPC5adn" "E" DS If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, returns there is a preferred one. If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not. If no mode or padding is specified, provider-specific default values for the mode and padding scheme are used. For example, the S n C provider uses E B the default mode, and P C 5 a d n as the default uJE C as KSPdig padding scheme for D SD S E E B o f s ciphers. This means that in the case of the E , E - D and l w i h S n C provider: uJE Cpe c =Cpe.eIsac(DSEBPC5adn"; ihr 1 ihrgtntne"E/C/KSPdig) and Cpe c =Cpe.eIsac(DS) ihr 1 ihrgtntne"E"; are equivalent statements. Using modes such as CFB and OFB, block ciphers can encrypt data in units smaller than the cipher's actual block size. When requesting such a mode, you may optionally specify the number of bits to be processed at a time by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the S n C uJE provider uses a default of 64 bits for DES.) Thus, block ciphers can be turned into byte-oriented stream ciphers by using an 8 bit mode such as CFB8 or OFB8. Appendix A of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation. The objects returned by factory methods are uninitialized, and must be initialized before they become usable.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
17/63
5/24/12
ENCRYPT_MODE Encryption of data. DECRYPT_MODE Decryption of data. WRAP_MODE Wrapping a j v . e u i y K y a a s c r t . e into bytes so that the key can be securely transported. UNWRAP_MODE Unwrapping of a previously wrapped key into a j v . e u i y K y aascrt.e object. Each of the Cipher initialization methods takes an operational mode parameter (o m d ), and initializes the poe Cipher object for that mode. Other parameters include the key (k y or certificate containing the key e) (c r i i a e algorithm parameters (p r m ), and a source of randomness (r n o ). e t f c t ), aas adm To initialize a Cipher object, call one of the following i i methods: nt pbi vi ii(n omd,Kyky; ulc od ntit poe e e) pbi vi ii(n omd,Criiaecriiae; ulc od ntit poe etfct etfct) pbi vi ii(n omd,Kyky ScrRno rno) ulc od ntit poe e e, eueadm adm; pbi vi ii(n omd,Criiaecriiae ulc od ntit poe etfct etfct, ScrRno rno) eueadm adm; pbi vi ii(n omd,Kyky ulc od ntit poe e e, AgrtmaaeeSe prm) loihPrmtrpc aas; pbi vi ii(n omd,Kyky ulc od ntit poe e e, AgrtmaaeeSe prm,ScrRno rno) loihPrmtrpc aas eueadm adm; pbi vi ii(n omd,Kyky ulc od ntit poe e e, Agrtmaaeesprm) loihPrmtr aas; pbi vi ii(n omd,Kyky ulc od ntit poe e e, Agrtmaaeesprm,ScrRno rno) loihPrmtr aas eueadm adm; If a Cipher object that requires parameters (e.g., an initialization vector) is initialized for encryption, and no parameters are supplied to the i i method, the underlying cipher implementation is supposed to supply the required nt parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters. However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the i i method, an I v l d e E c p i n nt n a i K y x e t o or I v l d l o i h P r m t r x e t o exception will be raised, depending on the naiAgrtmaaeeEcpin
See the section about M anaging Algorithm Parameters for more details. The same parameters that were used for encryption must be used for decryption. Note that when a Cipher object is initialized, it loses all previously-acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state acquired while in decryption mode.
5/24/12
pbi itdFnlbt[ ipt itiptfst ulc n oia(ye] nu, n nuOfe, itipte,bt[ otu) n nuLn ye] upt; pbi itdFnlbt[ ipt itiptfst ulc n oia(ye] nu, n nuOfe, itipte,bt[ otu,itotuOfe) n nuLn ye] upt n uptfst To encrypt or decrypt data in multiple steps, call one of the u d t methods: pae pbi bt[ udt(ye]ipt; ulc ye] paebt[ nu) pbi bt[ udt(ye]ipt itiptfst itipte) ulc ye] paebt[ nu, n nuOfe, n nuLn; pbi itudt(ye]ipt itiptfst itipte, ulc n paebt[ nu, n nuOfe, n nuLn bt[ otu) ye] upt; pbi itudt(ye]ipt itiptfst itipte, ulc n paebt[ nu, n nuOfe, n nuLn bt[ otu,itotuOfe) ye] upt n uptfst A multiple-part operation must be terminated by one of the above d F n l o i a methods (if there is still some input data left for the last step), or by one of the following d F n l o i a methods (if there is no input data left for the last step): pbi bt[ dFnl) ulc ye] oia(; pbi itdFnlbt[ otu,itotuOfe) ulc n oia(ye] upt n uptfst; All the d F n l o i a methods take care of any necessary padding (or unpadding), if padding (or unpadding) has been requested as part of the specified transformation. A call to d F n l o i a resets the Cipher object to the state it was in when initialized via a call to i i . That is, the nt Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call to i i ) more data. nt
1. the name of the key algorithm, and 2. the type of the wrapped key (one of C p e . E R T K YC p e . R V T _ E , ihrSCE_E, ihrPIAEKY or C p e . U L C K Y i h r P B I _ E ). The key algorithm name can be determined by calling the g t l o i h method from the Key interface: eAgrtm pbi Srn gtloih(; ulc tig eAgrtm) To unwrap the bytes returned by a previous call to w a , first initialize a Cipher object for UNWRAP_M ODE, rp then call the following: pbi fnlKyuwa(ye]wapde, ulc ia e nrpbt[ rpeKy Srn wapdeAgrtm tig rpeKyloih, itwapdeTp); n rpeKyye) Here, w a p d e is the bytes returned from the previous call to wrap, rpeKy w a p d e A g r t mis the algorithm associated with the wrapped key, and rpeKyloih w a p d e T p is the type of the wrapped key. This must be one of C p e . E R T K Y rpeKyye ihrSCE_E,
C p e . R V T _ E , or C p e . U L C K Y ihrPIAEKY ihrPBI_E.
Managing Algorithm Parameters
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
19/63
5/24/12
The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the i i method by the application or generated by the underlying implementation itself, can be retrieved from the nt Cipher object by calling its g t a a e e s e P r m t r method, which returns the parameters as a j v . e u i y A g r t m a a e e sobject (or n l if no parameters are being aascrt.loihPrmtr ul used). If the parameter is an initialization vector (IV), it can also be retrieved by calling the g t V e I method.
In the following example, a Cipher object implementing password-based encryption (PBE) is initialized with just a key and no parameters. However, the selected algorithm for password-based encryption requires two parameters - a salt and an iteration count. Those will be generated by the underlying algorithm implementation itself. The application can retrieve the generated parameters from the Cipher object as follows: ipr jvxcyt.; mot aa.rpo* ipr jv.euiyAgrtmaaees mot aascrt.loihPrmtr; / gtcpe ojc frpswr-ae ecyto / e ihr bet o asodbsd nrpin Cpe c=Cpe.eIsac(PEihDAdE"; ihr ihrgtntne"BWtM5nDS) / iiilz cpe frecyto,wtotsplig / ntaie ihr o nrpin ihu upyn / ayprmtr.Hr,"ye"i asmdt rfr / n aaees ee mKy s sue o ee / t a araygnrtdky / o n led-eeae e. cii(ihrECYTMD,mKy; .ntCpe.NRP_OE ye) / ecytsm dt adsoeaa cpetx / nrp oe aa n tr wy ihret / frltrdcyto / o ae erpin bt[ cpeTx =cdFnl"hsi js a eape.eBts); ye] ihret .oia(Ti s ut n xml"gtye() / rtiv prmtr gnrtdb udryn cpe / eree aaees eeae y nelig ihr / ipeetto / mlmnain Agrtmaaeesagaas=cgtaaees) loihPrmtr lPrm .ePrmtr(; / gtprmtrecdn adsoei aa / e aaee noig n tr t wy bt[ ecddlPrm =agaasgtnoe(; ye] noeAgaas lPrm.eEcdd) The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption, as follows: ipr jvxcyt.; mot aa.rpo* ipr jv.euiyAgrtmaaees mot aascrt.loihPrmtr; / gtprmtrojc frpswr-ae ecyto / e aaee bet o asodbsd nrpin Agrtmaaeesagaas loihPrmtr lPrm; agaas=Agrtmaaeesgtntne"BWtM5nDS) lPrm loihPrmtr.eIsac(PEihDAdE"; / iiilz wt prmtrecdn fo aoe / ntaie ih aaee noig rm bv agaasii(noeAgaas; lPrm.ntecddlPrm) / gtcpe ojc frpswr-ae ecyto / e ihr bet o asodbsd nrpin Cpe c=Cpe.eIsac(PEihDAdE"; ihr ihrgtntne"BWtM5nDS) / iiilz cpe frdcyto,uigoeo te / ntaie ihr o erpin sn n f h / ii( mtosta tksa Agrtmaaees / nt) ehd ht ae n loihPrmtr / ojc,adps i teagaasojc fo aoe / bet n as t h lPrm bet rm bv cii(ihrDCYTMD,mKy agaas; .ntCpe.ERP_OE ye, lPrm) If you did not specify any parameters when you initialized a Cipher object, and you are not sure whether or not the underlying implementation uses any parameters, you can find out by simply calling the g t a a e e s ePrmtr method of your Cipher object and checking the value returned. A return value of n l indicates that no parameters ul were used. The following cipher algorithms implemented by the S n C provider use parameters: uJE DES, DES-EDE, and Blowfish, when used in feedback (i.e., CBC, CFB, OFB, or PCBC) mode, use an initialization vector (IV). The j v x c y t . p c I P r m t r p c a a . r p o s e . v a a e e S e class can be used to initialize a Cipher object with a given IV. PBEWithM D5AndDES uses a set of parameters, comprising a salt and an iteration count. The
5/24/12
(encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).
s i ( o g method skips only data that has been processed by the Cipher. kpln)
It is crucial for a programmer using this class not to use methods that are not defined or overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherInputStream. As an example of its usage, suppose c p e 1 been initialized for i h r has encryption. The code below demonstrates how to use a CipherInputStream containing that cipher and a FileInputStream in order to encrypt input stream data: FlIpttemfs ienuSra i; FlOtuSra fs ieupttem o; CpeIpttemcs ihrnuSra i; fs=nwFlIpttem"tpatt) i e ienuSra(/m/.x"; cs=nwCpeIpttemfs cpe1; i e ihrnuSra(i, ihr) fs=nwFlOtuSra(/m/.x"; o e ieupttem"tpbtt) bt[ b=nwbt[] ye] e ye8; iti=csra() n i.edb; wie( ! -){ hl i = 1 fswieb 0 i; o.rt(, , ) i=csra() i.edb; } fscoe) o.ls(; The above program reads and encrypts the content from the file / m / . x tpatt
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 21/63
5/24/12
and then stores the result (the encrypted bytes) in / m / . x . tpbtt The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that c p e 1 ihr and c p e 2 i h r have been initialized for encryption and decryption (with corresponding keys), respectively. FlIpttemfs ienuSra i; FlOtuSra fs ieupttem o; CpeIpttemcs,cs; ihrnuSra i1 i2 fs=nwFlIpttem"tpatt) i e ienuSra(/m/.x"; cs =nwCpeIpttemfs cpe1; i1 e ihrnuSra(i, ihr) cs =nwCpeIpttemcs,cpe2; i2 e ihrnuSra(i1 ihr) fs=nwFlOtuSra(/m/.x"; o e ieupttem"tpbtt) bt[ b=nwbt[] ye] e ye8; iti=cs.edb; n i2ra() wie( ! -){ hl i = 1 fswieb 0 i; o.rt(, , ) i=cs.edb; i2ra() } fscoe) o.ls(; The above program copies the content from file / m / . x to tpatt / m / . x , except that the content is first encrypted and then decrypted tpbtt back when it is read from / m / . x . Of course since this program simply tpatt encrypts text and decrypts it back right away, it's actually not very useful except as a simple way of illustrating chaining of CipherInputStreams. Note that the read methods of the C p e I p t t e m i h r n u S r a will block until data is returned from the underlying cipher. If a block cipher is used, a full block of cipher text will have to be obtained from the underlying InputStream.
5/24/12
CpeOtuSra cs ihrupttem o; fs=nwFlIpttem"tpatt) i e ienuSra(/m/.x"; fs=nwFlOtuSra(/m/.x"; o e ieupttem"tpbtt) cs=nwCpeOtuSra(o,cpe1; o e ihrupttemfs ihr) bt[ b=nwbt[] ye] e ye8; iti=fsra() n i.edb; wie( ! -){ hl i = 1 cswieb 0 i; o.rt(, , ) i=fsra() i.edb; } csfuh) o.ls(; The above program reads the content from the file / m / . x , then tpatt
encrypts and stores the result (the encrypted bytes) in / m / . x . tpbtt The following example demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that c p e 1and c p e 2have been initialized for decryption and encryption ihr ihr (with corresponding keys), respectively: FlIpttemfs ienuSra i; FlOtuSra fs ieupttem o; CpeOtuSra cs,cs; ihrupttem o1 o2 fs=nwFlIpttem"tpatt) i e ienuSra(/m/.x"; fs=nwFlOtuSra(/m/.x"; o e ieupttem"tpbtt) cs =nwCpeOtuSra(o,cpe1; o1 e ihrupttemfs ihr) cs =nwCpeOtuSra(o1 cpe2; o2 e ihrupttemcs, ihr) bt[ b=nwbt[] ye] e ye8; iti=fsra() n i.edb; wie( ! -){ hl i = 1 cs.rt(,0 i; o2wieb , ) i=fsra() i.edb; } cs.ls(; o2fuh) The above program copies the content from file / m / . x to tpatt / m / . x , except that the content is first encrypted and then decrypted tpbtt back before it is written to / m / . x . tpbtt One thing to keep in mind when using block cipher algorithms is that a full block of plaintext data must be given to the C p e O t u S r a before the ihrupttem data will be encrypted and sent to the underlying output stream. There is one other important difference between the f u h c o e l s and l s methods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
23/63
5/24/12
A typical usage is illustrated in the following code segment: In order to seal an object, you create a S a e O j c from the object to be sealed and a fully initialized C p e object that will encrypt the eldbet ihr serialized object contents. In this example, the String "This is a secret" is sealed using the DES algorithm. Note that any algorithm parameters that may be used in the sealing operation are stored inside of S a e O j c : eldbet / cet Cpe ojc / rae ihr bet / NT:se i asmdt rfrt a araygnrtd / OE Ky s sue o ee o n led-eeae / sce DSky / ert E e. Cpe c=Cpe.eIsac(DS) ihr ihrgtntne"E"; cii(ihrECYTMD,se) .ntCpe.NRP_OE Ky; / d tesaig / o h eln SaeOjc s =nwSaeOjc(Ti i asce" c; eldbet o e eldbet"hs s ert, ) The original object that was sealed can be recovered in two different ways: by using a C p e object that has been initialized with the exact same algorithm, key, padding scheme, etc., ihr that were used to seal the object: cii(ihrDCYTMD,se) .ntCpe.ERP_OE Ky; ty{ r Srn s=(tigs.eOjc() tig Srn)ogtbetc; }cth(xeto e { ac Ecpin ) / d smtig / o oehn } ; This approach has the advantage that the party who unseals the sealed object does not require knowledge of the decryption key. For example, after one party has initialized the cipher object with the required decryption key, it could hand over the cipher object to another party who then unseals the sealed object. by using the appropriate decryption key (since DES is a symmetric encryption algorithm, we use the same key for sealing and unsealing): ty{ r Srn s=(tigs.eOjc(Ky; tig Srn)ogtbetse) }cth(xeto e { ac Ecpin ) / d smtig / o oehn } ; In this approach, the g t b e t e O j c method creates a cipher object for the appropriate decryption algorithm and initializes it with the given decryption key and the algorithm parameters (if any) that were stored in the sealed object. This approach has the advantage that the party who unseals the object does not need to keep track of the parameters (e.g., the IV) that were used to seal the object.
A M AC mechanism that is based on cryptographic hash functions is referred to as HM AC. HM AC can be used with any cryptographic hash function, e.g., M D5 or SHA-1, in combination with a secret shared key. The M c a class provides the functionality of a M essage Authentication Code (M AC). Please refer to the code example.
Creating a
Mc a Object
24/63
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
5/24/12
M cobjects are obtained by using one of the M cg t n t n e )static factory methods. a a eIsac(
Initializing a Mac Object
A M ac object is always initialized with a (secret) key and may optionally be initialized with a set of parameters, depending on the underlying M AC algorithm. To initialize a M ac object, call one of its i i methods: nt pbi vi ii(e ky; ulc od ntKy e) pbi vi ii(e ky AgrtmaaeeSe prm) ulc od ntKy e, loihPrmtrpc aas; You can initialize your M ac object with any (secret-)key object that implements the j v x c y t . e r t e interface. This could be an object returned by aa.rpoSceKy j v x c y t . e G n r t r g n r t K y )or one that is the result of a key aa.rpoKyeeao.eeaee(, agreement protocol, as returned by
K yInterfaces e
To this point, we have focused the high-level uses of the JCA without getting lost in the details of what keys are and how they are generated/represented. It is now time to turn our attention to keys. The j v . e u i y K y a a s c r t . e interface is the top-level interface for all opaque keys. It defines the functionality shared by all opaque key objects. An opaque key representation is one in which you have no direct access to the key material that constitutes a key. In other words: "opaque" gives you limited access to the key--just the three methods defined by the K y e interface (see below): g t l o i h , g t o m tand g t n o e . eAgrtm eFra, eEcdd This is in contrast to a transparent representation, in which you can access each key material value individually, through one of the g tmethods defined in the corresponding specification class. e All opaque keys have three characteristics:
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 25/63
5/24/12
An Algorithm The key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as A SD A R A which will work with those algorithms and with related E , S or S ), algorithms (such as M 5 i h S , S A w t R Aetc.) The name of the algorithm of a DwtRA H1ihS, key is obtained using this method: Srn gtloih( tig eAgrtm) An Encoded Form The external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party. The key is encoded according to a standard format (such as X.509 or PKCS8), and is returned using the method: bt[ gtnoe( ye] eEcdd) A Format The name of the format of the encoded key. It is returned by the method: Srn gtomt) tig eFra( Keys are generally obtained through key generators such as K y e e a o and K y a r e e a o , eGnrtr ePiGnrtr certificates, key specifications (using a K y a t r ), or a K y t r implementation accessing a keystore eFcoy eSoe database used to manage keys. It is possible to parse encoded keys, in an algorithm-dependent manner, using a Kyatr. eFcoy It is also possible to parse certificates, using a C r i i a e a t r . etfctFcoy Here is a list of interfaces which extend the K y e interface in the j v . e u i y i t r a e and aascrt.nefcs j v x c y t . n e f c spackages: aa.rpoitrae
SecretKey PBEKey
The
The K y a r e P i Class
The K y a r e P i class is a simple holder for a key pair (a public key and a private key). It has two public methods, one for returning the private key, and the other for returning the public key: Piaee gtrvt( rvtKy ePiae) PbiKygtulc) ulce ePbi(
Key Specification Interfaces and Classes K yobjects and key specifications (K y p c are two different representations of key data. C p e s use K yobjects e e S e s) ihr e
to initialize their encryption algorithms, but keys may need to be converted into a more portable format for transmission or storage. A transparent representation of keys means that you can access each key material value individually, through one of the g t e methods defined in the corresponding specification class. For example, D A r v t K y p c S P i a e e S e defines g t , g t , eX eP g t , and g t methods, to access the private key xand the DSA algorithm parameters used to calculate the key: the prime p eQ eG , , the sub-prime qand the base gIf the key is stored on a hardware device, its specification may contain information that helps , . identify the key on the device. This representation is contrasted with an opaque representation, as defined by the K y e interface, in which you have no direct access to the key material fields. In other words, an "opaque" representation gives you limited access to the key--just the three methods defined by the K y e interface: g t l o i h , g t o m tand g t n o e . eAgrtm eFra, eEcdd
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 26/63
5/24/12
A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components xpqand g , , , (see D A r v t K y p c or it may be specified S P i a e e S e ), using its DER encoding (see P C 8 n o e K y p c K S E c d d e S e ). The K y a t r and S c e K y a t r classes can be used to convert between opaque and transparent key eFcoy erteFcoy representations (that is, between K y and K y p c assuming that the operation is possible. (For example, private keys on es e S e s, smart cards might not be able leave the card. Such K y are not convertible.) es In the following sections, we discuss the key specification interfaces and classes in the j v . e u i y s e package. aascrt.pc
The
K y p cInterface eSe
This interface contains no methods or constants. Its only purpose is to group and provide type safety for all key specifications. All key specifications must implement this interface.
The
K y p cSubinterfaces eSe
Like the K y e interface, there are a similar set of K y p cinterfaces. eSe SecretKeySpec EncodedKeySpec PKCS8EncodedKeySpec X509EncodedKeySpec DESKeySpec DESedeKeySpec PBEKeySpec DHPrivateKeySpec DSAPrivateKeySpec ECPrivateKeySpec RSAM ultiPrimePrivateCrtKeySpec RSAPrivateCrtKeySpec RSAPrivateKeySpec DHPublicKeySpec DSAPublicKeySpec ECPublicKeySpec RSAPublicKeySpec
The
E c d d e S e Class noeKypc
This abstract class (which implements the K y p c e S e interface) represents a public or private key in encoded format. Its g t n o e method returns the encoded key: eEcdd asrc bt[ gtnoe(; btat ye] eEcdd) and its
See the next sections for the concrete implementations P C 8 n o e K y p c K S E c d d e S e and X0EcddeSe. 59noeKypc
The
PC8noeKypc K S E c d d e S e Class
This class, which is a subclass of E c d d e S e , represents the DER noeKypc encoding of a private key, according to the format specified in the PKCS8 standard. Its g t n o e method returns the key bytes, encoded according to the PKCS8 eEcdd standard. Its g t o m t e F r a method returns the string "PKCS#8".
The
X 0 E c d d e S e Class 59noeKypc
This class, which is a subclass of E c d d e S e , represents the DER noeKypc encoding of a public key, according to the format specified in the X.509 standard. Its g t n o e method returns the key bytes, encoded according to the X.509 eEcdd standard. Its g t o m t e F r a method returns the string "X.509".
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
27/63
5/24/12
factories. Generators are used to generate brand new objects. Generators can be initialized in either an algorithm-dependent or algorithmindependent way. For example, to create a Diffie-Hellman (DH) keypair, an application could specify the necessary P and G values, or the the generator could simply be initialized with the appropriate key length, and the generator will select appropriate P and G values. In both cases, the generator will produce brand new keys based on the parameters. On the other hand, factories are used to convert data from one existing object type to another. For example, an application might have available the components of a DH private key and can package them as a K y p cbut needs to convert them into a eSe, P i a e e object that can be used by a K y g e m n object, or vice-versa. Or they might have the byte array of a rvtKy eAreet certificate, but need to use a C r i i a e a t r to convert it into a X 0 C r i i a e etfctFcoy 5 9 e t f c t object. Applications use factory objects to do the conversion.
Key factories are bi-directional. They allow you to build an opaque key object from a given key specification (key material), or to retrieve the underlying key material of a key object in a suitable format. M ultiple compatible key specifications can exist for the same key. For example, a DSA public key may be specified by its components ypqand g(see j v . e u i y s e . S P b i K y p c or it may be specified using its DER , , , a a s c r t . p c D A u l c e S e ), encoding according to the X.509 standard (see X 0 E c d d e S e ). 59noeKypc A key factory can be used to translate between compatible key specifications. Key parsing can be achieved through translation between compatible key specifications, e.g., when you translate from X 0 E c d d e S e to D A u l c e S e , 59noeKypc SPbiKypc you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications and K y a t r section. eFcoy
K y a t r objects are obtained by using one of the K y a t r g t n t n e )static eFcoy eFcoy eIsac(
factory methods.
5/24/12
k y p cidentifies the specification class in which the key material should be returned. It could, for eSe example, be D A u l c e S e . l s , to indicate that the key material should be returned SPbiKypccas in an instance of the D A u l c e S e class. SPbiKypc
Please see the Examples section for more details.
Key factories are used to convert K y (opaque cryptographic keys of type j v . e u i y K y into key es aascrt.e) specifications (transparent representations of the underlying key material in a suitable format), and vice versa. Objects of type j v . e u i y K yof which j v . e u i y P b i K y aascrt.e, aascrt.ulce, j v . e u i y P i a e e , and j v x c y t . e r t e are subclasses, are opaque key aascrt.rvtKy aa.rpoSceKy objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and may be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys. For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value ythe prime modulus p , , and the base gand you feed the same specification to Diffie-Hellman key factories from different providers, the resulting , P b i K yobjects will most likely have different underlying implementations. ulce
A provider should document the key specifications supported by its secret key factory. For example, the S c e K y a t r for DES keys supplied by the S n C provider supports D S e S e as a transparent erteFcoy uJE EKypc representation of DES keys, the S c e K y a t r for DES-EDE keys supports D S d K y p c a erteFcoy E e e e S e as transparent representation of DES-EDE keys, and the S c e K y a t r for PBE supports P E e S e as a erteFcoy BKypc transparent representation of the underlying password. The following is an example of how to use a S c e K y a t r to convert secret key data into a S c e K y erteFcoy erte object, which can be used for a subsequent
C p e operation: ihr
/ Nt tefloigbtsaentraitcsce kydt / oe h olwn ye r o elsi ert e aa / btsbtaesml sple a a ilsrto o uigdt / ye u r ipy upid s n lutain f sn aa / bts(e mtra)yuarayhv t bidaDSeSe. / ye ky aeil o led ae o ul EKypc bt[ dseDt ={(ye00,(ye00,(ye00, ye] eKyaa bt)x1 bt)x2 bt)x3 (ye00,(ye00,(ye00,(ye00,(ye00 } bt)x4 bt)x5 bt)x6 bt)x7 bt)x8 ; DSeSe dseSe =nwDSeSe(eKyaa; EKypc eKypc e EKypcdseDt) SceKyatr kyatr =SceKyatr.eIsac(DS) erteFcoy eFcoy erteFcoygtntne"E"; SceKysceKy=kyatr.eeaeertdseSe) erte erte eFcoygnrtSce(eKypc; In this case, the underlying implementation of S c e K y based on the provider of K y a t r . e r t e is eFcoy An alternative, provider-independent way of creating a functionally equivalent S c e K y e r t e object from the same key material is to use the j v x c y t . p c S c e K y p c a a . r p o s e . e r t e S e class, which implements the
j v x c y t . e r t e interface: aa.rpoSceKy
bt[ dseDt ={(ye00,(ye00,..; ye] eKyaa bt)x1 bt)x2 .} SceKypcsceKy=nwSceKypcdseDt,"E"; erteSe erte e erteSe(eKyaa DS)
S c e K y a t r objects are obtained by using one of the S c e K y a t r erteFcoy erteFcoy g t n t n e )static factory methods. eIsac(
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 29/63
5/24/12
k y p cidentifies the specification class in which the key material should be returned. It could, for eSe example, be D S e S e . l s , to indicate that the key material should be returned in an EKypccas instance of the D S e S e class. EKypc The K y a r e e a o Class ePiGnrtr
The K y a r e e a o class is an engine class used to generate pairs of public and private keys. ePiGnrtr
There are two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object. Please see the Examples section for examples of calls to the methods documented below.
Creating a K y a r e e a o ePiGnrtr
All key pair generation starts with a K y a r e e a o . K y a r e e a o objects are ePiGnrtr ePiGnrtr obtained by using one of the K y a r e e a o g t n t n e ) e P i G n r t r e I s a c ( static factory methods.
Initializing a K y a r e e a o ePiGnrtr
A key pair generator for a particular algorithm creates a public/private key pair that can be used with this algorithm. It also associates algorithm-specific parameters with each of the generated keys. A key pair generator needs to be initialized before it can generate keys. In most cases, algorithm-independent initialization is sufficient. But in other cases, algorithm-specific initialization can be used.
Algorithm-Independent Initialization
All key pair generators share the concepts of a keysize and a source of randomness. The keysize is interpreted differently for different algorithms. For example, in the case of the DSA algorithm, the keysize corresponds to the length of the modulus. (See the Standard Names document for information about the keysizes for specific algorithms.) An i i i l z method takes two universally shared types of arguments: ntaie vi iiilz(n kyie ScrRno rno) od ntaieit esz, eueadm adm Another i i i l z method takes only a k y i e ntaie e s z argument; it uses a system-provided source of randomness: vi iiilz(n kyie od ntaieit esz) Since no other parameters are specified when you call the above algorithm-independent i i i l z methods, ntaie it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 30/63
5/24/12
If the algorithm is a "DSA" algorithm, and the modulus size (keysize) is 512, 768, or 1024, then the S N U provider uses a set of precomputed values for the pqand g , , parameters. If the modulus size is not one of the above values, the S N U provider creates a new set of parameters. Other providers might have precomputed parameter sets for more than just the three modulus sizes mentioned above. Still others might not have a list of precomputed parameters at all and instead always create new parameter sets.
Algorithm-Specific Initialization
For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two i i i l z methods that have an A g r t m a a e e S e argument. One ntaie loihPrmtrpc also has a S c r R n o argument, while the source of randomness is system-provided for the other: eueadm vi iiilz(loihPrmtrpcprm, od ntaieAgrtmaaeeSe aas ScrRno rno) eueadm adm vi iiilz(loihPrmtrpcprm) od ntaieAgrtmaaeeSe aas See the Examples section for more details.
Creating a
Kyeeao eGnrtr
K y e e a o objects are obtained by using one of the K y e e a o eGnrtr eGnrtr g t n t n e )static factory methods. eIsac(
Initializing a KeyGenerator Object
A key generator for a particular symmetric-key algorithm creates a symmetric key that can be used with that algorithm. It also associates algorithm-specific parameters (if any) with the generated key. There are two ways to generate a key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object: Algorithm-Independent Initialization All key generators share the concepts of a keysize and a source of randomness. There is an i i method that nt takes these two universally shared types of arguments. There is also one that takes just a k y i e esz argument, and uses a system-provided source of randomness, and one that takes just a source of randomness:
pbi vi ii(eueadmrno) ulc od ntScrRno adm; pbi vi ii(n kyie; ulc od ntit esz) pbi vi ii(n kyie ScrRno rno) ulc od ntit esz, eueadm adm; Since no other parameters are specified when you call the above algorithm-independent i i methods, it is up nt to the provider what to do about the algorithm-specific parameters (if any) to be associated with the generated key. Algorithm-S pecific Initialization For situations where a set of algorithm-specific parameters already exists, there are two i i methods that nt have an A g r t m a a e e S e argument. One also has a S c r R n o loihPrmtrpc eueadm argument, while the source of randomness is system-provided for the other:
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 31/63
5/24/12
pbi vi ii(loihPrmtrpcprm) ulc od ntAgrtmaaeeSe aas; pbi vi ii(loihPrmtrpcprm,ScrRno rno) ulc od ntAgrtmaaeeSe aas eueadm adm; In case the client does not explicitly initialize the KeyGenerator (via a call to an i i method), each provider must nt supply (and document) a default initialization.
Creating a Key
The following method generates a secret key: pbi SceKygnrtKy) ulc erte eeaee(;
exchange any secret information. Each party initializes their key agreement object with their private key, and then enters the public keys for each party that will participate in the communication. In most cases, there are just two parties, but algorithms such as Diffie-Hellman allow for multiple parties (3 or more) to participate. When all the public keys have been entered, each K y g e m n object will generate (agree eAreet upon) the same key. The KeyAgreement class provides the functionality of a key agreement protocol. The keys involved in establishing a shared secret are created by one of the key generators (K y a r e e a o or K y e e a o ), a K y a t r , or as a ePiGnrtr eGnrtr eFcoy result from an intermediate phase of the key agreement protocol.
5/24/12
pbi KydPaeKyky boenlsPae; ulc e ohs(e e, ola aths) The k y e parameter contains the key to be processed by that phase. In most cases, this is the public key of one of the other parties involved in the key agreement, or an intermediate key that was generated by a previous phase. d P a emay return an intermediate key that you may have to send to the other parties of this key agreement, so ohs they can process it in a subsequent phase. The l s P a e a t h s parameter specifies whether or not the phase to be executed is the last one in the key agreement: A value of F L E A S indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value of T U indicates that this is the last phase of the key agreement and the key agreement is RE completed, i.e., g n r t S c e can be called next. eeaeert In the example of Diffie-Hellman between two parties , you call d P a e o h s once, with l s P a eset to aths T U . In the example of Diffie-Hellman between three parties, you call d P a etwice: the first time with RE ohs l s P a eset to F L Ethe 2nd time with l s P a eset to T U . aths AS, aths RE
Key Management
A database called a "keystore" can be used to manage a repository of keys and certificates. (A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.)
Keystore Location
The user keystore is by default stored in a file named . e s o e the user's home directory, as determined by k y t r in the "user.home" system property. On Solaris systems "user.home" defaults to the user's home directory. On Win32 systems, given user name uName, "user.home" defaults to: C \ i n \ r f l s u a eon multi-user Windows NT systems :WntPoie\Nm C \ i d w \ r f l s u a eon multi-user Windows 95/98/2000 systems :WnosPoie\Nm C \ i d w o s n l - s rWindows 95/98/2000 systems :Wnos n igeue Of course, keystore files can be located as desired. In some environments, it may make sense for multiple keystores to exist. For example, in JSSE (SSL/TLS), one keystore might hold a user's private keys, and another might hold certificates used to establish trust relationships. In addition to the user's keystore, the Sun JDK also maintains a system-wide keystore which is used to store trusted certificates from a variety of Certificate Authorities (CA's). These CA certificates can be used to help make trust decisions. For example, in SSL/TLS when the S n S E u J S provider is presented with certificates from a remote peer, the default trustmanager will consult the: <aahm>lbetccrs jv-oe/i/x/aet <aahm>lbetccrs jv-oe\i\x\aet [nx,o Ui] r [idw] Wnos
file to determine if the connection is to be trusted. Instead of using the system-wide c c r s aet keystore, applications can set up and use their own keystores, or even use the user keystore described above.
Keystore Implementation
The K y t r class supplies well-defined interfaces to access and modify the information in a eSoe keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore. Currently, there are two command-line tools that make use of K y t r : k y o l j r i n r e S o e e t o and a s g e , and also a GUI-based tool named p l c t o . It is also used by the P l c reference implementation oiyol oiy when it processes policy files specifying the permissions (allowed accesses to system resources) to be granted to code from various sources. Since K y t r is publicly available, JDK users can write additional security applications eSoe that use it.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 33/63
5/24/12
Applications can choose different types of keystore implementations from different providers, using the g t n t n efactory method in the K y t r class. A keystore type defines the storage and data eIsac eSoe format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible. There is a built-in default keystore implementation type known as "j s that is provided by Sun M icrosystems. It k" implements the keystore as a file, utilizing a proprietary keystore type (format). It protects each private key with its own individual password, and also protects the integrity of the entire keystore with a (possibly different) password. The default is specified by the following line in the security properties file: kytr.yejs esoetp=k To have tools and other applications use a different default keystore implementation, you can change that line to specify a default type. If you have a provider package that supplies a keystore implementation for a keystore type called "jceks", change the line to: kytr.yejes esoetp=ck
k y o lalso let you override the default keystore type (via the eto, s o e y ecommand-line parameter). trtp
Some applications, such as NOTE: Keystore type designations are not case-sensitive. For example, "jks" would be considered the same as "jks". There are two other types of keystores that come with the Sun JDK implementation. 1. "jceks" is an alternate proprietary keystore format to "jks" that uses much stronger encryption in the form of Password-Based Encryption with Triple-DES. The Sun "jceks" implementation can parse and convert a "jks" keystore file to the "jceks" format. You may upgrade your keystore of type "jks" to a keystore of type "jceks" by changing the password of a private-key entry in your keystore and specifying " s o e y e j e s as the keystore type. To apply the -trtp ck" cryptographically strong(er) key protection supplied to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords: kyol-epsw -la sgky-trtp jes eto kyasd ais ine soeye ck See Security Tools for more information about k y o l about keystores and how they are managed. e t o and 2. "pkcs12" is another option. This is a cross platform keystore based on the RSA PKCS12 Personal Information Exchange Syntax Standard. This standard is primarily meant for storing or transporting a user's private keys, certificates, and miscellaneous secrets. As of JDK 6, standards for storing Trusted Certificates in "pkcs12" have not been established yet, and thus "jks" or "jceks" should be used for trusted certificates. Keystore implementations are provider-based. Developers interested in writing their own KeyStore implementations should consult How to Implement a Provider for the Java Cryptography Architecture for more information on this topic.
The
K y t r Class eSoe
The K y t r class is an engine class that supplies well-defined interfaces to access and modify eSoe
the information in a keystore. This class represents an in-memory collection of keys and certificates. K y t r manages two types of entries: eSoe Key Entry This type of keystore entry holds very sensitive cryptographic key information, which is
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 34/63
5/24/12
stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain authenticating the corresponding public key. Private keys and certificate chains are used by a given entity for self-authentication using digital signatures. For example, software distribution organizations digitally sign JAR files as part of releasing and/or licensing software. Trusted Certificate Entry This type of entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate. This type of entry can be used to authenticate other parties. Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms. Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This convention allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats). The main K y t r methods are described below. eSoe
5/24/12
The s t e E t y e K y n r methods add (if a i sdoesn't yet exist) or set key entries: la fnlvi steEtySrn ais ia od eKynr(tig la, Kyky e e, ca[ pswr, hr] asod Criiae]can etfct[ hi) fnlvi steEtySrn ais ia od eKynr(tig la, bt[ ky ye] e, Criiae]can etfct[ hi) In the method with k y a byte array, it is the bytes for a key in protected format. For e as example, in the keystore implementation supplied by the S N U provider, the k ybyte e array is expected to contain a protected private key, encoded as an E c y t d r v t K y n oas defined in the PKCS8 standard. In the other nrpePiaeeIf method, the p s w r is the password used to protect the key. asod The d l t E t y e e e n r method deletes an entry: fnlvi dltEtySrn ais ia od eeenr(tig la)
The
A g r t m a a e e S e Interface loihPrmtrpc
A g r t m a a e e S e is an interface to a transparent specification of cryptographic loihPrmtrpc
parameters. This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface. The algorithm parameter specification interfaces and classes in the j v . e u i y s e and aascrt.pc
36/63
5/24/12
The following algorithm parameter specs are used specifically for digital signatures, as part of JSR 105.
The
Agrtmaaees l o i h P r m t r Class
The A g r t m a a e e s l o i h P r m t r class is an engine class that provides an opaque representation of cryptographic parameters. You can initialize the A g r t m a a e e s l o i h P r m t r class using a specific A g r t m a a e e S e object, or by encoding the parameters in a recognized loihPrmtrpc format. You can retrieve the resulting specification with the g t a a e e S e method (see the ePrmtrpc following section).
Creating an A g r t m a a e e s l o i h P r m t r Object
A g r t m a a e e sobjects are obtained by using one of the loihPrmtr A g r t m a a e e sg t n t n e )static factory methods. loihPrmtr eIsac(
Initializing an A g r t m a a e e s l o i h P r m t r Object
Once an A g r t m a a e e s l o i h P r m t r object is instantiated, it must be initialized via a call to i i , using an appropriate parameter specification or parameter encoding: nt vi ii(loihPrmtrpcprmpc od ntAgrtmaaeeSe aaSe) vi ii(ye]prm) od ntbt[ aas vi ii(ye]prm,Srn fra) od ntbt[ aas tig omt In these i i methods, p r m is an array containing the encoded parameters, and nt aas
f r a is the name of the decoding format. In the i i method with a p r m omt nt aas argument but no f r a argument, the primary decoding format for parameters is omt
used. The primary decoding format is ASN.1, if an ASN.1 specification for the parameters exists. NOTE: A g r t m a a e e s l o i h P r m t r objects can be initialized only once. They are not reusable.
5/24/12
ignored.
The
A g r t m a a e e G n r t rClass loihPrmtreeao
The A g r t m a a e e G n r t r l o i h P r m t r e e a o class is an engine class used to generate a set of brand-new parameters suitable for a certain algorithm (the algorithm is specified when an A g r t m a a e e G n r t rinstance is created). This object is used when you do loihPrmtreeao not have an existing set of algorithm parameters, and want to generate one from scratch.
Creating an A g r t m a a e e G n r t r l o i h P r m t r e e a o Object
A g r t m a a e e G n r t robjects are obtained by using one of the loihPrmtreeao A g r t m a a e e G n r t rg t n t n e )static factory loihPrmtreeao eIsac(
methods.
Initializing an A g r t m a a e e G n r t r l o i h P r m t r e e a o Object
The A g r t m a a e e G n r t r l o i h P r m t r e e a o object can be initialized in two different ways: an algorithm-independent manner or an algorithm-specific manner. The algorithm-independent approach uses the fact that all parameter generators share the concept of a "size" and a source of randomness. The measure of size is universally shared by all algorithm parameters, though it is interpreted differently for different algorithms. For example, in the case of parameters for the DSA algorithm, "size" corresponds to the size of the prime modulus, in bits. (See the Standard Names document for information about the sizes for specific algorithms.) When using this approach, algorithm-specific parameter generation values--if any--default to some standard values. One i i method that takes these two universally shared types of arguments: nt vi ii(n sz,ScrRno rno) od ntit ie eueadm adm; Another i i method takes only a s z argument and uses a system-provided nt ie source of randomness: vi ii(n sz) od ntit ie A third approach initializes a parameter generator object using algorithm-specific semantics, which are represented by a set of algorithm-specific parameter generation values supplied in an
A g r t m a a e e S e object: loihPrmtrpc
vi ii(loihPrmtrpcgnaaSe, od ntAgrtmaaeeSe ePrmpc ScrRno rno) eueadm adm vi ii(loihPrmtrpcgnaaSe) od ntAgrtmaaeeSe ePrmpc To generate Diffie-Hellman system parameters, for example, the parameter generation values usually consist of the size of the prime modulus and the size of the random exponent, both specified in number of bits.
5/24/12
jv.euiycr.59R. aascrt.etX0CL
5/24/12
traffic. NOTE: The details presented here simply show how some of the above classes might be employed. This section will not present sufficient information for building a SSL/TLS implementation. For more details, please see the JSSE Reference Guide and RFC 2246: The TLS Protocol. Assume that this SSL/TLS implementation will be made available as a JSSE provider. A concrete implementation of the P o i e class is first rvdr written that will eventually be registered in the S c r t class' list of providers. This provider mainly provides a mapping from algorithm names euiy to actual implementation classes. (that is: "SSLContext.TLS"->"com.foo.TLSImpl") When an application requests an "TLS" instance (via S L o t x . e I s a c ( T S )the provider's list is consulted for the requested algorithm, and an appropriate instance is SCnetgtntne"L", created. Before discussing details of the actual handshake, a quick review of some of the JSSE's architecture is needed. The heart of the JSSE architecture is the S L o t x . The context eventually creates end objects (S L o k tand S L n i e which actually implement the SSL/TLS SCnet SSce SEgn) protocol. S L o t x s are initialized with two callback classes, K y a a e and T u t a a e , which allow applications to SCnet eMngr rsMngr first select authentication material to send and second to verify credentials sent by a peer. A JSSE K y a a e is responsible for choosing which credentials to present to a peer. M any algorithms are possible, but a common strategy is eMngr to maintain a RSA or DSA public/private key pair along with a X 0 C r i i a e a K y t r backed by a disk file. When a 5 9 e t f c t in e S o e K y t r object is initialized and loaded from the file, the file's raw bytes are converted into P b i K yand P i a e e objects eSoe ulce rvtKy using a K y a t r , and a certificate chain's bytes are converted using a C r i i a e a t r . When a credential is needed, the eFcoy etfctFcoy K y a a e simply consults this K y t r object and determines which credentials to present. eMngr eSoe A K y t r 's contents might have originally been created using a utility such as k y o lk y o l eSoe e t o . e t o creates a RSA or DSA K y a r e e a o and initializes it with an appropriate keysize. This generator is then used to create a K y a rwhich ePiGnrtr ePi k y o lwould store along with the newly-created certificate in the K y t r , which is eventually written to disk. eto eSoe A JSSE T u t a a e is responsible for verifying the credentials received from a peer. There are many ways to verify credentials: one of rsMngr them is to create a C r P t object, and let the JDK's built-in Public Key Infrastructure (PKI) framework handle the validation. Internally, the etah CertPath implementation might create a S g a u e i n t r object, and use that to verify that the each of the signatures in the certificate chain. With this basic understanding of the architecture, we can look at some of the steps in the SSL/TLS handshake. The client begins by sending a ClientHello message to the server. The server selects a ciphersuite to use, and sends that back in a ServerHello message, and begins creating JCA objects based on the suite selection. We'll use server-only authentication in the following examples.
In the first example, the server tries to use a RSA-based ciphersuite such as TLS_RSA_WITH_AES_128_CBC_SHA. The server's K y a a e eMngr is queried, and returns an appropriate RSA entry. The server's credentials (that is: certificate/public key) are sent in the server's Certificate message. The client's T u t a a e verifies the server's certificate, and if accepted, the client generates some random bytes using a S c r R n o rsMngr eueadm object. This is then encrypted using an encrypting asymmetric RSA C p e object that has been initialized with the P b i K y ihr u l c e found in
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 40/63
5/24/12
the server's certificate. This encrypted data is sent in a Client Key Exchange message. The server would use its corresponding P i a e e to rvtKy recover the bytes using a similar C p e in decrypt mode. These bytes are then used to establish the actual encryption keys. ihr In a different example, an ephemeral Diffie-Hellman key agreement algorithm along with the DSA signature algorithm is chosen, such as TLS_DHE_DSS_WITH_AES_128_CBC_SHA. The two sides must each establish a new temporary DH public/private keypair using a K y a r e e a o . Each generator creates DH keys which can then be further converted into pieces using the K y a t r and ePiGnrtr eFcoy D P b i K y p cclasses. Each side then creates a K y g e m n object and initializes it with their respective DH HulceSe eAreet P i a e e s. The server sends its public key pieces in a ServerKeyExchange message (protected by the DSA signature algorithm, and the client rvtKy sends its public key in a ClientKeyExchange message. When the public keys are reassembled using another K y a t r , they are fed into the eFcoy agreement objects. The K y g e m n objects then generate agreed-upon bytes that are then used to establish the actual encryption keys. eAreet Once the actual encryption keys have been established, the secret key is used to initialize a symmetric C p e object, and this cipher is used to ihr protect all data in transit. To help determine if the data has been modified, a M s a e i e t created and receives a copy of the data e s g D g s is destined for the network. When the packet is complete, the digest (hash) is appended to data, and the entire packet is encrypted by the C p e . If ihr a block cipher such as AES is used, the data must be padded to make a complete block. On the remote side, the steps are simply reversed. Padding (if any)
Header
Data
Digest
Again, this is vastly simplied, but gives one an idea of how these classes might be combined to create a higher level protocol.
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
5/24/12
by the entry in the Permission Policy File Step 4: Test Your Application Step 5: Apply for U.S. Government Export Approval If Required Step 6: Deploy Your Application
5/24/12
Code Examples
Here are some short examples which illustrate use of several of the JCA mechanisms. In addition, complete working examples can be found in Appendix D.
Computing a M s a e i e t e s g D g s Object
First create the message digest object, as in the following example: Msaeietsa=Msaeietgtntne"H-"; esgDgs h esgDgs.eIsac(SA1) This call assigns a properly initialized message digest object to the s a h variable. The implementation implements the Secure Hash Algorithm (SHA-1), as defined in the National Institute for Standards and Technology's (NIST) FIPS 180-2 document. See Appendix A for a complete discussion of standard names and algorithms. Next, suppose we have three byte arrays, i , i and i , which form the total input whose message digest we want to compute. 1 2 3 This digest (or "hash") could be calculated via the following calls:
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 43/63
5/24/12
saudt(1; h.paei) saudt(2; h.paei) saudt(3; h.paei) bt[ hs =sadgs(; ye] ah h.iet) An equivalent alternative series of calls would be: saudt(1; h.paei) saudt(2; h.paei) bt[ hs =sadgs(3; ye] ah h.ieti) After the message digest has been calculated, the message digest object is automatically reset and ready to receive new data and calculate its digest. All former state (i.e., the data supplied to u d t calls) is lost. pae Some hash implementations may support intermediate hashes through cloning. Suppose we want to calculate separate hashes for:
i 1 i adi 1 n 2 i,i,adi 1 2 n 3
A way to do it is: / cmuetehs fri * * opt h ah o 1 / saudt(1; h.paei) bt[ iHs =sacoe)dgs(; ye] 1ah h.ln(.iet) / cmuetehs fri adi * * opt h ah o 1 n 2 / saudt(2; h.paei) bt[ i2ah=sacoe)dgs(; ye] 1Hs h.ln(.iet) / cmuetehs fri,i adi * * opt h ah o 1 2 n 3 / saudt(3; h.paei) bt[ i2hs =sadgs(; ye] 13ah h.iet) This code works only if the SHA-1 implementation is cloneable. While some implementations of message digests are cloneable, others are not. To determine whether or not cloning is possible, attempt to clone the M s a e i e t esgDgs object and catch the potential exception as follows: ty{ r / tyadcoei / r n ln t / cmuetehs fri * * opt h ah o 1 / saudt(1; h.paei) bt[ iHs =sacoe)dgs(; ye] 1ah h.ln(.iet) ... bt[ i2hs =sadgs(; ye] 13ah h.iet) }cth(lnNtupreEcpincs){ ac CoeoSpotdxeto ne / d smtiges,sc a tecd sonblw / o oehn le uh s h oe hw eo } If a message digest is not cloneable, the other, less elegant way to compute intermediate digests is to create several digests. In this case, the number of intermediate digests to be computed must be known in advance:
M s a e i e ts a = M s a e i e t g t n t n e " H - " ; e s g D g s h1 esgDgs.eIsac(SA1) M s a e i e ts a 2 = M s a e i e t g t n t n e " H - " ; e s g D g s h1 esgDgs.eIsac(SA1) M s a e i e ts a 2 = M s a e i e t g t n t n e " H - " ; e s g D g s h13 esgDgs.eIsac(SA1)
bt[ iHs =sa.ieti) ye] 1ah h1dgs(1; sa2udt(1; h1.paei) bt[ i2ah=sa2dgs(2; ye] 1Hs h1.ieti) sa2.paei) h13udt(1; sa2.paei) h13udt(2; bt[ i2Hs =sa2.ieti) ye] 13ah h13dgs(3;
5/24/12
The first step is to get a key pair generator object for generating keys for the DSA algorithm: Kyareeao kye =Kyareeao.eIsac(DA) ePiGnrtr eGn ePiGnrtrgtntne"S";
Algorithm-Independent Initialization
All key pair generators share the concepts of a keysize and a source of randomness. The
K y a r e e a o class initialization methods at a minimum needs a keysize. If the source of ePiGnrtr randomness is not explicitly provided, a S c r R n o implementation of the highest-priority installed eueadm
provider will be used. Thus to generate keys with a keysize of 1024, simply call: ScrRno rno =ScrRno.eIsac(SAPN" "U"; eueadm adm eueadmgtntne"H1RG, SN) kye.ntaie12,rno) eGniiilz(04 adm; The following code illustrates how to use a specific, additionally seeded S c r R n o object: eueadm ScrRno rno =ScrRno.eIsac(SAPN" "U"; eueadm adm eueadmgtntne"H1RG, SN) rno.eSe(sred; admstedueSe) kye.ntaie12,rno) eGniiilz(04 adm; Since no other parameters are specified when you call the above algorithm-independent i i i l z method, it is up to the provider what to do about the algorithm-specific parameters (if ntaie any) to be associated with each of the keys. The provider may use precomputed parameter values or may generate new values.
Algorithm-Specific Initialization
For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two i i i l z methods that have an A g r t m a a e e S e argument. ntaie loihPrmtrpc Suppose your key pair generator is for the "DSA" algorithm, and you have a set of DSA-specific parameters, pq , , and gthat you would like to use to generate your key pair. You could execute the following code to initialize your , key pair generator (recall that D A a a e e S e is an AlgorithmParameterSpec): SPrmtrpc DAaaeeSe dapc=nwDAaaeeSe(,q g; SPrmtrpc sSe e SPrmtrpcp , ) ScrRno rno =ScrRno.eIsac(SAPN" "U"; eueadm adm eueadmgtntne"H1RG, SN) rno.eSe(sred; admstedueSe) kye.ntaiedapc rno) eGniiilz(sSe, adm; NOTE: The parameter named p a prime number whose length is the modulus length is ("size"). Therefore, you don't need to call any other method to specify the modulus length.
Generating a Signature
We first create a signature object: Sgaueda=Sgauegtntne"H1ihS"; intr s intr.eIsac(SAwtDA) Next, using the key pair generated in the key pair example, we initialize the object with the private key, then sign a byte array called d t . aa / Iiilzn teojc wt apiaeky* * ntaiig h bet ih rvt e / Piaee pi =pi.ePiae) rvtKy rv argtrvt(; daiiSg(rv; s.ntinpi) / Udt adsg tedt * * pae n in h aa / daudt(aa; s.paedt) bt[ sg=dasg(; ye] i s.in)
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 45/63
5/24/12
Verifying a Signature
Verifying the signature is straightforward. (Note that here we also use the key pair generated in the key pair example.) / Iiilzn teojc wt tepbi ky* * ntaiig h bet ih h ulc e / PbiKypb=pi.ePbi(; ulce u argtulc) daiiVrf(u) s.nteiypb; / Udt advrf tedt * * pae n eiy h aa / daudt(aa; s.paedt) boenvrfe =davrf(i) ola eiis s.eiysg; Sse.u.rnl(sgauevrfe:"+vrfe) ytmotpitn"intr eiis eiis;
5/24/12
sgvrf(intr) i.eiysgaue; NOTE: In the above, Alice needed to generate a P b i K y u l c e from the encoded key bits, since i i V r f nteiy requires a P b i K yOnce she has a P b i K yshe could also use the K y a t r ulce. ulce, eFcoy g t e S e method to convert it to a D A u l c e S e so that she can access the components, if eKypc SPbiKypc desired, as in: DAulceSe dauKypc= SPbiKypc sPbeSe (SPbiKypckyatr.eKypcpbe, DAulceSe)eFcoygteSe(uKy DAulceSe.ls) SPbiKypccas Now she can access the DSA public key components ypqand g , , , through the corresponding "get" methods on the D A u l c e S e class (g t , g t , g t , and g t ). SPbiKypc eY eP eQ eG
5/24/12
The following example parses a PKCS7-formatted certificate reply stored in a file and extracts all the certificates from it: FlIpttemfs=nwFlIpttemflnm) ienuSra i e ienuSra(ieae; Criiaeatr c =Criiaeatr.eIsac(X59) etfctFcoy f etfctFcoygtntne".0"; Cleto c=c.eeaeetfctsfs; olcin fgnrtCriiae(i) Ieao i=cieao(; trtr .trtr) wie(.aNx(){ hl ihset) Criiaecr =(etfct).et) etfct et Criiaeinx(; Sse.u.rnl(et; ytmotpitncr) }
Using Encryption
This section takes the user through the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. Throughout this example, we use the Advanced Encryption Standard (AES).
Generating a Key
To create an AES key, we have to instantiate a KeyGenerator for AES. We do not specify a provider, because we do not care about a particular AES key generation implementation. Since we do not initialize the KeyGenerator, a systemprovided source of randomness and a default keysize will be used to create the AES key: Kyeeao kye =Kyeeao.eIsac(AS) eGnrtr egn eGnrtrgtntne"E"; SceKyase =kye.eeaee(; erte eKy egngnrtKy) After the key has been generated, the same KeyGenerator object can be re-used to create further keys.
Creating a Cipher
The next step is to create a Cipher instance. To do this, we use one of the g t n t n e e I s a c factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/): the algorithm name the mode (optional) the padding scheme (optional) In this example, we create an AES cipher in Electronic Codebook mode, with PKCS5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation. The standard algorithm name for AES is "AES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS5-style padding is "PKCS5Padding": Cpe asihr ihr eCpe; / Cet tecpe / rae h ihr asihr=Cpe.eIsac(ASEBPC5adn"; eCpe ihrgtntne"E/C/KSPdig) We use the generated a s e from above to initialize the Cipher object for encryption: eKy / Iiilz tecpe frecyto / ntaie h ihr o nrpin asihrii(ihrECYTMD,ase) eCpe.ntCpe.NRP_OE eKy; / Orceret / u latx bt[ ceret="hsi js a eape.eBts) ye] latx Ti s ut n xml"gtye(; / Ecytteceret / nrp h latx bt[ cpetx =asihrdFnlceret; ye] ihret eCpe.oia(latx) / Iiilz tesm cpe frdcyto / ntaie h ae ihr o erpin asihrii(ihrDCYTMD,ase) eCpe.ntCpe.ERP_OE eKy; / Dcyttecpetx / erp h ihret bt[ ceret =asihrdFnlcpetx) ye] latx1 eCpe.oia(ihret;
5/24/12
It would seem logical to collect and store the password in an object of type j v . a g S r n . However, here's the aaln.tig caveat: Objects of type S r n are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out tig the contents of a S r n after usage. This feature makes S r n objects unsuitable for storing security sensitive information tig tig such as user passwords. You should always collect and store security sensitive information in a char array instead. For that reason, the j v x c y t . p c P E e S e class takes (and returns) a password as a char array. See aa.rpose.BKypc the ReadPassword class in the sample code in Appendix D for one possible way of reading character array passwords from an input stream. In order to use Password-Based Encryption (PBE) as defined in PKCS5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption: PEeSe peeSe; BKypc bKypc PEaaeeSe peaaSe; BPrmtrpc bPrmpc SceKyatr kya; erteFcoy eFc / Sl / at bt[ sl ={ ye] at (ye0c,(ye07,(ye02,(ye08, bt)x7 bt)x3 bt)x1 bt)xc (ye07,(ye0c,(ye0e,(ye09 bt)xe bt)x8 bt)xe bt)x9 } ; / Ieaincut / trto on itcut=2; n on 0 / Cet PEprmtrst / rae B aaee e peaaSe =nwPEaaeeSe(at cut; bPrmpc e BPrmtrpcsl, on) / Pop ue frecyto pswr. / rmt sr o nrpin asod / Cletue pswr a ca ary(sn te / olc sr asod s hr ra uig h / "edasod mto fo aoe,adcnet / raPswr" ehd rm bv) n ovr / i it aSceKyojc,uigaPEky / t no erte bet sn B e / fcoy / atr. Sse.u.rn(Etrecyto pswr: "; ytmotpit"ne nrpin asod ) Sse.u.ls(; ytmotfuh) peeSe =nwPEeSe(edasodSse.n) bKypc e BKypcraPswr(ytmi); kya =SceKyatr.eIsac(PEihDAdE"; eFc erteFcoygtntne"BWtM5nDS) SceKypee =kya.eeaeertpeeSe) erte bKy eFcgnrtSce(bKypc; / Cet PECpe / rae B ihr Cpe peihr=Cpe.eIsac(PEihDAdE"; ihr bCpe ihrgtntne"BWtM5nDS) / Iiilz PECpe wt kyadprmtr / ntaie B ihr ih e n aaees peihrii(ihrECYTMD,pee,peaaSe) bCpe.ntCpe.NRP_OE bKy bPrmpc; / Orceret / u latx bt[ ceret="hsi aohreape.eBts) ye] latx Ti s nte xml"gtye(; / Ecytteceret / nrp h latx bt[ cpetx =peihrdFnlceret; ye] ihret bCpe.oia(latx)
5/24/12
implementation. The PKCS11 Reference Guide and the underlying PKCS11 implementation should be consulted to determine if a desired algorithm will be available through the PKCS11 provider. Likewise, on Windows systems, the S n S A I u M C P provider does not provide any cryptographic functionality, but instead routes requests to the underlying Operating System for handling.
NOTE: An "*" can be used as a wildcard for any permission entry option. For example, an "*" (without the quotes) for an <alg_name> option means "all algorithms."
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
50/63
5/24/12
ipr jv.o* mot aai.; ipr jv.ahBgnee; mot aamt.iItgr ipr jv.euiy* mot aascrt.; ipr jv.euiyse.; mot aascrt.pc* ipr jv.euiyitrae.; mot aascrt.nefcs* ipr jvxcyt.; mot aa.rpo* ipr jvxcyt.pc* mot aa.rpose.; ipr jvxcyt.nefcs* mot aa.rpoitrae.; ipr cmsncyt.rvdrSnC; mot o.u.rpopoie.uJE /* * *Ti pormeeue teDfi-ela kyareetpooo hs rga xcts h ifeHlmn e gemn rtcl *bten2pris AieadBb ewe ate: lc n o. * *B dfut peofgrdprmtr (04btpiemdlsadbs y eal, rcniue aaees 12-i rm ouu n ae *gnrtrue b SI)aeue. eeao sd y KP r sd *I ti pormi cle wt te"gn oto,anwsto f hs rga s ald ih h -e" pin e e f *prmtr i cetd aaees s rae. * /
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 51/63
5/24/12
pbi casDKygemn2{ ulc ls HeAreet piaeDKygemn2){ rvt HeAreet( } pbi sai vi mi(tigag[){ ulc ttc od anSrn rv] ty{ r Srn md ="S_KPD_AAS; tig oe UESI_HPRM" DKygemn2kyge =nwDKygemn2) HeAreet eAre e HeAreet(; i (rvlnt >1 { f ag.egh ) kyge.sg(; eAreuae) trwnwEcpin"rn nme o cmadotos) ho e xeto(Wog ubr f omn pin"; }es i (rvlnt = 1 { le f ag.egh = ) i ((rv0.qas"gn)){ f !ag[]eul(-e") kyge.sg(; eAreuae) trwnwEcpin"neonzdfa:"+ag[]; ho e xeto(Urcgie lg rv0) } md ="EEAED_AAS; oe GNRT_HPRM" } kyge.u(oe; eArernmd) }cth(xeto e { ac Ecpin ) Sse.r.rnl(Err "+e; ytmerpitn"ro: ) Sse.xt1; ytmei() } } piaevi rnSrn md)trw Ecpin{ rvt od u(tig oe hos xeto DPrmtrpcdSiPrmpc HaaeeSe hkpaaSe; i (oeeul(GNRT_HPRM"){ f md.qas"EEAED_AAS) / Sm cnrlatoiycetsnwD prmtr / oe eta uhrt rae e H aaees Sse.u.rnl ytmotpitn (Cetn Dfi-ela prmtr (ae VR ln)..) "raig ifeHlmn aaees tks EY og ."; AgrtmaaeeGnrtrprme loihPrmtreeao aaGn =AgrtmaaeeGnrtrgtntne"H) loihPrmtreeao.eIsac(D"; prme.nt52; aaGnii(1) Agrtmaaeesprm =prme.eeaeaaees) loihPrmtr aas aaGngnrtPrmtr(; dSiPrmpc=(HaaeeSe)aasgtaaeeSe hkpaaSe DPrmtrpcprm.ePrmtrpc (HaaeeSe.ls) DPrmtrpccas; }es { le / uesm pegnrtd dfutD prmtr / s oe r-eeae, eal H aaees Sse.u.rnl(UigSI Dfi-ela prmtr"; ytmotpitn"sn KP ifeHlmn aaees) dSiPrmpc=nwDPrmtrpcsi12Mdls hkpaaSe e HaaeeSe(kp04ouu, si12Bs) kp04ae; } / * *AiecetshronD kypi,uigteD prmtr fo lc rae e w H e ar sn h H aaees rm *aoe bv * / Sse.u.rnl(AIE Gnrt D kyar..) ytmotpitn"LC: eeae H epi ."; Kyareeao aiepiGn=Kyareeao.eIsac(D"; ePiGnrtr lcKare ePiGnrtrgtntne"H) aiepiGniiilz(hkpaaSe) lcKare.ntaiedSiPrmpc; Kyaraiepi =aiepiGngnrtKyar) ePi lcKar lcKare.eeaeePi(; / AiecetsadiiilzshrD Kygemn ojc / lc rae n ntaie e H eAreet bet Sse.u.rnl(AIE Iiilzto ..) ytmotpitn"LC: ntaiain ."; Kygemn aieeAre=Kygemn.eIsac(D"; eAreet lcKyge eAreetgtntne"H) aieeAreii(lcKargtrvt() lcKyge.ntaiepi.ePiae); / Aieecdshrpbi ky adsnsi oe t Bb / lc noe e ulc e, n ed t vr o o. bt[ aieuKyn =aiepi.ePbi(.eEcdd) ye] lcPbeEc lcKargtulc)gtnoe(; / * *Ltstr oe t Bb Bbhsrcie Aiespbi ky e' un vr o o. o a eevd lc' ulc e *i ecddfra. n noe omt *H isatae aD pbi kyfo teecddkymtra. e ntnits H ulc e rm h noe e aeil * / Kyatr bbeFc=Kyatr.eIsac(D"; eFcoy oKya eFcoygtntne"H)
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 52/63
5/24/12
X0EcddeSe x0Kypc=nwX0EcddeSe 59noeKypc 59eSe e 59noeKypc (lcPbeEc; aieuKyn) PbiKyaieuKy=bbeFcgnrtPbi(59eSe) ulce lcPbe oKya.eeaeulcx0Kypc; / * *Bbgt teD prmtr ascae wt Aiespbi ky o es h H aaees soitd ih lc' ulc e. *H ms uetesm prmtr we h gnrtshsonky e ut s h ae aaees hn e eeae i w e *pi. ar * / DPrmtrpcdPrmpc=(DPbiKyaieuKy.ePrm(; HaaeeSe haaSe (Hulce)lcPbe)gtaas) / BbcetshsonD kypi / o rae i w H e ar Sse.u.rnl(BB Gnrt D kyar..) ytmotpitn"O: eeae H epi ."; Kyareeao bbpiGn=Kyareeao.eIsac(D"; ePiGnrtr oKare ePiGnrtrgtntne"H) bbpiGniiilz(haaSe) oKare.ntaiedPrmpc; Kyarbbpi =bbpiGngnrtKyar) ePi oKar oKare.eeaeePi(; / BbcetsadiiilzshsD Kygemn ojc / o rae n ntaie i H eAreet bet Sse.u.rnl(BB Iiilzto ..) ytmotpitn"O: ntaiain ."; Kygemn bbeAre=Kygemn.eIsac(D"; eAreet oKyge eAreetgtntne"H) bbeAreii(oKargtrvt() oKyge.ntbbpi.ePiae); / Bbecdshspbi ky adsnsi oe t Aie / o noe i ulc e, n ed t vr o lc. bt[ bbuKyn =bbpi.ePbi(.eEcdd) ye] oPbeEc oKargtulc)gtnoe(; / * *Aieue Bbspbi kyfrtefrt(n ol)pae lc ss o' ulc e o h is ad ny hs *o hrvrino teD f e eso f h H *pooo. rtcl *Bfr secnd s,sehst isataeaD pbi ky eoe h a o o h a o ntnit H ulc e *fo Bbsecddkymtra. rm o' noe e aeil * / Kyatr aieeFc=Kyatr.eIsac(D"; eFcoy lcKya eFcoygtntne"H) x0Kypc=nwX0EcddeSe(oPbeEc; 59eSe e 59noeKypcbbuKyn) PbiKybbuKy=aieeFcgnrtPbi(59eSe) ulce oPbe lcKya.eeaeulcx0Kypc; Sse.u.rnl(AIE EeuePAE ..) ytmotpitn"LC: xct HS1 ."; aieeAredPaebbuKy tu) lcKyge.ohs(oPbe, re; / * *Bbue Aiespbi kyfrtefrt(n ol)pae o ss lc' ulc e o h is ad ny hs *o hsvrino teD f i eso f h H *pooo. rtcl * / Sse.u.rnl(BB EeuePAE ..) ytmotpitn"O: xct HS1 ."; bbeAredPaeaieuKy tu) oKyge.ohs(lcPbe, re; / * *A ti sae bt AieadBbhv cmltdteD ky t hs tg, oh lc n o ae opee h H e *areetpooo. gemn rtcl *Bt gnrt te(ae sae sce. oh eeae h sm) hrd ert * / bt[ aiehrdert=aieeAregnrtSce(; ye] lcSaeSce lcKyge.eeaeert) itaiee =aiehrdertlnt; n lcLn lcSaeSce.egh bt[ bbhrdert=nwbt[lcLn; ye] oSaeSce e yeaiee] itbbe; n oLn ty{ r / so eapeo wa hpesi yu / hw xml f ht apn f o / poiea otu bfe ta i tosot / rvd n upt ufr ht s o hr bbe =bbeAregnrtSce(oSaeSce,1; oLn oKyge.eeaeertbbhrdert ) }cth(hrBfeEcpine { ac Sotufrxeto ) Sse.u.rnl(.eMsae); ytmotpitnegtesg() } / poieotu bfe o rqie sz / rvd upt ufr f eurd ie bbe =bbeAregnrtSce(oSaeSce,0; oLn oKyge.eeaeertbbhrdert ) Sse.u.rnl(Aiesce:"+ ytmotpitn"lc ert tHxtigaiehrdert) oeSrn(lcSaeSce); Sse.u.rnl(Bbsce:"+ ytmotpitn"o ert tHxtigbbhrdert) oeSrn(oSaeSce); i (jv.tlAry.qasaiehrdert bbhrdert) f !aaui.raseul(lcSaeSce, oSaeSce) trwnwEcpin"hrdscesdfe"; ho e xeto(Sae ert ifr)
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 53/63
5/24/12
Sse.u.rnl(Sae scesaetesm"; ytmotpitn"hrd ert r h ae) / * *Nwltsrtr tesae sce a aSceKyojc o e' eun h hrd ert s erte bet *aduei frecyto.Frt w gnrt SceKy frte n s t o nrpin is, e eeae ertes o h *"E"agrtm(ae o terwsae sce dt)ad DS loih bsd n h a hrd ert aa n *te w ueDSi EBmd hn e s E n C oe *a teecyto agrtm DSi EBmd de ntrqieay s h nrpin loih. E n C oe os o eur n *prmtr. aaees * *Te w ueDSi CCmd,wihrqie a iiilzto hn e s E n B oe hc eurs n ntaiain *vco (V prmtr I CCmd,yune t iiilz te etr I) aaee. n B oe o ed o ntaie h *Cpe ojc wt a I,wihcnb sple uigte ihr bet ih n V hc a e upid sn h *jvxcyt.pcIPrmtrpccas Nt ta yuhv t ue aa.rpose.vaaeeSe ls. oe ht o ae o s *tesm I frecyto addcyto:I yuueadfeet h ae V o nrpin n erpin f o s ifrn *I frdcyto ta yuue frecyto,dcyto wl V o erpin hn o sd o nrpin erpin il *fi. al * *NT:I yud ntseiya I we yuiiilz te OE f o o o pcf n V hn o ntaie h *Cpe ojc frecyto,teudryn ipeetto ihr bet o nrpin h nelig mlmnain *wl gnrt arno oe wihyuhv t rtiv uigte il eeae adm n, hc o ae o eree sn h *jvxcyt.ihrgtaaees)mto,wihrtrsa aa.rpoCpe.ePrmtr( ehd hc eun n *isac o jv.euiyAgrtmaaees Yune t tase ntne f aascrt.loihPrmtr. o ed o rnfr *tecnet o ta ojc (.. i ecddfra,otie va h otns f ht bet eg, n noe omt band i *teAgrtmaaeesgtnoe( mto)t teprywowl h loihPrmtr.eEcdd) ehd o h at h il *d tedcyto.We iiilzn teCpe frdcyto, o h erpin hn ntaiig h ihr o erpin *te(entnitd Agrtmaaeesojc ms b pse t h risatae) loihPrmtr bet ut e asd o *teCpe.nt)mto. h ihrii( ehd * / Sse.u.rnl(Rtr sae sce a SceKyojc ..) ytmotpitn"eun hrd ert s erte bet ."; / Bb / o / NT:Tecl t bbeAregnrtSce aoerstteky / OE h al o oKyge.eeaeert bv ee h e / areetojc,s w cl dPaeaanpirt aohr / gemn bet o e al ohs gi ro o nte / gnrtSce cl / eeaeert al bbeAredPaeaieuKy tu) oKyge.ohs(lcPbe, re; SceKybbeKy=bbeAregnrtSce(DS) erte oDse oKyge.eeaeert"E"; / Aie / lc / NT:Tecl t aieeAregnrtSce aoerstteky / OE h al o lcKyge.eeaeert bv ee h e / areetojc,s w cl dPaeaanpirt aohr / gemn bet o e al ohs gi ro o nte / gnrtSce cl / eeaeert al aieeAredPaebbuKy tu) lcKyge.ohs(oPbe, re; SceKyaieeKy=aieeAregnrtSce(DS) erte lcDse lcKyge.eeaeert"E"; / * *Bbecyt,uigDSi EBmd o nrps sn E n C oe * / Cpe bbihr=Cpe.eIsac(DSEBPC5adn"; ihr oCpe ihrgtntne"E/C/KSPdig) bbihrii(ihrECYTMD,bbeKy; oCpe.ntCpe.NRP_OE oDse) bt[ ceret="hsi js a eape.eBts) ye] latx Ti s ut n xml"gtye(; bt[ cpetx =bbihrdFnlceret; ye] ihret oCpe.oia(latx) / * *Aiedcyt,uigDSi EBmd lc erps sn E n C oe * / Cpe aieihr=Cpe.eIsac(DSEBPC5adn"; ihr lcCpe ihrgtntne"E/C/KSPdig) aieihrii(ihrDCYTMD,aieeKy; lcCpe.ntCpe.ERP_OE lcDse) bt[ rcvrd=aieihrdFnlcpetx) ye] eoee lcCpe.oia(ihret; i (jv.tlAry.qasceret rcvrd) f !aaui.raseul(latx, eoee) trwnwEcpin"E i CCmd rcvrdtx i "+ ho e xeto(DS n B oe eoee et s "ifrn fo ceret) dfeet rm latx"; Sse.u.rnl(DSi EBmd rcvrdtx i "+ ytmotpitn"E n C oe eoee et s "aea ceret) sm s latx"; / * *Bbecyt,uigDSi CCmd o nrps sn E n B oe * / bbihr=Cpe.eIsac(DSCCPC5adn"; oCpe ihrgtntne"E/B/KSPdig) bbihrii(ihrECYTMD,bbeKy; oCpe.ntCpe.NRP_OE oDse) ceret="hsi js a eape.eBts) latx Ti s ut n xml"gtye(;
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 54/63
5/24/12
cpetx =bbihrdFnlceret; ihret oCpe.oia(latx) / Rtiv teprmtrta wsue,adtase i t Aiei / eree h aaee ht a sd n rnfr t o lc n / ecddfra / noe omt bt[ ecddaas=bbihrgtaaees)gtnoe(; ye] noePrm oCpe.ePrmtr(.eEcdd) / * *Aiedcyt,uigDSi CCmd lc erps sn E n B oe * / / IsataeAgrtmaaeesojc fo prmtrecdn / ntnit loihPrmtr bet rm aaee noig / otie fo Bb / band rm o Agrtmaaeesprm =Agrtmaaeesgtntne"E"; loihPrmtr aas loihPrmtr.eIsac(DS) prm.ntecddaas; aasii(noePrm) aieihr=Cpe.eIsac(DSCCPC5adn"; lcCpe ihrgtntne"E/B/KSPdig) aieihrii(ihrDCYTMD,aieeKy prm) lcCpe.ntCpe.ERP_OE lcDse, aas; rcvrd=aieihrdFnlcpetx) eoee lcCpe.oia(ihret; i (jv.tlAry.qasceret rcvrd) f !aaui.raseul(latx, eoee) trwnwEcpin"E i CCmd rcvrdtx i "+ ho e xeto(DS n B oe eoee et s "ifrn fo ceret) dfeet rm latx"; Sse.u.rnl(DSi CCmd rcvrdtx i "+ ytmotpitn"E n B oe eoee et s "aea ceret) sm s latx"; } / * *Cnet abt t hxdgtadwie t tesple bfe ovrs ye o e ii n rts o h upid ufr * / piaevi bt2e(yeb SrnBfe bf { rvt od yehxbt , tigufr u) ca[ hxhr ={'' '' '' '' '' '' '' '' '' hr] eCas 0, 1, 2, 3, 4, 5, 6, 7, 8, '' '' '' '' '' '' ''} 9, A, B, C, D, E, F ; ithg =(b&0f)> 4; n ih ( x0 > ) itlw=( &00) n o b xf; bfapn(eCashg]; u.pedhxhr[ih) bfapn(eCaslw) u.pedhxhr[o]; } / * *Cnet abt aryt hxsrn ovrs ye ra o e tig * / piaeSrn tHxtigbt[ bok { rvt tig oeSrn(ye] lc) SrnBfe bf=nwSrnBfe(; tigufr u e tigufr) itln=boklnt; n e lc.egh fr(n i=0 i<ln i+ { o it ; e; +) bt2e(lc[] bf; yehxboki, u) i ( <ln1 { f i e-) bfapn(:) u.ped""; } } rtr bftSrn(; eun u.otig) } / * *Pit teuaeo ti ts. rns h sg f hs et * / piaevi uae){ rvt od sg( Sse.r.rn(DKygemn uae "; ytmerpit"HeAreet sg: ) Sse.r.rnl([gn"; ytmerpitn"-e]) } / Te12 btDfi-ela mdlsvle ue b SI / h 04 i ifeHlmn ouu aus sd y KP piaesai fnlbt si12Mdlsye[ ={ rvt ttc ia ye kp04ouuBts] (ye0F,(ye08,(ye0F,(ye05, bt)x4 bt)x8 bt)xD bt)x8 (ye04,(ye04,(ye0D,(ye0C, bt)xE bt)x9 bt)xB bt)xD (ye02,(ye0B,(ye09,(ye0E, bt)x0 bt)x4 bt)xD bt)x4 (ye09,(ye00,(ye03,(ye06, bt)x1 bt)x7 bt)x6 bt)xB (ye03,(ye06,(ye03,(ye00, bt)x3 bt)xC bt)x8 bt)xD (ye04,(ye01,(ye00,(ye07, bt)x5 bt)xD bt)xF bt)xC (ye08,(ye0B,(ye01,(ye07, bt)x8 bt)x3 bt)xC bt)xC (ye05,(ye02,(ye08,(ye0F, bt)xB bt)xD bt)xE bt)x6 (ye0F,(ye0C,(ye02,(ye0C, bt)x3 bt)x9 bt)x3 bt)x0 (ye04,(ye0F,(ye0A,(ye05, bt)x3 bt)x0 bt)x5 bt)xB (ye01,(ye08,(ye08,(ye0B, bt)x8 bt)xD bt)xE bt)xB
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 55/63
5/24/12
(ye05,(ye08,(ye0B,(ye05, bt)x5 bt)xC bt)x8 bt)xD (ye03,(ye0D,(ye03,(ye0F, bt)x8 bt)x3 bt)x4 bt)xD (ye07,(ye01,(ye05,(ye04, bt)xC bt)x7 bt)x7 bt)x3 (ye0A,(ye01,(ye01,(ye06, bt)x3 bt)xD bt)x8 bt)xC (ye0D,(ye03,(ye02,(ye02, bt)xE bt)x3 bt)x1 bt)xC (ye0B,(ye02,(ye0F,(ye03, bt)x5 bt)xA bt)xF bt)xC (ye0E,(ye0B,(ye02,(ye04, bt)x1 bt)x1 bt)x9 bt)x0 (ye01,(ye01,(ye08,(ye07, bt)x8 bt)x1 bt)xD bt)xC (ye08,(ye0A,(ye00,(ye07, bt)x4 bt)x7 bt)xA bt)x2 (ye0D,(ye08,(ye0C,(ye00, bt)x6 bt)x6 bt)x4 bt)x3 (ye01,(ye0C,(ye00,(ye02, bt)x9 bt)x8 bt)x7 bt)x9 (ye07,(ye0C,(ye09,(ye00, bt)xA bt)xA bt)x5 bt)xC (ye0D,(ye09,(ye09,(ye0A, bt)x9 bt)x6 bt)xF bt)xB (ye0D,(ye00,(ye05,(ye09, bt)x0 bt)xA bt)x0 bt)xB (ye00,(ye04,(ye0D,(ye00, bt)x2 bt)x6 bt)x3 bt)x8 (ye03,(ye06,(ye0A,(ye05, bt)xD bt)x6 bt)x4 bt)xD (ye04,(ye09,(ye09,(ye07, bt)x1 bt)xF bt)xC bt)xC (ye0B,(ye08,(ye04,(ye02, bt)xD bt)x9 bt)xB bt)x2 (ye01,(ye02,(ye0B,(ye0A, bt)x9 bt)x6 bt)xA bt)xB (ye0A,(ye05,(ye0C,(ye05, bt)x2 bt)xE bt)x3 bt)x5 (ye0E,(ye02,(ye07,(ye0C bt)x9 bt)xF bt)x8 bt)x7 } ; / TeSI 12 btmdls / h KP 04 i ouu piaesai fnlBgnee si12Mdls rvt ttc ia iItgr kp04ouu =nwBgnee(,si12Mdlsye) e iItgr1 kp04ouuBts; / Tebs ue wt teSI 12 btmdls / h ae sd ih h KP 04 i ouu piaesai fnlBgnee si12Bs =Bgnee.auO() rvt ttc ia iItgr kp04ae iItgrvlef2; }
ipr jv.o* mot aai.; ipr jv.ahBgnee; mot aamt.iItgr ipr jv.euiy* mot aascrt.; ipr jv.euiyse.; mot aascrt.pc* ipr jv.euiyitrae.; mot aascrt.nefcs* ipr jvxcyt.; mot aa.rpo* ipr jvxcyt.pc* mot aa.rpose.;
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 56/63
5/24/12
ipr jvxcyt.nefcs* mot aa.rpoitrae.; ipr cmsncyt.rvdrSnC; mot o.u.rpopoie.uJE /* * *Ti pormeeue teDfi-ela kyareetpooo hs rga xcts h ifeHlmn e gemn rtcl *bten3pris Aie Bb adCrl ewe ate: lc, o, n ao. * *W uetesm 12-i piemdlsadbs gnrtrta ae e s h ae 04bt rm ouu n ae eeao ht r *ue b SI. sd y KP * / pbi casDKygemn3{ ulc ls HeAreet piaeDKygemn3){ rvt HeAreet( } pbi sai vi mi(tigag[){ ulc ttc od anSrn rv] ty{ r DKygemn3kyge =nwDKygemn3) HeAreet eAre e HeAreet(; kyge.u(; eArern) }cth(xeto e { ac Ecpin ) Sse.r.rnl(Err "+e; ytmerpitn"ro: ) Sse.xt1; ytmei() } } piaevi rn)trw Ecpin{ rvt od u( hos xeto DPrmtrpcdSiPrmpc HaaeeSe hkpaaSe; Sse.u.rnl(UigSI Dfi-ela prmtr"; ytmotpitn"sn KP ifeHlmn aaees) dSiPrmpc=nwDPrmtrpcsi12Mdls si12Bs) hkpaaSe e HaaeeSe(kp04ouu, kp04ae; / AiecetshronD kypi / lc rae e w H e ar Sse.u.rnl(AIE Gnrt D kyar..) ytmotpitn"LC: eeae H epi ."; Kyareeao aiepiGn=Kyareeao.eIsac(D"; ePiGnrtr lcKare ePiGnrtrgtntne"H) aiepiGniiilz(hkpaaSe) lcKare.ntaiedSiPrmpc; Kyaraiepi =aiepiGngnrtKyar) ePi lcKar lcKare.eeaeePi(; / BbcetshsonD kypi / o rae i w H e ar Sse.u.rnl(BB Gnrt D kyar..) ytmotpitn"O: eeae H epi ."; Kyareeao bbpiGn=Kyareeao.eIsac(D"; ePiGnrtr oKare ePiGnrtrgtntne"H) bbpiGniiilz(hkpaaSe) oKare.ntaiedSiPrmpc; Kyarbbpi =bbpiGngnrtKyar) ePi oKar oKare.eeaeePi(; / CrlcetshronD kypi / ao rae e w H e ar Sse.u.rnl(CRL Gnrt D kyar..) ytmotpitn"AO: eeae H epi ."; Kyareeao crlpiGn=Kyareeao.eIsac(D"; ePiGnrtr aoKare ePiGnrtrgtntne"H) crlpiGniiilz(hkpaaSe) aoKare.ntaiedSiPrmpc; Kyarcrlpi =crlpiGngnrtKyar) ePi aoKar aoKare.eeaeePi(;
/ Aieiiilz / lc ntaie Sse.u.rnl(AIE Iiilz ..) ytmotpitn"LC: ntaie ."; Kygemn aieeAre=Kygemn.eIsac(D"; eAreet lcKyge eAreetgtntne"H) aieeAreii(lcKargtrvt() lcKyge.ntaiepi.ePiae); / Bbiiilz / o ntaie Sse.u.rnl(BB Iiilz ..) ytmotpitn"O: ntaie ."; Kygemn bbeAre=Kygemn.eIsac(D"; eAreet oKyge eAreetgtntne"H) bbeAreii(oKargtrvt() oKyge.ntbbpi.ePiae); / Crliiilz / ao ntaie Sse.u.rnl(CRL Iiilz ..) ytmotpitn"AO: ntaie ."; Kygemn crleAre=Kygemn.eIsac(D"; eAreet aoKyge eAreetgtntne"H) crleAreii(aoKargtrvt() aoKyge.ntcrlpi.ePiae);
/ Aieue Crlspbi ky / lc ss ao' ulc e Kya =aieeAredPaecrlpi.ePbi(,fle; e c lcKyge.ohs(aoKargtulc) as) / Bbue Aiespbi ky / o ss lc' ulc e Kyb =bbeAredPaeaiepi.ePbi(,fle; e a oKyge.ohs(lcKargtulc) as)
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 57/63
5/24/12
/ Aieue Crlsrsl fo aoe / lc ss ao' eut rm bv aieeAredPaec,tu) lcKyge.ohs(b re; / Bbue Aiesrsl fo aoe / o ss lc' eut rm bv bbeAredPaea,tu) oKyge.ohs(c re; / Crlue Bbsrsl fo aoe / ao ss o' eut rm bv crleAredPaeb,tu) aoKyge.ohs(a re;
/ Aie BbadCrlcmuetersces / lc, o n ao opt hi ert bt[ aiehrdert=aieeAregnrtSce(; ye] lcSaeSce lcKyge.eeaeert) Sse.u.rnl(Aiesce:"+tHxtigaiehrdert) ytmotpitn"lc ert oeSrn(lcSaeSce); bt[ bbhrdert=bbeAregnrtSce(; ye] oSaeSce oKyge.eeaeert) Sse.u.rnl(Bbsce:"+tHxtigbbhrdert) ytmotpitn"o ert oeSrn(oSaeSce); bt[ crlhrdert=crleAregnrtSce(; ye] aoSaeSce aoKyge.eeaeert) Sse.u.rnl(Crlsce:"+tHxtigcrlhrdert) ytmotpitn"ao ert oeSrn(aoSaeSce);
/ CmaeAieadBb / opr lc n o i (jv.tlAry.qasaiehrdert bbhrdert) f !aaui.raseul(lcSaeSce, oSaeSce) trwnwEcpin"lc adBbdfe"; ho e xeto(Aie n o ifr) Sse.u.rnl(AieadBbaetesm"; ytmotpitn"lc n o r h ae) / CmaeBbadCrl / opr o n ao i (jv.tlAry.qasbbhrdert crlhrdert) f !aaui.raseul(oSaeSce, aoSaeSce) trwnwEcpin"o adCrldfe"; ho e xeto(Bb n ao ifr) Sse.u.rnl(BbadCrlaetesm"; ytmotpitn"o n ao r h ae) }
/ * *Cnet abt t hxdgtadwie t tesple bfe ovrs ye o e ii n rts o h upid ufr * / piaevi bt2e(yeb SrnBfe bf { rvt od yehxbt , tigufr u) ca[ hxhr ={'' '' '' '' '' '' '' '' '' hr] eCas 0, 1, 2, 3, 4, 5, 6, 7, 8, '' '' '' '' '' '' ''} 9, A, B, C, D, E, F ; ithg =(b&0f)> 4; n ih ( x0 > ) itlw=( &00) n o b xf; bfapn(eCashg]; u.pedhxhr[ih) bfapn(eCaslw) u.pedhxhr[o]; } / * *Cnet abt aryt hxsrn ovrs ye ra o e tig * / piaeSrn tHxtigbt[ bok { rvt tig oeSrn(ye] lc) SrnBfe bf=nwSrnBfe(; tigufr u e tigufr) itln=boklnt; n e lc.egh fr(n i=0 i<ln i+ { o it ; e; +) bt2e(lc[] bf; yehxboki, u) i ( <ln1 { f i e-) bfapn(:) u.ped""; } } rtr bftSrn(; eun u.otig) } / * *Pit teuaeo ti ts. rns h sg f hs et * / piaevi uae){ rvt od sg( Sse.r.rn(DKygemn uae "; ytmerpit"HeAreet sg: ) Sse.r.rnl([gn"; ytmerpitn"-e]) }
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 58/63
5/24/12
/ Te12 btDfi-ela mdlsvle ue b SI / h 04 i ifeHlmn ouu aus sd y KP piaesai fnlbt si12Mdlsye[ ={ rvt ttc ia ye kp04ouuBts] (ye0F,(ye08,(ye0F,(ye05, bt)x4 bt)x8 bt)xD bt)x8 (ye04,(ye04,(ye0D,(ye0C, bt)xE bt)x9 bt)xB bt)xD (ye02,(ye0B,(ye09,(ye0E, bt)x0 bt)x4 bt)xD bt)x4 (ye09,(ye00,(ye03,(ye06, bt)x1 bt)x7 bt)x6 bt)xB (ye03,(ye06,(ye03,(ye00, bt)x3 bt)xC bt)x8 bt)xD (ye04,(ye01,(ye00,(ye07, bt)x5 bt)xD bt)xF bt)xC (ye08,(ye0B,(ye01,(ye07, bt)x8 bt)x3 bt)xC bt)xC (ye05,(ye02,(ye08,(ye0F, bt)xB bt)xD bt)xE bt)x6 (ye0F,(ye0C,(ye02,(ye0C, bt)x3 bt)x9 bt)x3 bt)x0 (ye04,(ye0F,(ye0A,(ye05, bt)x3 bt)x0 bt)x5 bt)xB (ye01,(ye08,(ye08,(ye0B, bt)x8 bt)xD bt)xE bt)xB (ye05,(ye08,(ye0B,(ye05, bt)x5 bt)xC bt)x8 bt)xD (ye03,(ye0D,(ye03,(ye0F, bt)x8 bt)x3 bt)x4 bt)xD (ye07,(ye01,(ye05,(ye04, bt)xC bt)x7 bt)x7 bt)x3 (ye0A,(ye01,(ye01,(ye06, bt)x3 bt)xD bt)x8 bt)xC (ye0D,(ye03,(ye02,(ye02, bt)xE bt)x3 bt)x1 bt)xC (ye0B,(ye02,(ye0F,(ye03, bt)x5 bt)xA bt)xF bt)xC (ye0E,(ye0B,(ye02,(ye04, bt)x1 bt)x1 bt)x9 bt)x0 (ye01,(ye01,(ye08,(ye07, bt)x8 bt)x1 bt)xD bt)xC (ye08,(ye0A,(ye00,(ye07, bt)x4 bt)x7 bt)xA bt)x2 (ye0D,(ye08,(ye0C,(ye00, bt)x6 bt)x6 bt)x4 bt)x3 (ye01,(ye0C,(ye00,(ye02, bt)x9 bt)x8 bt)x7 bt)x9 (ye07,(ye0C,(ye09,(ye00, bt)xA bt)xA bt)x5 bt)xC (ye0D,(ye09,(ye09,(ye0A, bt)x9 bt)x6 bt)xF bt)xB (ye0D,(ye00,(ye05,(ye09, bt)x0 bt)xA bt)x0 bt)xB (ye00,(ye04,(ye0D,(ye00, bt)x2 bt)x6 bt)x3 bt)x8 (ye03,(ye06,(ye0A,(ye05, bt)xD bt)x6 bt)x4 bt)xD (ye04,(ye09,(ye09,(ye07, bt)x1 bt)xF bt)xC bt)xC (ye0B,(ye08,(ye04,(ye02, bt)xD bt)x9 bt)xB bt)x2 (ye01,(ye02,(ye0B,(ye0A, bt)x9 bt)x6 bt)xA bt)xB (ye0A,(ye05,(ye0C,(ye05, bt)x2 bt)xE bt)x3 bt)x5 (ye0E,(ye02,(ye07,(ye0C bt)x9 bt)xF bt)x8 bt)x7 } ; / TeSI 12 btmdls / h KP 04 i ouu piaesai fnlBgnee si12Mdls rvt ttc ia iItgr kp04ouu =nwBgnee(,si12Mdlsye) e iItgr1 kp04ouuBts; / Tebs ue wt teSI 12 btmdls / h ae sd ih h KP 04 i ouu piaesai fnlBgnee si12Bs =Bgnee.auO() rvt ttc ia iItgr kp04ae iItgrvlef2; }
5/24/12
*POIS O BSNS ITRUTO)HWVRCUE ADO AYTER O RFT; R UIES NERPIN OEE ASD N N N HOY F *LAIIY WEHRI CNRC,SRC LAIIY O TR (NLDN IBLT, HTE N OTAT TIT IBLT, R OT ICUIG *NGIEC O OHRIE AIIGI AYWYOTO TEUEO TI ELGNE R TEWS) RSN N N A U F H S F HS *SFWR,EE I AVSDO TEPSIIIYO SC DMG. OTAE VN F DIE F H OSBLT F UH AAE * /
ipr jv.euiy* mot aascrt.; ipr jvxcyt.; mot aa.rpo* ipr jvxcyt.pc* mot aa.rpose.; /* * *Ti pormgnrtsaBofs ky rtivsisrwbts ad hs rga eeae lwih e, eree t a ye, n *te risatae aBofs kyfo tekybts hn entnits lwih e rm h e ye. *Terisatae kyi ue t iiilz aBofs cpe fr h entnitd e s sd o ntaie lwih ihr o *ecyto. nrpin * / pbi casBofsKy{ ulc ls lwihe pbi sai vi mi(tig]ag)trw Ecpin{ ulc ttc od anSrn[ rs hos xeto Kyeeao ke =Kyeeao.eIsac(Bofs"; eGnrtr gn eGnrtrgtntne"lwih) SceKyse =ke.eeaee(; erte ky gngnrtKy) bt[ rw=se.eEcdd) ye] a kygtnoe(; SceKypcseSe =nwSceKypcrw "lwih) erteSe kypc e erteSe(a, Bofs"; Cpe cpe =Cpe.eIsac(Bofs"; ihr ihr ihrgtntne"lwih) cpe.ntCpe.NRP_OE seSe) ihrii(ihrECYTMD, kypc; bt[ ecytd= ye] nrpe cpe.oia(Ti i js a eape.eBts); ihrdFnl"hs s ut n xml"gtye() } }
HMAC-MD5 Example
/ * *Cprgt()20,Oal ado isaflae.Alrgt rsre. oyih c 06 rce n/r t fiits l ihs eevd * *Rdsrbto aduei suc adbnr frs wt o wtot eitiuin n s n ore n iay om, ih r ihu *mdfcto,aepritdpoie ta tefloigcniin oiiain r emte rvdd ht h olwn odtos *aemt r e: * * -Rdsrbtoso suc cd ms rti teaoecprgt eitiuin f ore oe ut ean h bv oyih * ntc,ti ls o cniin adtefloigdslie. oie hs it f odtos n h olwn icamr * * -Rdsrbtosi bnr fr ms rpoueteaoecprgt eitiuin n iay om ut erdc h bv oyih * ntc,ti ls o cniin adtefloigdslie i te oie hs it f odtos n h olwn icamr n h * dcmnainado ohrmtraspoie wt tedsrbto. ouetto n/r te aeil rvdd ih h itiuin * * -Nihrtenm o Oal nrtenmso is ete h ae f rce o h ae f t * cnrbtr myb ue t edreo pooepout drvd otiuos a e sd o nos r rmt rdcs eie * fo ti sfwr wtotseii pirwitnpriso. rm hs otae ihu pcfc ro rte emsin * *TI SFWR I POIE B TECPRGTHLESADCNRBTR "S HS OTAE S RVDD Y H OYIH ODR N OTIUOS A *I"ADAYEPESO IPIDWRATE,ICUIG BTNTLMTDT, S N N XRS R MLE ARNIS NLDN, U O IIE O *TEIPIDWRATE O MRHNAIIYADFTESFRAPRIUA H MLE ARNIS F ECATBLT N INS O ATCLR *PROEAEDSLIE. I N EETSALTECPRGTONRO UPS R ICAMD N O VN HL H OYIH WE R *CNRBTR B LAL FRAYDRC,IDRC,ICDNA,SEIL OTIUOS E IBE O N IET NIET NIETL PCA, *EEPAY O CNEUNILDMGS(NLDN,BTNTLMTDT, XMLR, R OSQETA AAE ICUIG U O IIE O *POUEETO SBTTT GOSO SRIE;LS O UE DT,O RCRMN F USIUE OD R EVCS OS F S, AA R *POIS O BSNS ITRUTO)HWVRCUE ADO AYTER O RFT; R UIES NERPIN OEE ASD N N N HOY F *LAIIY WEHRI CNRC,SRC LAIIY O TR (NLDN IBLT, HTE N OTAT TIT IBLT, R OT ICUIG *NGIEC O OHRIE AIIGI AYWYOTO TEUEO TI ELGNE R TEWS) RSN N N A U F H S F HS *SFWR,EE I AVSDO TEPSIIIYO SC DMG. OTAE VN F DIE F H OSBLT F UH AAE * / ipr jv.euiy* mot aascrt.; ipr jvxcyt.; mot aa.rpo* /* * *Ti pormdmntae hwt gnrt asce-e ojc fr hs rga eosrts o o eeae ertky bet o
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 60/63
5/24/12
*HA-D,adiiilz a HA-D ojc wt i. MCM5 n ntaie n MCM5 bet ih t * / pbi casiiMc{ ulc ls nta pbi sai vi mi(tig]ag)trw Ecpin{ ulc ttc od anSrn[ rs hos xeto / Gnrt sce kyfrHA-D / eeae ert e o MCM5 Kyeeao k =Kyeeao.eIsac(HaM5) eGnrtr g eGnrtrgtntne"mcD"; SceKys =k.eeaee(; erte k ggnrtKy) / Gtisac o Mcojc ipeetn HA-D,ad / e ntne f a bet mlmnig MCM5 n / iiilz i wt teaoesce ky / ntaie t ih h bv ert e Mcmc=Mcgtntne"mcD"; a a a.eIsac(HaM5) mcii(k; a.nts) bt[ rsl =mcdFnl"iTee.eBts); ye] eut a.oia(H hr"gtye() } }
ipr jv.tl* mot aaui.; ipr jv.o* mot aai.; ipr jv.euiy* mot aascrt.; pbi casRaPswr { ulc ls edasod /* * *Ra apswr fo teIpttem"n. ed asod rm h nuSra i" *<> p *A Srnsaeimtbe pswrssol b soe a a ary s tig r mual, asod hud e trd s n ra *o caatr,wihcnb bakdotwe n lne nee. f hrces hc a e lne u hn o ogr edd *<> p *I tepoie Ipttemi teSse' Cnoe ti mto f h rvdd nuSra s h ytms osl, hs ehd *ue tennehigraPswr( mto o jv.oCnoe ss h o-con edasod) ehd f aai.osl *(e t JK6. I nt aflbc ipeetto i ue. nw o D ) f o, alak mlmnain s sd *<> p *NT: Frepstr proe,adbcuesm apiain d OE o xoioy upss n eas oe plctos o *ntudrtn mlibt caatr,ol 8btACIpswrs o nesad ut-ye hrces ny -i SI asod *aehnldhr. r ade ee *<> p
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 61/63
5/24/12
*NT: I aScrtMngri ue,tedfutsadr OE f euiyaae s sd h eal tnad *jv.oiyfl fudi SnsJK(.. aaplc ie on n u' D ie *<aahm>lbscrt/aaplc)alw raigte jv-oe/i/euiyjv.oiy los edn h *ln.eaao poet. I yu evrneti dfeet ti iesprtr rpry f or niomn s ifrn, hs *cd wl ne t b gatdteaporaepiiee oe il ed o e rne h prpit rvlg. * *@aa prm i n * teIpttemue t oti tepswr. h nuSra sd o ban h asod * *@eun Acaatrarycnann tepswr o psprs, rtr hrce ra otiig h asod r ashae * nticuigteln-emnto caatr, o nldn h ietriain hrces * o nl i a edo sra hsbe rahd r ul f n n f tem a en ece. * *@hos IEcpin trw Oxeto * i a IOpolmocr f n / rbe cus * / pbi sai fnlca[ raPswr(nuSra i) ulc ttc ia hr] edasodIpttem n trw IEcpin{ hos Oxeto / * *I aalbe drcl uetejv.oCnoecast f vial, iety s h aai.osl ls o *aodcaatrehig vi hrce con. * / i (n= Sse.n& Sse.osl( ! nl){ f i = ytmi & ytmcnoe) = ul / raPswr rtrs" i yujs pitETR / edasod eun " f o ut rn NE, rtr Sse.osl(.edasod) eun ytmcnoe)raPswr(; } / * *I acnoei ntaalbe ra teIpttem f osl s o vial, ed h nuSra *drcl. Ti apoc mycuepswr ehig iety hs prah a as asod con. * *Snedfeetoeaigsseshv dfeetEdO-ie ic ifrn prtn ytm ae ifrn n-fLn *(O)sqecs ti agrtmsol alwfr EL eune, hs loih hud lo o *pafr-needn ipeettos TpclELsqecs ltomidpnet mlmnain. yia O eune *aeasnl ln fe (\',o acrig rtr/ieed r ige ie ed 'n) r arae eunlnfe *cmiain(\\'. Hwvr sm O' ueasnl obnto 'rn) oee, oe Ss s ige *acrig rtr (\',wihcmlctspraiiy arae eun 'r) hc opiae otblt. * *Snew mynthv teaiiyt ps btsbc it te ic e a o ae h blt o uh ye ak no h *Ipttem aohrapoc i ue hr. Tejvdcfr nuSra, nte prah s sd ee h aao o *j v . a g S s e . e P o e t e ( seiista a a l n . y t m g t r p r i s ) pcfe ht *testo sse poete wl cnanasse-pcfc h e f ytm rpris il oti ytmseii *vlefrte"iesprtr. Sa frti caatr au o h ln.eaao" cn o hs hrce *sqec isedo hr-oigapriua sqec. eune nta f adcdn atclr eune * / / * *Ecoetegtrpryi adPiiee bokt mnmz nls h ePoet n orvlgd lc o iiie *tecl sakpriso rqie. h al tc emsin eurd * / ca [ EL=AcsCnrle.orvlgd hr ] O cesotolrdPiiee( nwPiieeAto<hr]( { e rvlgdcinca[>) pbi ca[ rn){ ulc hr] u( Srn s=Sse.ePoet(ln.eaao"; tig ytmgtrpry"iesprtr) / Solnthpe. / hud' apn i ( = nl){ f s = ul trwnwRniexeto( ho e utmEcpin "iesprtrntdfnd) ln.eaao o eie"; } rtr stCaAry) eun .ohrra(; } }; ) ca [ bfe =nwca[2] hr ] ufr e hr18; ty{ r itln=0 n e ; / lno dt i bfe. / e f aa n ufr boendn =fle ola oe as; / fudteELsqec / on h O eune itb n ; / bt ra / ye ed wie(dn){ hl !oe / *
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html 62/63
5/24/12
*ralci ncsay elo f eesr * / i (e > bfe.egh { f ln = ufrlnt) ca [ nwufr=nwca[e +18; hr ] ebfe e hrln 2] Sse.racp(ufr 0 nwufr 0 ln; ytmaryoybfe, , ebfe, , e) Ary.ilbfe,''; rasfl(ufr ) bfe =nwufr ufr ebfe; } / * *Edo-tem n-fSra? * / i (b=i.ed) = -){ f ( nra() = 1 / Rtr a mc a w hv,nl ohrie / eun s uh s e ae ul tews. i (e = 0 { f ln = ) rtr nl; eun ul } bek ra; }es { le / * *NT: I tesml PEeapehr, OE n h ipe B xml ee *ol 8btACIcaatr aehnld ny i SI hrces r ade. * / bfe[e+]=(hr b ufrln+ ca) ; } / * *cekfrteELsqec. D w hv eog bts hc o h O eune o e ae nuh ye? * / i (e > ELlnt){ f ln = O.egh iti=0 n ; fr( =0 i<ELlnt;i+ { o i ; O.egh +) i (ufrln-ELlnt +i ! ELi){ f bfe[e O.egh ] = O[] bek ra; } } dn =( = ELlnt) oe i = O.egh; } } / * *I w fudteEL srpteELcas f e on h O, ti h O hr. * / ca [ rsl =nwca[oe?ln-ELlnt :ln; hr ] eut e hrdn e O.egh e] Sse.racp(ufr 0 rsl,0 rsl.egh; ytmaryoybfe, , eut , eutlnt) rtr rsl; eun eut }fnly{ ial / * *Zr ottebfe. eo u h ufr * / i (ufr! nl){ f bfe = ul Ary.ilbfe,''; rasfl(ufr ) } } } }
Java Technology
Copyright 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us
docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
63/63