iaik.cms
Class SecurityProvider

java.lang.Object
  extended by iaik.cms.SecurityProvider
Direct Known Subclasses:
IaikProvider

public class SecurityProvider
extends Object

This class centralizes all cryptographic operations used for CMS.

With this class IAIK-CMS adopts the SecurityProvider model introduced by the IAIK-SSL library iSaSiLk. The SecurityProvider model used here is similar to that of iSaSiLk except for a the following changes:

This class is the main class of the IAIK-CMS SecurityProvider model. It itself provides default implementations of all cryptographic operations required by CMS, expect for Ephemeral Static Diffie Hellman. Unfortunately there is no general way to initialize a KeyPairGenerator with algorithm parameters as required when creating a originator ESDH key pair with domain parameters matching to those of the recipient public key. So the default implementation of method generateKeyAgreementKeyPair(AlgorithmID keyAgreeAlgorithm, PublicKey otherKey) has to throw an exception and has to be implemented if using another cryptographic provider than IAIK. The same applies to method #createSharedKeyEncryptionKey(AlgorithmID, PrivateKey, PublicKey, AlgorithmID, int, byte[], String) createSharedKeyEncryptionKey} which cannot handle an ESDHKeyAgreement in provider independent way. So at the current state it might be preferable to override all ESDH related methods when intending to use another provider than IAIK.

With class IaikProvider IAIK-CMS contains an SecurityProvider implemention for the IAIK cryptography provider of the crypto toolkit IAIK-JCE. Please note the difference: The IAIK provider is a JCA/JCE cryptography provider supplying cryptographic engines; Class IaikProvider is an IAIK-CMS SecurityProvider implementation that makes the cryptographic engines of the IAIK JCA/JCE cyrptography provider available for IAIK-CMS.

Per default IAIK-CMS is configured to look if the IAIK cryptography provider is available. If yes, it uses the IaikProvider as SecurityProvider. If not it uses an instance of this class. So if you want to use the IAIK provider you do not have to make any care about the SecurityProvider setting. However, if you do not want to use the IAIK provider for some reasons (e.g. you require a specific, e.g. smartcard depending, handling for some tasks) you have two options:

  1. Use the default SecurityProvider implementation this class provides by setting it as SecurityProvider to be used:
         SecurityProvider.setSecurityProvider(new SecurityProvider());
         
  2. Implementing your own SecurityProvider for the required cryptographic tasks and installing it as SecurityProvider to be used:
         MySecurityProvider mySecurityProvider = ...;
         SecurityProvider.setSecurityProvider(mySecurityProvider);
         
If choosing the second option from above basically you may follow one of two ways for implementing your own SecurityProvider:
  1. You want to mainly use the IAIK JCE as a cryptography provider and use another provider just for a few algorithms. For example, you want to use a smartcard requiring a particular handling for RSA signature calculatuion.
  2. You do not want to use the IAIK JCE at all and use only some other provider.
In the first case the easiest thing to do is to subclass the IaikProvider class, e.g.:
 public class MySecurityProvider extends IaikProvider {

   public byte[] calculateSignatureFromSignedAttributes(AlgorithmID signatureAlgorithm, 
     AlgorithmID digestAlgorithm, PrivateKey privateKey, byte[] signedAttributes) 
     throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
 
     // get the implementation name: RSA? (note that CMS indicates rsaEncryption as Signature algorithm)
     String implementationName = signatureAlgorithm.getImplementationName();
     if (implementationName.equals(IMPLEMENTATION_NAME_RSA)) {
       // let the smartcard calculate the signature value
       byte[] signatureValue = ...;
     } else {
       return super.calculateSignatureFromSignedAttributes(signatureAlgorithm, 
         digestAlgorithm, privateKey, signedAttributes);
     } 
   } 
 }
 
In the second case, i.e. you want to use a different provider alltogether and not use the IAIK JCE at all (for whatever reason ;-) it will be easiest to start with the SecurityProvider class and override those methods where you cannot use the default implementation.

Note that you also may install a SecurityProvider per CMS object. To, for instance, use one specific SecurityProvider only for one specific SignedDataStream object, you may use its setSecurityProvider method, e.g.:

 MySecurityProvider myProvider = ...;
 SignedDataStream signedData = ...;
 signedData.setSecurityProvider(myProvider);
 
Now myProvider will be used for any cryptographic operation required by this one specific SignedDataStream object. If any of the CMS objects (SignerInfos) belonging to this SignedDataStream object need a SecurityProvider, they will use myProvider, too; except for those, who already have installed their own SecurityProvider. However, SecurityProviders are only forwarded from "higher" to "lower" objects, e.g.: if a SignedData(Stream) object has its own SecurityProvider it forwards it to its SignerInfos objects (as long as they do not already have their own SecurityProviders), but if a SignerInfo with its own SecurityProvider is added to a SignedData(Stream) object that has no SecurityProvider installed, the SecurityProvider of the SignerInfo is not forwarded to the SignedData(Stream) object. In this case the SignedDataStream object will use the default, system-wide installed SecurityProvider (which should be available in any case).
If you want to use a specific SecurityProvider for a specific CMS object please look at the Javadoc if you may add it by using method setSecurityProvider (if present), or if you already may install it via the constructor (which may required when, for instance, parsing a CMS object that needs cryptographic engines already during the parsing procedure (e.g. for digest calculation initialization when parsing a SignedData object)).

See Also:
IaikProvider

Field Summary
static String ALG_CIPHER_RSA
          Constant string RSA/ECB/PKCS1Padding.
static String ALG_CIPHER_RSA_DECRYPT
          Constant string RSA/ECB/PKCS1Padding/Decrypt.
static String ALG_CIPHER_RSA_ENCRYPT
          Constant string RSA/ECB/PKCS1Padding/Encrypt.
static String ALG_CIPHER_RSA_SIGN
          Constant string RSA/ECB/PKCS1Padding/Sign.
static String ALG_CIPHER_RSA_VERIFY
          Constant string RSA/ECB/PKCS1Padding/Verify.
static String ALG_DIGEST_MD5
          Constant string MD5.
static String ALG_DIGEST_SHA
          Constant string SHA.
static String ALG_HMAC_MD5
          Constant string HmacMD5.
static String ALG_HMAC_SHA
          Constant string HmacSHA1.
static String ALG_KEYEX_DH
          Constant string DH
static String ALG_KEYEX_ESDH
          Constant string ESDH
static String ALG_KEYEX_SSDH
          Constant string SSDH
static String ALG_SIGNATURE_RAWDSA
          Constant string RawDSA.
static String ALG_SIGNATURE_RAWECDSA
          Constant string RawECDSA.
static String ALG_SIGNATURE_RAWECDSA_PLAIN
          Constant string RawECDSAPlain.
static String ALG_SIGNATURE_RAWRSAPSS
          Constant string RawRSAPSS.
static String ALG_SIGNATURE_SHADSA
          Constant string SHA1withDSA.
static int CIPHER_DECRYPT
          Constant for a cipher object which is to be initialized for decryption.
static int CIPHER_ENCRYPT
          Constant for a cipher object which is to be initialized for encryption.
static int CIPHER_NONE
          Constant for a cipher object which is not to be initialized.
static int CIPHER_UNWRAP
          Constant for a cipher object which is to be initialized for decryption.
static int CIPHER_WRAP
          Constant for a cipher object which is to be initialized for key wrap.
static int COMPRESS
          Constant for a compress engine to be initialized for compression.
static int DECOMPRESS
          Constant for a compress engine to be initialized for decompression.
static String IMPLEMENTATION_NAME_DSA
          Constant string SHA-1/DSA.
static String IMPLEMENTATION_NAME_ECDSA
          Constant string ECDSA.
static String IMPLEMENTATION_NAME_ECDSA_PLAIN
          Constant string ECDSAPlain.
static String IMPLEMENTATION_NAME_PBKDF2
          Constant string PBKDF2.
static String IMPLEMENTATION_NAME_PWRI_KEK
          Constant string PWRI-KEK.
static String IMPLEMENTATION_NAME_RSA
          Constant string RSA.
static String IMPLEMENTATION_NAME_RSA_OAEP
          Constant string RSAES-OAEP.
static String IMPLEMENTATION_NAME_RSA_PSS
          Constant string RSASSA-PSS.
protected  String providerName_
          The name of the underlying cryptographic provider, if installed.
protected  SecureRandom random_
          The SecureRandom.
static int SIGNATURE_NONE
          Constant for a signature object which is not to be initialized.
static int SIGNATURE_SIGN
          Constant for a signature object which is to be initialized for signing.
static int SIGNATURE_VERIFY
          Constant for a signature object which is to be initialized for verification.
 
Constructor Summary
SecurityProvider()
          Default constructor.
SecurityProvider(String providerName)
          Cretes a SecurityProvider for the given cryptographic provider to use.
 
Method Summary
 byte[] calculateMac(AlgorithmID algorithmID, Key key, AlgorithmParameterSpec paramSpec, byte[] data)
          Calculates a Message Authentication Code on the given data.
 byte[] calculateSharedSecret(AlgorithmID keyAgreementAlgorithm, Key key, Key otherKey, AlgorithmParameterSpec paramSpec)
          This method uses the specified KeyAgreement algorithm to calculate a shared secret between the owners of the given private and public key.
 byte[] calculateSignatureFromHash(AlgorithmID signatureAlgorithm, AlgorithmID digestAlgorithm, PrivateKey privateKey, byte[] digest)
          Calculates the signature value for a CMS SignerInfo over the given digest value with the given algorithm using the supplied private key.
 byte[] calculateSignatureFromSignedAttributes(AlgorithmID signatureAlgorithm, AlgorithmID digestAlgorithm, PrivateKey privateKey, byte[] signedAttributes)
          Calculates the signature value for a CMS SignerInfo over the given signed attributes with the given algorithm using the supplied private key.
 void checkDomainParameters(PrivateKey myKey, PublicKey otherKey)
          Checks if the given private and public key agreement keys have the same domain parameters.
 byte[] compress(AlgorithmID compressAlg, byte[] data, int compressionMode)
          Uses the given compression algorithm to compress/decompress the supplied input data.
static int convertCipherMode(int mode)
          Converts the SecurityProvider Cipher mode to the javax.crypto Cipher mode.
 SecretKey createSharedKeyEncryptionKey(AlgorithmID keyAgreeAlg, PrivateKey myKey, PublicKey otherKey, AlgorithmID kea, int kekLength, byte[] ukm, String kekName)
          Create a shared secret key encryption key for the given key agree algorithm.
 SecretKey decryptKey(byte[] encryptedKey, AlgorithmID kea, PrivateKey recipientKey)
          Decrypts the given encrypted content encryption key for a KeyTransRecipientInfo.
 SecretKey decryptKey(byte[] encryptedKey, AlgorithmID kea, PrivateKey recipientKey, String cekAlgorithmName)
          Decrypts the given encrypted content encryption key for a KeyTransRecipientInfo.
 Key deriveKey(char[] password, AlgorithmID keyDerivationAlg, AlgorithmParameterSpec paramSpec)
          Uses the requested key derivation function to create a secret key from the supplied password.
 byte[] encryptKey(SecretKey cek, AlgorithmID kea, PublicKey recipientKey)
          Encrypts the given secret content encryption key for a KeyTransRecipientInfo.
 SecretKey generateKey(AlgorithmID algorithm, AlgorithmParameterSpec paramSpec)
          Generates a SecretKey for the requested algorithm.
 SecretKey generateKey(AlgorithmID algorithm, int keyLength)
          Generates a SecretKey for the requested algorithm.
 KeyPair generateKeyAgreementKeyPair(AlgorithmID keyAgreeAlgorithm, PublicKey otherKey)
          Generates a key pair with same domain parameters of the given public key for the given key agreement method.
 AlgorithmParameters getAlgorithmParameters(AlgorithmID algorithm)
          Gets the algorithm parameters from the given AlgorithmID.
 AlgorithmParameters getAlgorithmParameters(AlgorithmID algorithmID, String algorithm)
          Gets the algorithm parameters with the given name from the given AlgorithmID.
 AlgorithmParameters getAlgorithmParameters(String algorithm)
          Gets an AlgorithmParameters instance for the requested algorithm.
 AlgorithmParameterSpec getAlgorithmParameterSpec(AlgorithmID algID)
          Gets algorithm parameter specification from the given AlgorithmID.
 ASN1Object getASN1OriginatorPublicKey(PublicKey originatorPublicKey)
          Gets an ASN.1 representation of the provided originator public key.
 AuthCipherEngine getAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params, byte[] aad)
          Gets an AuthCipherEngine for authenticated data encryption.
 AuthCipherEngine getAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params, byte[] aad)
          Gets an AuthCipherEngine for authenticated data encryption.
 ByteArrayAuthCipherEngine getByteArrayAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params, byte[] aad)
          Gets a ByteArrayAuthCipherEngine for authenticated en/decrypting data supplied by some byte array.
 ByteArrayAuthCipherEngine getByteArrayAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params, byte[] aad)
          Gets a ByteArrayAuthCipherEngine for en/decrypting data supplied by some byte array.
 ByteArrayCipherEngine getByteArrayCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params)
          Gets a ByteArrayCipherEngine for en/decrypting data supplied by some byte array.
 ByteArrayCipherEngine getByteArrayCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params)
          Gets a ByteArrayCipherEngine for en/decrypting data supplied by some byte array.
 Cipher getCipher(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params)
          Returns the desired Cipher object for the requested algorithm.
 Cipher getCipher(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params)
          Returns the desired Cipher object for the requested algorithm.
 Cipher getCipher(String algorithm, int mode, Key key, AlgorithmParameters params)
          This method returns the desired Cipher object.
 Cipher getCipher(String algorithm, int mode, Key key, AlgorithmParameterSpec params)
          This method returns the desired Cipher object.
 byte[] getHash(AlgorithmID algorithm, byte[] data)
          Calculates the hash on the given data using the requested hash algorithm.
 InputStreamAuthCipherEngine getInputStreamAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params, byte[] aad)
          Gets an InputStreamAuthCipherEngine for authenticated en/decrypting data read from some input stream.
 InputStreamAuthCipherEngine getInputStreamAuthCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params, byte[] aad)
          Gets an InputStreamAuthCipherEngine for authenticated en/decrypting data read from some input stream.
 InputStreamCipherEngine getInputStreamCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameters params)
          Gets an InputStreamCipherEngine for en/decrypting data read from some input stream.
 InputStreamCipherEngine getInputStreamCipherEngine(AlgorithmID algorithm, int mode, Key key, AlgorithmParameterSpec params)
          Gets an InputStreamCipherEngine for en/decrypting data read from some input stream.
 InputStreamCompressEngine getInputStreamCompressEngine(AlgorithmID compressAlg, InputStream is, int compressionMode, int bufferSize)
          Gets an InputStreamCompressEngine for compressing/decompressing data read from some input stream.
 InputStreamHashEngine getInputStreamHashEngine(AlgorithmID algorithm, InputStream is)
          Returns an InputStreamHashEngine for calculating the hash value on the data supplied from the given input stream.
 InputStreamMacEngine getInputStreamMacEngine(AlgorithmID algorithm, Key key, AlgorithmParameterSpec paramSpec, InputStream is)
          Gets an InputStreamMacEngine for calculating a Message Authentication Code on data read from some input stream.
 KeyAgreement getKeyAgreement(AlgorithmID keyAgreementAlgorithm, Key key, AlgorithmParameterSpec paramSpec)
          This method returns the desired KeyAgreement object.
 KeyFactory getKeyFactory(AlgorithmID algorithm)
          This method returns the desired KeyFactory object.
 KeyGenerator getKeyGenerator(AlgorithmID algorithm, AlgorithmParameterSpec paramSpec)
          Returns a KeyGenerator for the requested algorithm.
 KeyGenerator getKeyGenerator(AlgorithmID algorithm, int keyLength)
          Return a KeyGenerator for the requested algorithm.
 int getKeyLength(Key key)
          Calculates the length of the given key.
 int getKeyLength(PrivateKey privKey)
          Calculates the length of the given private key.
 int getKeyLength(PublicKey pubKey)
          Calculates the length of the given public key.
 KeyPairGenerator getKeyPairGenerator(AlgorithmID algorithm)
          Return a KeyPairGenerator for the requested algorithm.
 Mac getMac(AlgorithmID algorithm, Key key, AlgorithmParameterSpec paramSpec)
          This method returns the desired MAC object.
 Mac getMac(String algorithm, Key key, AlgorithmParameterSpec paramSpec)
          This method returns the desired MAC object.
 MessageDigest getMessageDigest(AlgorithmID algorithm)
          This method returns the desired MessageDigest object.
 MessageDigest getMessageDigest(String algorithm)
          This method returns the desired MessageDigest object.
 AlgorithmID[] getMicAlgs(String micalg)
          Returns an array of AlgorithmIDs specified by the given micalg String.
 PublicKey getOriginatorPublicKey(ASN1Object obj)
          Decodes the OriginatorPublicKey from the given ASN1Object.
 OutputStreamCompressEngine getOutputStreamCompressEngine(AlgorithmID compressAlg, OutputStream os, int bufferSize)
          Gets an OutputStreamCompressEngine for compressing data written to some output stream.
 OutputStreamHashEngine getOutputStreamHashEngine(AlgorithmID algorithm, OutputStream os)
          Returns an OutputStreamHashEngine for calculating the hash value on the data supplied from the given output stream.
 OutputStreamMacEngine getOutputStreamMacEngine(AlgorithmID algorithm, Key key, AlgorithmParameterSpec paramSpec, OutputStream os)
          Gets an OutputStreamMacEngine for calculating a Message Authentication Code on data written to some output stream.
 Key getPBEKey(char[] password, AlgorithmID pbeAlg)
          Creates secret key from the supplied password using the specified PBE algorithm.
 String getProviderName()
          Gets the name of the underlying cryptographic provider.
 SecretKeyFactory getSecretKeyFactory(AlgorithmID algorithm)
          Return a SecretKeyFactory for the requested algorithm.
 SecureRandom getSecureRandom()
          Returns the random number generator.
static SecurityProvider getSecurityProvider()
          Returns the active SecurityProvider.
 Signature getSignature(AlgorithmID signatureAlgorithm, int mode, Key key)
          This method returns the desired Signature object.
 Signature getSignature(AlgorithmID signatureAlgorithm, int mode, Key key, AlgorithmParameterSpec paramSpec)
          This method returns the desired Signature object.
 Signature getSignature(String algorithm, int mode, Key key)
          This method returns the desired Signature object.
 Signature getSignature(String algorithm, int mode, Key key, AlgorithmParameterSpec paramSpec)
          This method returns the desired Signature object.
 void setSecureRandom(SecureRandom random)
          Sets the random number generator.
static void setSecurityProvider(SecurityProvider provider)
          Sets the global SecurityProvider.
static void setSignatureParameters(Signature signature, AlgorithmParameterSpec paramSpec)
          Sets the parametes for a Signature engine.
 SecretKey unwrapKey(byte[] wrappedCek, AlgorithmID kea, Key kek, AlgorithmParameters params, String cekAlgName)
          Unwraps the given wrapped (encrypted) secret content encryption key for a KEKRecipientInfo or KeyAgreeRecipientInfo, or PasswordRecipientInfo.
 boolean verifySignatureFromHash(AlgorithmID signatureAlgorithm, AlgorithmID digestAlgorithm, PublicKey publicKey, byte[] digest, byte[] signatureValue)
          Verifies the signature value of a CMS SignerInfo object with the given algorithm using the supplied public key.
 boolean verifySignatureFromSignedAttributes(AlgorithmID signatureAlgorithm, AlgorithmID digestAlgorithm, PublicKey publicKey, byte[] signedAttributes, byte[] signatureValue)
          Verifies the signature value of a CMS SignerInfo calculated over the given signed attributes with the given algorithm using the supplied public key.
 byte[] wrapKey(SecretKey cek, AlgorithmID kea, Key kek, AlgorithmParameters params)
          Wraps the given secret content encryption key for a KEKRecipientInfo or KeyAgreeRecipientInfo, or PasswordRecipientInfo.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SIGNATURE_NONE

public static final int SIGNATURE_NONE
Constant for a signature object which is not to be initialized.

See Also:
Constant Field Values

SIGNATURE_SIGN

public static final int SIGNATURE_SIGN
Constant for a signature object which is to be initialized for signing.

See Also:
Constant Field Values

SIGNATURE_VERIFY

public static final int SIGNATURE_VERIFY
Constant for a signature object which is to be initialized for verification.

See Also:
Constant Field Values

CIPHER_NONE

public static final int CIPHER_NONE
Constant for a cipher object which is not to be initialized.

See Also:
Constant Field Values

CIPHER_ENCRYPT

public static final int CIPHER_ENCRYPT
Constant for a cipher object which is to be initialized for encryption.

See Also:
Constant Field Values

CIPHER_DECRYPT

public static final int CIPHER_DECRYPT
Constant for a cipher object which is to be initialized for decryption.

See Also:
Constant Field Values

CIPHER_WRAP

public static final int CIPHER_WRAP
Constant for a cipher object which is to be initialized for key wrap.

See Also:
Constant Field Values

CIPHER_UNWRAP

public static final int CIPHER_UNWRAP
Constant for a cipher object which is to be initialized for decryption.

See Also:
Constant Field Values

COMPRESS

public static final int COMPRESS
Constant for a compress engine to be initialized for compression.

See Also:
Constant Field Values

DECOMPRESS

public static final int DECOMPRESS
Constant for a compress engine to be initialized for decompression.

See Also:
Constant Field Values

IMPLEMENTATION_NAME_DSA

public static final String IMPLEMENTATION_NAME_DSA
Constant string SHA-1/DSA. Implementation name of the DSA Signature engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_ECDSA

public static final String IMPLEMENTATION_NAME_ECDSA
Constant string ECDSA. Implementation name of the ECDSA Signature engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_ECDSA_PLAIN

public static final String IMPLEMENTATION_NAME_ECDSA_PLAIN
Constant string ECDSAPlain. Implementation name of the ECDSAPlain Signature engine. The signature value is encoded as (r || s) and not wrapped into a SEQUENCE as done by X9.62; see German BSI Technical Guideline TR-03111.

See Also:
Constant Field Values

IMPLEMENTATION_NAME_RSA_PSS

public static final String IMPLEMENTATION_NAME_RSA_PSS
Constant string RSASSA-PSS. Implementation name of the RSA-PSS Signature engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_RSA

public static final String IMPLEMENTATION_NAME_RSA
Constant string RSA. Implementation name of the RSA Cipher engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_RSA_OAEP

public static final String IMPLEMENTATION_NAME_RSA_OAEP
Constant string RSAES-OAEP. Implementation name of the RSA-OAEP Cipher engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_PBKDF2

public static final String IMPLEMENTATION_NAME_PBKDF2
Constant string PBKDF2. Implementation name of the PBKDF2 Cipher engine

See Also:
Constant Field Values

IMPLEMENTATION_NAME_PWRI_KEK

public static final String IMPLEMENTATION_NAME_PWRI_KEK
Constant string PWRI-KEK. Implementation name of the PWRI-KEK Cipher engine

See Also:
Constant Field Values

ALG_DIGEST_MD5

public static final String ALG_DIGEST_MD5
Constant string MD5. Used by the library with getMessageDigest().

See Also:
Constant Field Values

ALG_DIGEST_SHA

public static final String ALG_DIGEST_SHA
Constant string SHA. Used by the library with getMessageDigest().

See Also:
Constant Field Values

ALG_HMAC_MD5

public static final String ALG_HMAC_MD5
Constant string HmacMD5. Used by the library with getMac().

See Also:
Constant Field Values

ALG_HMAC_SHA

public static final String ALG_HMAC_SHA
Constant string HmacSHA1. Used by the library with getMac().

See Also:
Constant Field Values

ALG_SIGNATURE_SHADSA

public static final String ALG_SIGNATURE_SHADSA
Constant string SHA1withDSA. Used by the library with getSignature().

See Also:
Constant Field Values

ALG_SIGNATURE_RAWDSA

public static final String ALG_SIGNATURE_RAWDSA
Constant string RawDSA. Used by the library with getSignature().

See Also:
Constant Field Values

ALG_SIGNATURE_RAWECDSA

public static final String ALG_SIGNATURE_RAWECDSA
Constant string RawECDSA. Used by the library with getSignature().

See Also:
Constant Field Values

ALG_SIGNATURE_RAWECDSA_PLAIN

public static final String ALG_SIGNATURE_RAWECDSA_PLAIN
Constant string RawECDSAPlain. Used by the library with getSignature(). The signature value is encoded as (r || s) and not wrapped into a SEQUENCE as done by X9.62; see German BSI Technical Guideline TR-03111.

See Also:
Constant Field Values

ALG_SIGNATURE_RAWRSAPSS

public static final String ALG_SIGNATURE_RAWRSAPSS
Constant string RawRSAPSS. Used by this provider with getSignature().

See Also:
Constant Field Values

ALG_KEYEX_DH

public static final String ALG_KEYEX_DH
Constant string DH

See Also:
Constant Field Values

ALG_KEYEX_ESDH

public static final String ALG_KEYEX_ESDH
Constant string ESDH

See Also:
Constant Field Values

ALG_KEYEX_SSDH

public static final String ALG_KEYEX_SSDH
Constant string SSDH

See Also:
Constant Field Values

ALG_CIPHER_RSA

public static final String ALG_CIPHER_RSA
Constant string RSA/ECB/PKCS1Padding. This string is NOT used with getCipher(), but it is the prefix of all RSA algorithm identifier strings using PKCS#1v1.5 padding (see below). The different identifiers were chosen to simplify using a particular RSA implementation just one of these operations. For example, to using a smartcard for RSA signing only one will only care about signature creation operations and will want to leave all other operations to the standard implementation. This can easily be done by checking for the String ALG_CIPHER_RSA_SIGN only.

If you write your own security provider that does nothing like this you will typically use code like:

 if( algorithm.startsWith(ALG_CIPHER_RSA) ) {
   algorithm = ALG_CIPHER_RSA;
 }
 return Cipher.getInstance(algorithm, "MyProvider");
 

See Also:
Constant Field Values

ALG_CIPHER_RSA_SIGN

public static final String ALG_CIPHER_RSA_SIGN
Constant string RSA/ECB/PKCS1Padding/Sign. Used by the library with getCipher() to indicate an RSA signature creation operation (private key encryption).

See Also:
Constant Field Values

ALG_CIPHER_RSA_VERIFY

public static final String ALG_CIPHER_RSA_VERIFY
Constant string RSA/ECB/PKCS1Padding/Verify. Used by the library with getCipher() to indicate an RSA signature verification operation (public key decryption).

See Also:
Constant Field Values

ALG_CIPHER_RSA_ENCRYPT

public static final String ALG_CIPHER_RSA_ENCRYPT
Constant string RSA/ECB/PKCS1Padding/Encrypt. Used by the library with getCipher() to indicate an RSA data encryption operation (public key encryption).

See Also:
Constant Field Values

ALG_CIPHER_RSA_DECRYPT

public static final String ALG_CIPHER_RSA_DECRYPT
Constant string RSA/ECB/PKCS1Padding/Decrypt. Used by the library with getCipher() to indicate an RSA data decryption operation (private key decryption).

See Also:
Constant Field Values

providerName_

protected String providerName_
The name of the underlying cryptographic provider, if installed. If set, anytime at first is tried to get an engine from this cryptographic JCA/JCE provider.


random_

protected SecureRandom random_
The SecureRandom.

Constructor Detail

SecurityProvider

public SecurityProvider()
Default constructor.


SecurityProvider

public SecurityProvider(String providerName)
Cretes a SecurityProvider for the given cryptographic provider to use.

Parameters:
providerName - the name of the underlying cryptographic provider; if set, anytime at first is tried to get an engine from this cryptographic JCA/JCE provider.
Method Detail

getSecurityProvider

public static SecurityProvider getSecurityProvider()
Returns the active SecurityProvider. If no provider has been set explicitly using setSecurityProvider() and the IAIK JCE is available this will be the IaikProvider, otherwise it is an instance of this class.

NOTE that the SecurityProvider setting is global.

Attention This method does not synchronize on the SecurityProvider setting. If required, an application may take care for synchronizing itself or may ensure to set the security provider at application startup.

Returns:
the installed SecurityProvider

setSecurityProvider

public static void setSecurityProvider(SecurityProvider provider)
Sets the global SecurityProvider.

NOTE that the SecurityProvider setting is global.

Attention This method does not synchronize on the SecurityProvider setting. If required, an application may take care for synchronizing itself or may ensure to set the security provider at application startup.

Parameters:
provider - the SecurityProvider which shall be used

getProviderName

public String getProviderName()
Gets the name of the underlying cryptographic provider. If set, anytime at first is tried to get an engine from this cryptographic JCA/JCE provider.

Returns:
the name of the underlying cryptographic provider, or null if no cryptographic provider is set

getMessageDigest

public MessageDigest getMessageDigest(String algorithm)
                               throws NoSuchAlgorithmException
This method returns the desired MessageDigest object.

Parameters:
algorithm - the name of the requested digest algorithm
Returns:
the requested MessageDigest engine
Throws:
NoSuchAlgorithmException - if no MessageDigest engine is available for the requested algorithm

getMessageDigest

public MessageDigest getMessageDigest(AlgorithmID algorithm)
                               throws NoSuchAlgorithmException
This method returns the desired MessageDigest object.

Parameters:
algorithm - the AlgorithmID of the requested digest algorithm
Returns:
the requested MessageDigest engine
Throws:
NoSuchAlgorithmException - if no MessageDigest engine is available for the requested algorithm

getHash

public byte[] getHash(AlgorithmID algorithm,
                      byte[] data)
               throws NoSuchAlgorithmException
Calculates the hash on the given data using the requested hash algorithm.

Parameters:
algorithm - the hash algorithm to be used
data - the data on which the hash shall be calculated
Returns:
the hash calculated on the given data
Throws:
NoSuchAlgorithmException - if the requested hash algorithm is not supported

getInputStreamHashEngine

public InputStreamHashEngine getInputStreamHashEngine(AlgorithmID algorithm,
                                                      InputStream is)
                                               throws NoSuchAlgorithmException
Returns an InputStreamHashEngine for calculating the hash value on the data supplied from the given input stream. This method may be called by SignedDataStream or DigestedDataStream for obtaining an InputStreamHashEngine to which to pipe the data to be hashed:
 AlgorithmID hashAlgorithm = ...;
 InputStream is = ...;
 InputStreamHashEngine engine = securityProvider().getInputStreamHashEngine(hashAlgorithm, is);
 InputStream digestStream = engine.getInputStream();
 ...
 // read the stream
 byte[] hash = engine.getHash();
 

Parameters:
algorithm - the hash algorithm to be used
is - the inputstream supplying the data to be hashed
Returns:
the InputStreamHashEngine for the given algorithm
Throws:
NoSuchAlgorithmException - if the requested algorithm is not supported

getInputStreamCipherEngine

public InputStreamCipherEngine getInputStreamCipherEngine(AlgorithmID algorithm,
                                                          int mode,
                                                          Key key,
                                                          AlgorithmParameters params)
                                                   throws NoSuchAlgorithmException,
                                                          InvalidKeyException,
                                                          InvalidAlgorithmParameterException
Gets an InputStreamCipherEngine for en/decrypting data read from some input stream. An InputStreamCipherEngine is used by class EncryptedContentInfoStream for content en/decryption. The default implementation is based on the JCE javax.crypto.Cipher engine and uses a CipherInputStream for en/decrypting the data that is read from an underlying input stream.

Parameters:
algorithm - the cipher algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
Returns:
the InputStreamCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getInputStreamCipherEngine

public InputStreamCipherEngine getInputStreamCipherEngine(AlgorithmID algorithm,
                                                          int mode,
                                                          Key key,
                                                          AlgorithmParameterSpec params)
                                                   throws NoSuchAlgorithmException,
                                                          InvalidKeyException,
                                                          InvalidAlgorithmParameterException
Gets an InputStreamCipherEngine for en/decrypting data read from some input stream. An InputStreamCipherEngine is used by class EncryptedContentInfoStream for content en/decryption. The default implementation is based on the JCE javax.crypto.Cipher engine and uses a CipherInputStream for en/decrypting the data that is read from an underlying input stream.

Parameters:
algorithm - the cipher algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
Returns:
the InputStreamCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getByteArrayCipherEngine

public ByteArrayCipherEngine getByteArrayCipherEngine(AlgorithmID algorithm,
                                                      int mode,
                                                      Key key,
                                                      AlgorithmParameters params)
                                               throws NoSuchAlgorithmException,
                                                      InvalidKeyException,
                                                      InvalidAlgorithmParameterException
Gets a ByteArrayCipherEngine for en/decrypting data supplied by some byte array. An ByteArrayCipherEngine is used by class EncryptedContentInfo for content en/decryption. The default implementation is based on the JCE javax.crypto.Cipher engine that en/decrypts data that is supplied by a byte array.

Parameters:
algorithm - the cipher algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
Returns:
the ByteArrayCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getByteArrayCipherEngine

public ByteArrayCipherEngine getByteArrayCipherEngine(AlgorithmID algorithm,
                                                      int mode,
                                                      Key key,
                                                      AlgorithmParameterSpec params)
                                               throws NoSuchAlgorithmException,
                                                      InvalidKeyException,
                                                      InvalidAlgorithmParameterException
Gets a ByteArrayCipherEngine for en/decrypting data supplied by some byte array. An ByteArrayCipherEngine is used by class EncryptedContentInfo for content en/decryption. The default implementation is based on the JCE javax.crypto.Cipher engine that en/decrypts data that is supplied by a byte array.

Parameters:
algorithm - the cipher algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
Returns:
the ByteArrayCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getInputStreamAuthCipherEngine

public InputStreamAuthCipherEngine getInputStreamAuthCipherEngine(AlgorithmID algorithm,
                                                                  int mode,
                                                                  Key key,
                                                                  AlgorithmParameterSpec params,
                                                                  byte[] aad)
                                                           throws NoSuchAlgorithmException,
                                                                  InvalidKeyException,
                                                                  InvalidAlgorithmParameterException
Gets an InputStreamAuthCipherEngine for authenticated en/decrypting data read from some input stream. An InputStreamAuthCipherEngine is used by class EncryptedContentInfoStream for authenticated content en/decryption with CMS content-type AuthEnvelopedData. The default implementation is based on the JCE javax.crypto.Cipher engine and uses a CipherInputStream for en/decrypting the data that is read from an underlying input stream.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes or they are not available because we are in the parsing phase where the authenticated attributes may not be accessible at setup time because they are located behind the content
Returns:
the InputStreamAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getInputStreamAuthCipherEngine

public InputStreamAuthCipherEngine getInputStreamAuthCipherEngine(AlgorithmID algorithm,
                                                                  int mode,
                                                                  Key key,
                                                                  AlgorithmParameters params,
                                                                  byte[] aad)
                                                           throws NoSuchAlgorithmException,
                                                                  InvalidKeyException,
                                                                  InvalidAlgorithmParameterException
Gets an InputStreamAuthCipherEngine for authenticated en/decrypting data read from some input stream. An InputStreamAuthCipherEngine is used by class EncryptedContentInfoStream for authenticated content en/decryption with CMS content-type AuthEnvelopedData. The default implementation is based on the JCE javax.crypto.Cipher engine and uses a CipherInputStream for en/decrypting the data that is read from an underlying input stream.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes or they are not available because we are in the parsing phase where the authenticated attributes may not be accessible at setup time because they are located behind the content
Returns:
the InputStreamAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getByteArrayAuthCipherEngine

public ByteArrayAuthCipherEngine getByteArrayAuthCipherEngine(AlgorithmID algorithm,
                                                              int mode,
                                                              Key key,
                                                              AlgorithmParameters params,
                                                              byte[] aad)
                                                       throws NoSuchAlgorithmException,
                                                              InvalidKeyException,
                                                              InvalidAlgorithmParameterException
Gets a ByteArrayAuthCipherEngine for authenticated en/decrypting data supplied by some byte array. An ByteArrayAuthCipherEngine is used by class EncryptedContentInfo for authenicated content en/decryption with CMS content-type AuthEnvelopedData. The default implementation is based on the JCE javax.crypto.Cipher engine that en/decrypts data that is supplied by a byte array.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes
Returns:
the ByteArrayAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getByteArrayAuthCipherEngine

public ByteArrayAuthCipherEngine getByteArrayAuthCipherEngine(AlgorithmID algorithm,
                                                              int mode,
                                                              Key key,
                                                              AlgorithmParameterSpec params,
                                                              byte[] aad)
                                                       throws NoSuchAlgorithmException,
                                                              InvalidKeyException,
                                                              InvalidAlgorithmParameterException
Gets a ByteArrayAuthCipherEngine for en/decrypting data supplied by some byte array. An ByteArrayCipherEngine is used by class EncryptedContentInfo for authenicated content en/decryption with CMS content-type AuthEnvelopedData. The default implementation is based on the JCE javax.crypto.Cipher engine that en/decrypts data that is supplied by a byte array.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes
Returns:
the ByteArrayAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getAuthCipherEngine

public AuthCipherEngine getAuthCipherEngine(AlgorithmID algorithm,
                                            int mode,
                                            Key key,
                                            AlgorithmParameterSpec params,
                                            byte[] aad)
                                     throws NoSuchAlgorithmException,
                                            InvalidKeyException,
                                            InvalidAlgorithmParameterException
Gets an AuthCipherEngine for authenticated data encryption. An AuthCipherEngine is used by class EncryptedContentInfoOutputStream for authenticated content encryption with CMS content-type AuthEnvelopedData.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes or they are not available because we are in the parsing phase where the authenticated attributes may not be accessible at setup time because they are located behind the content
Returns:
the IAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getAuthCipherEngine

public AuthCipherEngine getAuthCipherEngine(AlgorithmID algorithm,
                                            int mode,
                                            Key key,
                                            AlgorithmParameters params,
                                            byte[] aad)
                                     throws NoSuchAlgorithmException,
                                            InvalidKeyException,
                                            InvalidAlgorithmParameterException
Gets an AuthCipherEngine for authenticated data encryption. An AuthCipherEngine is used by class EncryptedContentInfoOutputStream for authenticated content encryption with CMS content-type AuthEnvelopedData.

Parameters:
algorithm - the content-authenticated encryption algorithm to be used
mode - the cipher mode to be used (CIPHER_NONE, CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP)
key - the key to be used for en/deciphering
params - any algorithm parameters required by the cipher algorithm
aad - the additional authenticated data (DER encoded authenticated attributes from AuthEnvelopedData content type according to RFC 5083), or null if there are no authenticated attributes or they are not available because we are in the parsing phase where the authenticated attributes may not be accessible at setup time because they are located behind the content
Returns:
the IAuthCipherEngine just created
Throws:
NoSuchAlgorithmException - if the requested cipher algorithm is not supported
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are not valid for the requested algorithm

getOutputStreamHashEngine

public OutputStreamHashEngine getOutputStreamHashEngine(AlgorithmID algorithm,
                                                        OutputStream os)
                                                 throws NoSuchAlgorithmException
Returns an OutputStreamHashEngine for calculating the hash value on the data supplied from the given output stream. This method may be called by the S/MIME part of this library for obtaining an OutputStreamHashEngine to which to pipe the data to be hashed:
 AlgorithmID hashAlgorithm = ...;
 OutputStream is = ...;
 OutputStreamHashEngine engine = securityProvider().getOutputStreamHashEngine(hashAlgorithm, is);
 OutputStream digestStream = engine.getOutputStream();
 ...
 // read the stream
 byte[] hash = engine.getHash();
 

Parameters:
algorithm - the hash algorithm to be used
os - the outputstream to which the data to be hashed is written
Returns:
the OutputStreamHashEngine for the given algorithm
Throws:
NoSuchAlgorithmException - if the requested algorithm is not supported

getInputStreamCompressEngine

public InputStreamCompressEngine getInputStreamCompressEngine(AlgorithmID compressAlg,
                                                              InputStream is,
                                                              int compressionMode,
                                                              int bufferSize)
                                                       throws NoSuchAlgorithmException
Gets an InputStreamCompressEngine for compressing/decompressing data read from some input stream. An InputStreamCompressEngine is used by class CompressedDataStream for content compression/decompression. This class provides an implementation of the ZLIB compression algorithm ([RFC1950] [RFC1951]) based on the Deflater/Inflater utilities of the java.utils.zip package.

Parameters:
compressAlg - the compression/decompression algorithm to be used
is - the input stream supplying the data to be compressed/decompressed
compressionMode - the compression mode to be used (COMPRESS or DECOMPRESS)
bufferSize - the size of the internal buffer, if used by the compress engine (will be the blockSize value used for the compressed data encoding); maybe -1, if no block encoding is used; in this case the engine may use a default buffer size
Returns:
the InputStreamCompressEngine just created
Throws:
NoSuchAlgorithmException - if the requested compression algorithm is not supported

getOutputStreamCompressEngine

public OutputStreamCompressEngine getOutputStreamCompressEngine(AlgorithmID compressAlg,
                                                                OutputStream os,
                                                                int bufferSize)
                                                         throws NoSuchAlgorithmException
Gets an OutputStreamCompressEngine for compressing data written to some output stream. An OutputStreamCompressEngine is used by class CompressedDataOutputStream for content compression. This class provides an implementation of the ZLIB compression algorithm ([RFC1950] [RFC1951]) based on the Deflater utilities of the java.utils.zip package.

Parameters:
compressAlg - the compression algorithm to be used
os - the output stream to which to write the data to be compressed
bufferSize - the size of the internal buffer, if used by the compress engine (will be the blockSize value used for the compressed data encoding); maybe -1, if no block encoding is used; in this case the engine may use a default buffer size
Returns:
the OutputStreamCompressEngine just created
Throws:
NoSuchAlgorithmException - if the requested compression algorithm is not supported

compress

public byte[] compress(AlgorithmID compressAlg,
                       byte[] data,
                       int compressionMode)
                throws NoSuchAlgorithmException,
                       IOException
Uses the given compression algorithm to compress/decompress the supplied input data. This class provides an implementation of the ZLIB compression algorithm ([RFC1950] [RFC1951]) based on the Deflater/Inflater utilities of the java.utils.zip package.

Parameters:
compressAlg - the compression/decompression algorithm to be used
data - the input data to be compressed/decompressed
compressionMode - the compression mode to be used (COMPRESS or DECOMPRESS)
Returns:
the compressed/decompressed data as byte array
Throws:
IOExecption - if an I/O error occurs during data compression/decompression
NoSuchAlgorithmException - if the requested compression algorithm is not supported
IOException

getMac

public Mac getMac(String algorithm,
                  Key key,
                  AlgorithmParameterSpec paramSpec)
           throws InvalidKeyException,
                  NoSuchAlgorithmException,
                  InvalidAlgorithmParameterException
This method returns the desired MAC object.

Parameters:
algorithm - the name of the Mac algorithm
key - the key, if not null to be used for initializing the Mac object
paramSpec - any parameters, if not null to be used for initializing the Mac object
Returns:
the requested Mac engine, already initialized with given key and params, if not null
Throws:
InvalidAlgorithmParameterException - if the parameters are not valid
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Mac engine is available for the requested algorithm

getMac

public Mac getMac(AlgorithmID algorithm,
                  Key key,
                  AlgorithmParameterSpec paramSpec)
           throws InvalidKeyException,
                  NoSuchAlgorithmException,
                  InvalidAlgorithmParameterException
This method returns the desired MAC object.

Parameters:
algorithm - the name of the Mac algorithm
key - the key, if not null to be used for initializing the Mac object
paramSpec - any parameters, if not null to be used for initializing the Mac object
Returns:
the requested Mac engine, already initialized with given key and params, if not null
Throws:
InvalidAlgorithmParameterException - if the parameters are not valid
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Mac engine is available for the requested algorithm

getInputStreamMacEngine

public InputStreamMacEngine getInputStreamMacEngine(AlgorithmID algorithm,
                                                    Key key,
                                                    AlgorithmParameterSpec paramSpec,
                                                    InputStream is)
                                             throws InvalidKeyException,
                                                    NoSuchAlgorithmException,
                                                    InvalidAlgorithmParameterException
Gets an InputStreamMacEngine for calculating a Message Authentication Code on data read from some input stream. An InputStreamMacEngine is used by class AuthenticatedDataStream for content MAC calculation. The default implementation is based on the JCA javax.crypto.Mac engine.

Parameters:
algorithm - the name of the Mac algorithm
key - the key, if not null to be used for initializing the Mac object
paramSpec - any parameters to be used for initializing the Mac object; maybe null
is - the input stream supplying the data to be processed
Returns:
the requested InputStreamMacEngine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Mac engine is available for the requested algorithm
InvalidAlgorithmParameterException - if the parameters are not valid

getOutputStreamMacEngine

public OutputStreamMacEngine getOutputStreamMacEngine(AlgorithmID algorithm,
                                                      Key key,
                                                      AlgorithmParameterSpec paramSpec,
                                                      OutputStream os)
                                               throws InvalidKeyException,
                                                      NoSuchAlgorithmException,
                                                      InvalidAlgorithmParameterException
Gets an OutputStreamMacEngine for calculating a Message Authentication Code on data written to some output stream. An OutputStreamMacEngine is used by class AuthenticatedDataOutputStream for content MAC calculation. The default implementation is based on the JCA javax.crypto.Mac engine.

Parameters:
algorithm - the name of the Mac algorithm
key - the key, if not null to be used for initializing the Mac object
paramSpec - any parameters to be used for initializing the Mac object; maybe null
os - the output stream to which the data to be processed is written
Returns:
the requested OutputStreamMacEngine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Mac engine is available for the requested algorithm
InvalidAlgorithmParameterException - if the parameters are not valid

calculateMac

public byte[] calculateMac(AlgorithmID algorithmID,
                           Key key,
                           AlgorithmParameterSpec paramSpec,
                           byte[] data)
                    throws InvalidKeyException,
                           NoSuchAlgorithmException,
                           InvalidAlgorithmParameterException
Calculates a Message Authentication Code on the given data.

Parameters:
algorithmID - the id of the Mac algorithm
key - the key to be used for initializing the Mac object
paramSpec - any parameters, if not null to be used for initializing the Mac object
data - the data from which to calculate the MAC
Returns:
the Mac value calculated on the data
Throws:
InvalidAlgorithmParameterException - if the parameters are not valid
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Mac engine is available for the requested algorithm

getSignature

public Signature getSignature(String algorithm,
                              int mode,
                              Key key)
                       throws InvalidKeyException,
                              NoSuchAlgorithmException
This method returns the desired Signature object. If the mode parameter is SIGNATURE_SIGN or SIGNATURE_VERIFY the signature object has to be initialized with the provided key in the respective mode.

Parameters:
algorithm - the name of the Signature algorithm
mode - the mode indicating if the engine has to be initialized
key - the key for initializing the Signature engine
Returns:
the (if requested initialized) Signature engine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Signature engine is available for the requested algorithm

getSignature

public Signature getSignature(String algorithm,
                              int mode,
                              Key key,
                              AlgorithmParameterSpec paramSpec)
                       throws InvalidKeyException,
                              NoSuchAlgorithmException
This method returns the desired Signature object. If the mode parameter is SIGNATURE_SIGN or SIGNATURE_VERIFY the signature object has to be initialized with the provided key in the respective mode. If algorithm parameters are specified they are set for the Signature engine.

Parameters:
algorithm - the name of the Signature algorithm
mode - the mode indicating if the engine has to be initialized
key - the key for initializing the Signature engine
paramSpec - any parameters to be set for the Signature engine, if not null
Returns:
the (if requested initialized) Signature engine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Signature engine is available for the requested algorithm

getSignature

public Signature getSignature(AlgorithmID signatureAlgorithm,
                              int mode,
                              Key key)
                       throws InvalidKeyException,
                              NoSuchAlgorithmException
This method returns the desired Signature object. If the mode parameter is SIGNATURE_SIGN or SIGNATURE_VERIFY the signature object is to be initialized with the provided key in the respective mode.

Parameters:
signatureAlgorithm - the AlgorithmID of the Signature algorithm
mode - the mode indicating if the engine has to be initialized
key - the key for initializing the Signature engine
Returns:
the (if requested initialized) Signature engine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Signature engine is available for the requested algorithm

getSignature

public Signature getSignature(AlgorithmID signatureAlgorithm,
                              int mode,
                              Key key,
                              AlgorithmParameterSpec paramSpec)
                       throws InvalidKeyException,
                              NoSuchAlgorithmException
This method returns the desired Signature object. If the mode parameter is SIGNATURE_SIGN or SIGNATURE_VERIFY the signature object is to be initialized with the provided key in the respective mode. If algorithm parameters are specified they are set for the Signature engine.

Parameters:
signatureAlgorithm - the AlgorithmID of the Signature algorithm
mode - the mode indicating if the engine has to be initialized
key - the key for initializing the Signature engine
paramSpec - any parameters to be set for the Signature engine, if not null
Returns:
the (if requested initialized) Signature engine
Throws:
InvalidKeyException - if the key is not valid
NoSuchAlgorithmException - if no Signature engine is available for the requested algorithm

setSignatureParameters

public static void setSignatureParameters(Signature signature,
                                          AlgorithmParameterSpec paramSpec)
Sets the parametes for a Signature engine.
This method calls Signature.setParameter(AlgorithmParameterSpec paramSpec) for JDK versions > 1.2, and Signature.setParameter(String param, Object value) (via reflection) for JDK 1.1.x.

Parameters:
signature - the Signature engine from which to get the parametes

getKeyAgreement

public KeyAgreement getKeyAgreement(AlgorithmID keyAgreementAlgorithm,
                                    Key key,
                                    AlgorithmParameterSpec paramSpec)
                             throws InvalidKeyException,
                                    InvalidAlgorithmParameterException,
                                    NoSuchAlgorithmException
This method returns the desired KeyAgreement object.

Parameters:
keyAgreementAlgorithm - the algorithmID of the key agreement algorithm requested
key - the (private) key for initializing the KeyAgreement
paramSpec - any parameters used for intializing the key agreement
Returns:
the initialized KeyAgreement engine
Throws:
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid
NoSuchAlgorithmException - if no KeyAgreement engine is available for the requested algorithm

calculateSharedSecret

public byte[] calculateSharedSecret(AlgorithmID keyAgreementAlgorithm,
                                    Key key,
                                    Key otherKey,
                                    AlgorithmParameterSpec paramSpec)
                             throws InvalidKeyException,
                                    InvalidAlgorithmParameterException,
                                    NoSuchAlgorithmException
This method uses the specified KeyAgreement algorithm to calculate a shared secret between the owners of the given private and public key.

Parameters:
keyAgreementAlgorithm - the algorithmID of the key agreement algorithm requested
key - the (private) key for initializing the KeyAgreement
otherKey - the (public) key from the other party
paramSpec - any parameters used for intializing the key agreement
Returns:
the shared secret
Throws:
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid
NoSuchAlgorithmException - if no KeyAgreement engine is available for the requested algorithm

calculateSignatureFromSignedAttributes

public byte[] calculateSignatureFromSignedAttributes(AlgorithmID signatureAlgorithm,
                                                     AlgorithmID digestAlgorithm,
                                                     PrivateKey privateKey,
                                                     byte[] signedAttributes)
                                              throws NoSuchAlgorithmException,
                                                     InvalidKeyException,
                                                     SignatureException
Calculates the signature value for a CMS SignerInfo over the given signed attributes with the given algorithm using the supplied private key.

Each SignerInfo included in a CMS SignedData object may calculate the signature value differently depending on the presence of signed attributes:

This method is called by class SignerInfo for calculating the signature when signed attributes are present.

When writing your own SecurityProvider and overriding this method, be aware that only the -- yet NOT hashed -- DER encoding of the signed attributes is supplied to this method. For that reason this method can be overriden for use with smartcards requiring to do the digest calculation theirselves: ensure that your SignerInfo contains signed attributes and override this method in a way to pass the given DER encoding of the signed attributes to your smartcard for doing the signature (and digest) calculation.

Since this method requires to calculate the digest value over the DER encoded signed attributes as part of the signature calculation, it uses a ordinary JCA Signature engine.

Parameters:
signatureAlgorithm - signatureAlgorithm the signature algorithm to be used, e.g. rsaEncryption, DSA
digestAlgorithm - the digest algorithm to be used for hash computation (e.g. SHA-1, ..., SHA-512); may be necessary for some signature schemes (e.g. to be included as a DigestInfo in a PKCS#1 RSA signature)
privateKey - the private key of the signer (i.e. the one supplied when creating a SignerInfo object; may be some kind of "dummy" key when used for smartcards
signedAttributes - the DER encoding of the signed attributes over which the signature shall be calculated
Returns:
the signature value calculated from the given DER encoded signed attributes
Throws:
NoSuchAlgorithmException - if no Signature engine is available for the requested algorithm
InvalidKeyException - if the key is not valid
if - signature calculation fails
SignatureException

calculateSignatureFromHash

public byte[] calculateSignatureFromHash(AlgorithmID signatureAlgorithm,
                                         AlgorithmID digestAlgorithm,
                                         PrivateKey privateKey,
                                         byte[] digest)
                                  throws NoSuchAlgorithmException,
                                         InvalidKeyException,
                                         SignatureException
Calculates the signature value for a CMS SignerInfo over the given digest value with the given algorithm using the supplied private key.

Each SignerInfo included in a CMS SignedData object may calculate the signature value differently depending on the presence of signed attributes:

This method is called by class SignerInfo for calculating the signature when no signed attributes are present. Since the data to be signed may be of arbitrary size this method expects the already hashed data to only calculate the signature value on it (for instance, by doing the digest encrypting when using RSA for signing).

For that reason, when writing your own SecurityProvider and overriding this method, you will need some kind of RAW signature (respectively digest encryption) mechanism only expecting the already hashed data (e.g. a "RawDSA" signature engine when using DSA repectively a Cipher engine when using RSA).

If you want to override this method for use with smartcards, please be sure that your smartcard is able to do the signature (respectively digest encryption) operation only. However, if your smartcard requires to supply the whole data for doing the hash calcualtion itself, you may ensure that your SignerInfo contains signed attributes and override method calculateSignatureFromSignedAttributes for calculating the signature over the DER encoding of the signed attributes (thereby doing the hash computation, too).

Parameters:
signatureAlgorithm - signatureAlgorithm the signature algorithm to be used, e.g. rsaEncryption, DSA
digestAlgorithm - the digest algorithm used for hash computation (e.g. SHA-1, ..., SHA-512); may be necessary for some signature schemes (e.g. to be included as a DigestInfo in a PKCS#1 RSA signature)
privateKey - the private key of the signer (i.e. the one supplied when creating a SignerInfo object; may be some kind of "dummy" key when used for smartcards
digest - the digest value over which the signature shall be calculated
Returns:
the signature value calculated from the given digest value
Throws:
NoSuchAlgorithmException - if any of the required algorithms is not supported
InvalidKeyException - if the key is not valid
SignatureException - if signature verification fails because of some crypto related error

verifySignatureFromSignedAttributes

public boolean verifySignatureFromSignedAttributes(AlgorithmID signatureAlgorithm,
                                                   AlgorithmID digestAlgorithm,
                                                   PublicKey publicKey,
                                                   byte[] signedAttributes,
                                                   byte[] signatureValue)
                                            throws NoSuchAlgorithmException,
                                                   InvalidKeyException,
                                                   SignatureException
Verifies the signature value of a CMS SignerInfo calculated over the given signed attributes with the given algorithm using the supplied public key.

Each SignerInfo included in a CMS SignedData object may calculate the signature value differently depending on the presence of signed attributes:

This method is called by class SignerInfo for verifying the signature when no signed attributes are present.

When writing your own SecurityProvider and overriding this method, be aware that only the -- yet NOT hashed -- DER encoding of the signed attributes is supplied to this method. Although generally for public key operations smartcards may not be used, this method can be overriden for use with smartcards requiring to do the digest calculation theirselves: ensure that your SignerInfo contains signed attributes and override this method in a way to pass the given DER encoding of the signed attributes to your smartcard for doing the signature verification (including any digest calculation required).

Since this method requires to calculate the digest value over the DER encoded signed attributes as part of the signature verification, it uses a oridinary JCA Signature engine.

Parameters:
signatureAlgorithm - signatureAlgorithm the signature algorithm to be used, e.g. rsaEncryption, DSA
digestAlgorithm - the digest algorithm to be used for hash computation (e.g. SHA-1, ..., SHA-512);
publicKey - the public key of the signer
signedAttributes - the DER encoding of the signed attributes over which the signature has been calculated
signatureValue - the signatureValue the signature value to be verified
Returns:
true if the signature is ok, false if not
Throws:
NoSuchAlgorithmException - if any of the required algorithms is not supported
InvalidKeyException - if the key is not valid
SignatureException - if signature verification fails because of some computation error

verifySignatureFromHash

public boolean verifySignatureFromHash(AlgorithmID signatureAlgorithm,
                                       AlgorithmID digestAlgorithm,
                                       PublicKey publicKey,
                                       byte[] digest,
                                       byte[] signatureValue)
                                throws NoSuchAlgorithmException,
                                       InvalidKeyException,
                                       SignatureException
Verifies the signature value of a CMS SignerInfo object with the given algorithm using the supplied public key.

Each SignerInfo included in a CMS SignedData object may calculate the signature value differently depending on the presence of signed attributes:

This method is called by class SignerInfo for verifying the signature when no signed attributes are present. Since the data to be verified may be of arbitrary size this method expects the already hashed data to only be verified against the signature value.

For that reason, when writing your own SecurityProvider and overriding this method, you will need some kind of RAW signature (respectively "encrypted digest decryption") mechanism only expecting the already hashed data (e.g. a "RawDSA" signature engine when using DSA repectively a Cipher engine when using RSA).

Although generally for public key operations smartcards may not be used, when overriding this method for use with smartcards, please be sure that your smartcard is able to do the signature verification operation only. However, if your smartcard requires to supply the whole data for doing the hash calcualtion itself, you may ensure that your SignerInfo contains signed attributes and override method verifySignatureFromSignedAttributes for verifying the signature calculated from the DER encoding of the signed attributes (thereby doing the hash computation, too).

Parameters:
signatureAlgorithm - signatureAlgorithm the signature algorithm to be used for verification, e.g. rsaEncryption, DSA
digestAlgorithm - the digest algorithm that has been used for hash computation (e.g. SHA-1, ..., SHA-512); may be necessary for some signature schemes (e.g. to be check against a DigestInfo in a PKCS#1 RSA signature)
publicKey - the public key of the signer
digest - the digest value to be verified
Returns:
true if the signature is ok, false if not
Throws:
NoSuchAlgorithmException - if any of the required algorithms is not supported
InvalidKeyException - if the key is not valid
SignatureException - if signature verification fails because of some crypto related or parsing error

encryptKey

public byte[] encryptKey(SecretKey cek,
                         AlgorithmID kea,
                         PublicKey recipientKey)
                  throws NoSuchAlgorithmException,
                         InvalidKeyException,
                         NoSuchPaddingException,
                         BadPaddingException
Encrypts the given secret content encryption key for a KeyTransRecipientInfo.

CMS EnvelopedData uses the KeyTransRecipientInfo type for encrypting the secret content encryption key with the public key of the recipient. Currently in general RSA PKCS#1v1.5 is used for key transport. If rsaEncryption is requested as key encryption algorithm this method uses a RSA Cipher ("RSA/ECB/PKCS1Padding/Encrypt") for encrypting the key. If another algorithm than RSA is requested, this method throws a NoSuchAlgorithmException. An application wishing to support another algorithm may override this method.

Parameters:
cek - the secret content encryption key to be encrypted
kea - the key encryption alglorithm to be used, e.g. rsaEncryption
recipientKey - the public key of the recipient to be used for encrypting content encryption key
Returns:
the encrypted content encryption key as byte array
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the encryption key is not valid
NoSuchPaddingException - if the required padding scheme is not supported
BadPaddingException - if an padding error occurs

decryptKey

public SecretKey decryptKey(byte[] encryptedKey,
                            AlgorithmID kea,
                            PrivateKey recipientKey)
                     throws NoSuchAlgorithmException,
                            InvalidKeyException,
                            NoSuchPaddingException,
                            BadPaddingException
Decrypts the given encrypted content encryption key for a KeyTransRecipientInfo.

CMS EnvelopedData uses the KeyTransRecipientInfo type for encrypting the secret content encryption key with the public key of the recipient. Currently in general RSA PKCS#1v1.5 is used for key transport. If rsaEncryption is requested as key encryption algorithm this method uses a RSA Cipher ("RSA/ECB/PKCS1Padding/Encrypt") for decrypting the encrypted content encryption key with the supplied private key of the recipient. If another algorithm than RSA is requested, this method throws a NoSuchAlgorithmException. An application wishing to support another algorithm may override this method.

Parameters:
encryptedKey - the encrypted content encryption key to be decrypted
kea - the key encryption alglorithm to be used, e.g. rsaEncryption
recipientKey - the private key of the recipient to be used for decrypting the encrypted content encryption key
Returns:
the decrypted content encryption key, the algorithm name will be set to "RAW"
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the decryption key is not valid
NoSuchPaddingException - if the required padding scheme is not supported
BadPaddingException - if an padding error occurs

decryptKey

public SecretKey decryptKey(byte[] encryptedKey,
                            AlgorithmID kea,
                            PrivateKey recipientKey,
                            String cekAlgorithmName)
                     throws NoSuchAlgorithmException,
                            InvalidKeyException,
                            NoSuchPaddingException,
                            BadPaddingException
Decrypts the given encrypted content encryption key for a KeyTransRecipientInfo.

CMS EnvelopedData uses the KeyTransRecipientInfo type for encrypting the secret content encryption key with the public key of the recipient. Currently in general RSA PKCS#1v1.5 is used for key transport. If rsaEncryption is requested as key encryption algorithm this method uses a RSA Cipher ("RSA/ECB/PKCS1Padding/Encrypt") for decrypting the encrypted content encryption key with the supplied private key of the recipient. If another algorithm than RSA is requested, this method throws a NoSuchAlgorithmException. An application wishing to support another algorithm may override this method.

Parameters:
encryptedKey - the encrypted content encryption key to be decrypted
kea - the key encryption alglorithm to be used, e.g. rsaEncryption
recipientKey - the private key of the recipient to be used for decrypting the encrypted content encryption key
cekAlgorithmName - the name of the content encryption key (e.g. "DES") to be set for the SecretKey object created by this method
Returns:
the decrypted content encryption key
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the decryption key is not valid
NoSuchPaddingException - if the required padding scheme is not supported
BadPaddingException - if an padding error occurs

getCipher

public Cipher getCipher(String algorithm,
                        int mode,
                        Key key,
                        AlgorithmParameters params)
                 throws NoSuchAlgorithmException,
                        InvalidKeyException,
                        InvalidAlgorithmParameterException
This method returns the desired Cipher object.

The symmetric ciphers shall explain themselves.

RSA/ECB/PKCS1Padding means RSA en/decryption with padding as defined in PKCS#1 1.5 where the padding block type is automatically selected based on the type of key used (block type 1 for signature operations, block type 2 for encryption operations). This cipher will be always used the same way (other methods need not to be implemented!):

 Cipher rsa = provider.getCipher("RSA/ECB/PKCS1Padding/...", ...);
 crypted = rsa.doFinal(plain);
 
If the mode parameter is CIPHER_ENCRYPT, CIPHER_WRAP CIPHER_DECRYPT, or CIPHER_UNWRAP the cipher object has to be initialized with the provided key in the respective mode.

Parameters:
algorithm - the name of the requested algorithm
mode - the mode indicating if the Cipher has to be initialized
key - the key to be used for initializing the cipher
params - the parameters to be used to initialize the cipher
Returns:
the initialized Cipher object
Throws:
NoSuchAlgorithmException - if no Cipher engine is available for the requested algorithm
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid

getCipher

public Cipher getCipher(String algorithm,
                        int mode,
                        Key key,
                        AlgorithmParameterSpec params)
                 throws NoSuchAlgorithmException,
                        InvalidKeyException,
                        InvalidAlgorithmParameterException
This method returns the desired Cipher object.

The symmetric ciphers shall explain themselves.

RSA/ECB/PKCS1Padding means RSA en/decryption with padding as defined in PKCS#1 1.5 where the padding block type is automatically selected based on the type of key used (block type 1 for signature operations, block type 2 for encryption operations). This cipher will be always used the same way (other methods need not to be implemented!):

 Cipher rsa = provider.getCipher("RSA/ECB/PKCS1Padding/...", ...);
 crypted = rsa.doFinal(plain);
 
If the mode parameter is CIPHER_ENCRYPT, CIPHER_WRAP CIPHER_DECRYPT, or CIPHER_UNWRAP the cipher object has to be initialized with the provided key in the respective mode.

Parameters:
algorithm - the name of the requested algorithm
mode - the mode indicating if the Cipher has to be initialized
key - the key to be used for initializing the cipher
params - the parameters to be used to initialize the cipher
Returns:
the initialized Cipher object
Throws:
NoSuchAlgorithmException - if no Cipher engine is available for the requested algorithm
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid

getCipher

public Cipher getCipher(AlgorithmID algorithm,
                        int mode,
                        Key key,
                        AlgorithmParameters params)
                 throws NoSuchAlgorithmException,
                        InvalidKeyException,
                        InvalidAlgorithmParameterException
Returns the desired Cipher object for the requested algorithm.

If the mode parameter is CIPHER_ENCRYPT, CIPEHER_WRAP, CIPHER_DECRYPT or CIPHER_UNWRAP the cipher object is to be initialized with the provided key and parameters in the respective mode.

If initializing the cipher for encryption/wrapping any parameters used for initializing or produced by the Cipher engine have to be included in the supplied algorithmID, e.g.:

 if ((mode == CIPHER_ENCRYPT) || (mode == CIPHER_WRAP)) {
   AlgorithmParameters parameters = cipher.getParameters();
   if (parameters != null) {
     algorithm.setAlgorithmParameters(parameters);   
   }
 } 
 
Since getParameters may not be implemented by some particular provider, in this case this methods looks if the cipher produced an IV and includes it into the AlgorithmID (however, only if the AlgorithmID yet does not include parameters):
 if ((mode == CIPHER_ENCRYPT) || (mode == CIPHER_WRAP)) {
   // any parameters to set for the AlgorithmID?
   AlgorithmParameters parameters = cipher.getParameters();
   if (parameters != null) {
     algorithm.setAlgorithmParameters(parameters);   
   } else { 
     if (algorithm.getParameter() == null) {
       if (params != null) {
         algorithm.setAlgorithmParameters(params); 
       } else { 
         // iv?
         byte[] iv = cipher.getIV();
         if (iv != null) {
           algorithm.setParameter(new OCTET_STRING(iv));   
         }    
       }
     }  
   }
 }
 

Parameters:
algorithm - the algorithm for which to create a Cipher engine
mode - the Cipher mode (CIPHER_ENCRYPT, CIPHER_WRAP, CIPHER_DECRYPT, CIPHER_UNWRAP)
key - the key to be used for initializing the cipher
params - any algorithm parameters used for initializing the cipher
Returns:
the already initialized Cipher engine
Throws:
NoSuchAlgorithmException - if no Cipher engine is available for the requested algorithm
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid

getCipher

public Cipher getCipher(AlgorithmID algorithm,
                        int mode,
                        Key key,
                        AlgorithmParameterSpec params)
                 throws NoSuchAlgorithmException,
                        InvalidKeyException,
                        InvalidAlgorithmParameterException
Returns the desired Cipher object for the requested algorithm.

If the mode parameter is CIPHER_ENCRYPT, CIPEHER_WRAP, CIPHER_DECRYPT or CIPHER_UNWRAP the cipher object is to be initialized with the provided key and parameters in the respective mode.

If initializing the cipher for encryption/wrapping any parameters used for initializing or produced by the Cipher engine have to be included in the supplied algorithmID, e.g.:

 if ((mode == CIPHER_ENCRYPT) || (mode == CIPHER_WRAP)) {
   AlgorithmParameters parameters = cipher.getParameters();
   if (parameters != null) {
     algorithm.setAlgorithmParameters(parameters);   
   }
 } 
 
Since getParameters may not be implemented by some particular provider, in this case this methods looks if the cipher produced an IV and includes it into the AlgorithmID (however, only if the AlgorithmID yet does not include parameters):
 if ((mode == CIPHER_ENCRYPT) || (mode == CIPHER_WRAP)) {
   // any parameters to set for the AlgorithmID?
   AlgorithmParameters parameters = cipher.getParameters();
   if (parameters != null) {
     algorithm.setAlgorithmParameters(parameters);   
   } else { 
     if (algorithm.getParameter() == null) {
       // iv?
       byte[] iv = cipher.getIV();
       if (iv != null) {
         algorithm.setParameter(new OCTET_STRING(iv));   
       }    
     }  
   }
 }
 

Parameters:
algorithm - the algorithm for which to create a Cipher engine
mode - the Cipher mode (CIPHER_ENCRYPT, CIPHER_WRAP, CIPHER_DECRYPT, CIPHER_UNWRAP)
key - the key to be used for initializing the cipher
params - any algorithm parameters used for initializing the cipher
Returns:
the already initialized Cipher engine
Throws:
NoSuchAlgorithmException - if no Cipher engine is available for the requested algorithm
InvalidKeyException - if the key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid

getKeyPairGenerator

public KeyPairGenerator getKeyPairGenerator(AlgorithmID algorithm)
                                     throws NoSuchAlgorithmException
Return a KeyPairGenerator for the requested algorithm.

Parameters:
algorithm - the requested algorithm
Returns:
the KeyPairGenerator for the requested algorithm
Throws:
NoSuchSuchAlgorithmException - if no KeyPairGenerator for the requested algorithm is available
NoSuchAlgorithmException

getKeyGenerator

public KeyGenerator getKeyGenerator(AlgorithmID algorithm,
                                    int keyLength)
                             throws NoSuchAlgorithmException
Return a KeyGenerator for the requested algorithm.

Parameters:
algorithm - the requested algorithm
keyLength - the length of the key to be generated, may be required for algorithms with variable key size; -1 if the KeyGenerator should generate a key of default length
Returns:
the KeyGenerator for the requested algorithm
Throws:
NoSuchSuchAlgorithmException - if no KeyGenerator for the requested algorithm is available
NoSuchAlgorithmException

getKeyGenerator

public KeyGenerator getKeyGenerator(AlgorithmID algorithm,
                                    AlgorithmParameterSpec paramSpec)
                             throws NoSuchAlgorithmException,
                                    InvalidAlgorithmParameterException
Returns a KeyGenerator for the requested algorithm.

Parameters:
algorithm - the requested algorithm
paramSpec - any parameters for initializing the key generator
Returns:
the KeyGenerator (initialized; if paramSpec is not null) for the requested algorithm
Throws:
NoSuchSuchAlgorithmException - if no KeyGenerator for the requested algorithm is available
InvalidAlgorithmParameterException - if the parameters are invalid or not suitable for the requested KeyGenerator
NoSuchAlgorithmException

generateKey

public SecretKey generateKey(AlgorithmID algorithm,
                             AlgorithmParameterSpec paramSpec)
                      throws NoSuchAlgorithmException,
                             InvalidAlgorithmParameterException
Generates a SecretKey for the requested algorithm.

Parameters:
algorithm - the requested algorithm
paramSpec - any parameters for initializing the key generator
Returns:
the generated secret key
Throws:
NoSuchSuchAlgorithmException - if the key for the requested algorithm cannot be created
InvalidAlgorithmParameterException - if the parameters are invalid or not suitable for the requested Key
NoSuchAlgorithmException

generateKey

public SecretKey generateKey(AlgorithmID algorithm,
                             int keyLength)
                      throws NoSuchAlgorithmException
Generates a SecretKey for the requested algorithm.

Parameters:
algorithm - the requested algorithm
keyLength - the length of the key to be generated, may be required for algorithms with variable key size
Returns:
the generated secret key
Throws:
NoSuchSuchAlgorithmException - if the key for the requested algorithm cannot be created
NoSuchAlgorithmException

getSecretKeyFactory

public SecretKeyFactory getSecretKeyFactory(AlgorithmID algorithm)
                                     throws NoSuchAlgorithmException
Return a SecretKeyFactory for the requested algorithm.

Parameters:
algorithm - the requested algorithm
Returns:
the SecretKeyFactory for the requested algorithm
Throws:
NoSuchSuchAlgorithmException - if no KeyGenerator for the requested algorithm is available
NoSuchAlgorithmException

getKeyFactory

public KeyFactory getKeyFactory(AlgorithmID algorithm)
                         throws NoSuchAlgorithmException
This method returns the desired KeyFactory object.

Parameters:
algorithm - the name of the algorithm for which to get a KeyFactory
Returns:
the KeyFactory engine
Throws:
NoSuchAlgorithmException - if no KeyFactory is available for the requested algorithm

wrapKey

public byte[] wrapKey(SecretKey cek,
                      AlgorithmID kea,
                      Key kek,
                      AlgorithmParameters params)
               throws NoSuchAlgorithmException,
                      InvalidKeyException,
                      InvalidAlgorithmParameterException,
                      IllegalBlockSizeException,
                      BadPaddingException
Wraps the given secret content encryption key for a KEKRecipientInfo or KeyAgreeRecipientInfo, or PasswordRecipientInfo.

The given secret content encryption key is wrapped by encrypting it with the given secret key encryption key using the requested key encryption algorithm. If algorithm parameters are supplied they are used for initializing the key encryption cipher. Attention: If algorithm parameters are to be used (or produced by the cipher) this method has to include them into the parameters field of the supplied key encryption AlgorithmID, too (this only may work if the Cipher engine supports method getParameters.

Parameters:
cek - the secret content encryption key to be wrapped (encrypted)
kea - the key wrap (encryption) alglorithm to be used, e.g. 3DESKeyWrap
kek - the key encryption key to be used for encrypting the content encryption key
params - any algorithm parameters required for initializing the key encryption cipher
Returns:
the wrapped (encrypted) content encryption key as byte array
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the key encryption key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid
IllegalBlockSizeException - if the block size is not correct
BadPaddingException - if an padding error occurs

unwrapKey

public SecretKey unwrapKey(byte[] wrappedCek,
                           AlgorithmID kea,
                           Key kek,
                           AlgorithmParameters params,
                           String cekAlgName)
                    throws NoSuchAlgorithmException,
                           InvalidKeyException,
                           InvalidAlgorithmParameterException
Unwraps the given wrapped (encrypted) secret content encryption key for a KEKRecipientInfo or KeyAgreeRecipientInfo, or PasswordRecipientInfo.

The given wrapped secret content encryption key is unwrapped by decrypting it with the given secret key encryption key using the requested key encryption algorithm. If algorithm parameters are supplied they are used for initializing the key (un)wrapping cipher.

Parameters:
wrappedCek - the wrapped secret content encryption key to be unwrapped (decrypted)
kea - the key (un)wrap (en/decryption) alglorithm to be used, e.g. 3DESKeyWrap
kek - the key encryption key to be used for decrypting the encrypted content encryption key
params - any algorithm parameters required for initializing the cipher
cekAlgName - the name of the content encryption cipher (required by the unwrap method of a JCE cipher engine)
Returns:
the unwrapped decrypted) content encryption key
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the key encryption key is not valid
InvalidAlgorithmParameterException - if the parameters are not valid

createSharedKeyEncryptionKey

public SecretKey createSharedKeyEncryptionKey(AlgorithmID keyAgreeAlg,
                                              PrivateKey myKey,
                                              PublicKey otherKey,
                                              AlgorithmID kea,
                                              int kekLength,
                                              byte[] ukm,
                                              String kekName)
                                       throws NoSuchAlgorithmException,
                                              InvalidKeyException,
                                              InvalidAlgorithmParameterException
Create a shared secret key encryption key for the given key agree algorithm.

Creating a shared key encryption key is required when a key agreement algorithm is used as key management protocol for the recipient of an EnvelopedData or AuthenticatedData object. The shared key encryption key will be used by an KeyAgreeRecipientInfo to encrypt the secret content encryption key or Mac key.

Attention: This method ALWAYS throws an exception since there is no general way for initializing a ESDH KeyAgreement with an IAIK ESDHKEKParameterSpec (representing the RFC2631 OtherInfo). When using a different provider than IAIK this method has to be overriden to create the shared key! For the IAIK cryptography provider this method is overriden for ESDH key agreement.

Parameters:
keyAgreeAlg - the key agreement algorithm
myKey - the private key agreement key of the one party
otherKey - the public key agreement key of the other party
kea - the key ancryption algorithm (may be required for kek generation)
kekLength - the length of the shared key encryption key to be generated
ukm - any user keying material that may be required for kek generation
kekName - the name of the key encryption algorithm
Returns:
the shared key encryption key generated
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if there is a key related problem
InvalidAlgorithmParameterException - if the parameters are invalid

checkDomainParameters

public void checkDomainParameters(PrivateKey myKey,
                                  PublicKey otherKey)
                           throws InvalidParameterException
Checks if the given private and public key agreement keys have the same domain parameters.

Only for DH key agreement there is a general way to access the parameters of DH keys through the JCE API. CMS, however, per default uses ephemeral static DH (ESDH) (EnvelopedData, AuthenticatedData). For also supporting ESDH in a general way this method tries to get the parameters from the key Algorithm IDs and compares their encodings if the supplied keys are not standard JCE DH keys. Since this proceeding invloves some encoding - decoding overhead, it might be appropriate to override this method for an ESDH supporting provider (as done for IAIK by the IaikProvider.

Parameters:
myKey - the private key of the first party
otherKey - the public key of the other party
Throws:
InvalidParameterEyception - if domain parameters are included in both keys, but the domain parameters do not match
InvalidParameterException

generateKeyAgreementKeyPair

public KeyPair generateKeyAgreementKeyPair(AlgorithmID keyAgreeAlgorithm,
                                           PublicKey otherKey)
                                    throws NoSuchAlgorithmException,
                                           InvalidKeyException,
                                           InvalidAlgorithmParameterException
Generates a key pair with same domain parameters of the given public key for the given key agreement method. Attention: This method ALWAYS throws an exception since there is no general way for initializing a KeyPairGenerator with algorithm parameters. When using a different provider as IAIK this method has to be overriden to create the requested key pair! For the IAIK cryptography provider this method is overriden for (ES)DH key agreement methods to use its (ES)DH KeyPairGenerator witch can be initialized with the parameters of the public key of the other party.

This method is called by the library for creating the originator key pair if the OriginatorPublicKey alternative is used for representing the public key of the originator within a KeyAgreeRecipientInfo. The public key supplied to this method is the one of the recipient and the key pair returned by this method must have domain parameters matching to those of the given recipient public key. Note that ephemeral static Diffie Hellmean (ESDH) is the default key agreement method used by the CMS types EnvelopedData and AuthenticatedData. According RFC 5652 the OriginatorPublicKey has to be used for representing the public key of the originator if ESDH is used as key agreement algorithm.

Parameters:
keyAgreeAlgorithm - the key agreement algorithm to be used
otherKey - the public key of the other party
Returns:
the originator key pair with domain parameters matching to those of the supplied key of the other party
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeyException - if the key is not appropriate for the key agreement algorithm
InvalidAlgorithmParameterException - if the parameters are invalid

getASN1OriginatorPublicKey

public ASN1Object getASN1OriginatorPublicKey(PublicKey originatorPublicKey)
                                      throws CMSException
Gets an ASN.1 representation of the provided originator public key.

For some key agree algorithms CMS may require a special key encoding for the KeyAgreeRecipientInfo OriginatorPublicKey choice. According to RFC 3370 (Cryptographic Message Syntax Algorithms), ESDH public keys have to be encoded with absent parameters in their AlgorithmID field when encoded as originator public keys:

 The originatorKey algorithm field MUST contain the dh-public-number
 object identifier with absent parameters.  The originatorKey
 publicKey field MUST contain the ephemeral public key of the sender.
 
This method tries to get an ASN.1 representation of the suppiled originator public key. Since it only can handle keys in a general way it simple calls
 DerCoder.decode(originatorPublicKey.getEncoded());  
 
An application may override this method to handle keys in a provider-specific manner.

Parameters:
originatorPublicKey - the originator public key from which to get an ASN.1 representation
Returns:
the ASN.1 representation of the originator public key
Throws:
CMSException - if the key cannot be ASN.1 represented

getOriginatorPublicKey

public PublicKey getOriginatorPublicKey(ASN1Object obj)
                                 throws CMSException
Decodes the OriginatorPublicKey from the given ASN1Object.

For some key agree algorithms CMS may require a special key encoding for the OriginatorPublicKey of a KeyAgreeRecipientInfo. This method tries to create a PublicKey from the given ASN1Object by using a general KeyFactory. An application may override this method to handle keys in a provider-specific manner.

Parameters:
obj - the OriginatorPublicKey as ASN1Object
Returns:
the originator public key
Throws:
CMSException - if the ASN1Object cannot be decoded or is invalid structured

getAlgorithmParameters

public AlgorithmParameters getAlgorithmParameters(AlgorithmID algorithm)
                                           throws NoSuchAlgorithmException
Gets the algorithm parameters from the given AlgorithmID.

Parameters:
algorithm - the AlgorithmID from which to extract the parameters.
Returns:
the algorithm parameters or null if no parameters are included
Throws:
NoSuchAlgorithmException - if no AlgorithmParameters for the requested algorithm are available

getAlgorithmParameters

public AlgorithmParameters getAlgorithmParameters(AlgorithmID algorithmID,
                                                  String algorithm)
                                           throws NoSuchAlgorithmException
Gets the algorithm parameters with the given name from the given AlgorithmID.

Parameters:
algorithmID - the AlgorithmID from which to extract the parameters
algorithm - the name of the algorithm the parameters belong to
Returns:
the algorithm parameters or null if no parameters are included
Throws:
NoSuchAlgorithmException - if no AlgorithmParameters for the requested algorithm are available

getAlgorithmParameters

public AlgorithmParameters getAlgorithmParameters(String algorithm)
                                           throws NoSuchAlgorithmException
Gets an AlgorithmParameters instance for the requested algorithm.

In contrast to

Parameters:
algorithm - the name of the algorithm for which AlgorithmParameters are requested
Returns:
the AlgorithmParameters instance for the requested algorithm
Throws:
NoSuchAlgorihmException - if no AlgorithmParameters for the requested algorithm are available
NoSuchAlgorithmException

getAlgorithmParameterSpec

public AlgorithmParameterSpec getAlgorithmParameterSpec(AlgorithmID algID)
                                                 throws InvalidParameterSpecException
Gets algorithm parameter specification from the given AlgorithmID.

This method returns null in any case since there is no general way to get an AlgorithmParameterSpec from an AlgorithmID object in provider and algorithm independent way. A SecurityProvider implementation may override this method for some specific crypto provider.

The library uses this method to get paramaters from an RSA-PSS signature algorithm id, or from an MAC algorithm id.

Parameters:
algID - the AlgorithmID from which to get the parameter specification
Returns:
null in any case since cannot be handled in provider independent way (may be overriden by a specific provider implementation)
Throws:
InvalidParameterException - if an error occurs when trying to fetch the algorithm parameter specification
InvalidParameterSpecException

getPBEKey

public Key getPBEKey(char[] password,
                     AlgorithmID pbeAlg)
              throws NoSuchAlgorithmException,
                     InvalidKeySpecException
Creates secret key from the supplied password using the specified PBE algorithm.

Parameters:
password - the password for creating the secret key
pbeAlg - the PBE algorithm to be used
Returns:
the secret key
Throws:
NoSuchAlgorithmException - if the requested algorithm is not available
InvalidKeySpecException - if the key cannot be created from the password specification

deriveKey

public Key deriveKey(char[] password,
                     AlgorithmID keyDerivationAlg,
                     AlgorithmParameterSpec paramSpec)
              throws NoSuchAlgorithmException,
                     InvalidAlgorithmParameterException
Uses the requested key derivation function to create a secret key from the supplied password.

Parameters:
password - the password for creating the secret key
keyDerivationAlg - the key derivation function to be used
paramSpec - any required algorithm parameters; may be null if no parameters are required or the parameters are supplied via the AlgorithmID; may also contain the password in which case the password parameter maybe null
Returns:
the secret key
Throws:
NoSuchAlgorithmException - if the requested key derivation function is not available
InvalidAlgorithmParameterException - if the parameters are invalid or cannot be parsed from the AlgorithmID

getKeyLength

public int getKeyLength(Key key)
Calculates the length of the given key.

Parameters:
key - the key for which to calculate the length
Returns:
the length of the key (in bits for private/public keys; in bytes for secret keys)
Throws:
IllegalArgumentException - if the public key algorithm is not supported

getKeyLength

public int getKeyLength(PublicKey pubKey)
Calculates the length of the given public key.

Parameters:
pubKey - the public key for which to calculate the length
Returns:
the length (in bits) of the public key
Throws:
IllegalArgumentException - if the public key algorithm is not supported

getKeyLength

public int getKeyLength(PrivateKey privKey)
Calculates the length of the given private key.

Parameters:
privKey - the public key for which to calculate the length
Returns:
the length (in bits) of the private key
Throws:
IllegalArgumentException - if the private key algorithm is not supported

getSecureRandom

public SecureRandom getSecureRandom()
Returns the random number generator.

Attention This method does not synchronize on the random number generator of this SecurityProvider. If required, an application may take care for synchronizing itself or may ensure to set the random number generator at application startup. By default this method returns a new SecureRandom anytime when called. However, when a SecureRandom has been explicitly set by calling method setSecureRandom, this SecureRandom is returned.

Returns:
the randon number generator

setSecureRandom

public void setSecureRandom(SecureRandom random)
Sets the random number generator.

Attention This method does not synchronize on the random number generator of this SecurityProvider. If required, an application may take care for synchronizing itself or may ensure to set the random number generator at application startup. When using this method to set a SecureRandom object, this SecureRandom is used throughout the whole application. If not explicitly set, method getSecureRandom returns a new SecureRandom anytime when called.

Parameters:
random - the secure random to be set

convertCipherMode

public static int convertCipherMode(int mode)
Converts the SecurityProvider Cipher mode to the javax.crypto Cipher mode.

CIPHER_ENCRYPT --> Cipher.ENCRYPT_MODE CIPHER_DECRYPT --> Cipher.DECRYPT_MODE CIPHER_WRAP --> Cipher.WRAP_MODE CIPHER_UNWRAP --> Cipher.UNWRAP_MODE

Returns:
the java.crypto Cipher mode

getMicAlgs

public AlgorithmID[] getMicAlgs(String micalg)
Returns an array of AlgorithmIDs specified by the given micalg String.

The micalg parameter of an multipart/signed message may specify more than only one hash algorithm, separated by commas. This method steps through the algorithm names and tries to get the corresponding AlgorithmIDs.

Parameters:
micalg - the micalg parameters string, e.g. "sha1"
Returns:
an array of AlgorithmIDs for the hash algorithms specified in the micag string

This Javadoc may contain text parts from text parts from IETF Internet Standard specifications (see copyright note).

IAIK-CMS 5.0, (c) 2002 IAIK, (c) 2003 - 2010 SIC