IAIK PKCS#11 Wrapper
version 1.5

iaik.pkcs.pkcs11
Class Session

java.lang.Object
  |
  +--iaik.pkcs.pkcs11.Session

public class Session
extends java.lang.Object

Session objects are used to perform cryptographic operations on a token. The application gets a Session object by calling openSession on a certain Token object. Having the session object, the application may log-in the user, if required.

 
   TokenInfo tokenInfo = token.getTokenInfo();
   // check, if log-in of the user is required at all
   if (tokenInfo.isLoginRequired()) {
     // check, if the token has own means to authenticate the user; e.g. a PIN-pad on the reader
     if (tokenInfo.isProtectedAuthenticationPath()) {
       System.out.println("Please enter the user PIN at the PIN-pad of your reader.");
       session.login(Session.UserType.USER, null); // the token prompts the PIN by other means; e.g. PIN-pad
     } else {
       System.out.print("Enter user-PIN and press [return key]: ");
       System.out.flush();
       BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
       String userPINString = input.readLine();
       session.login(Session.UserType.USER, userPINString.toCharArray());
     }
   }
 
 
With this session object the application can search for token objects and perform a cryptographic operation. For example, to find private RSA keys that the application can use for signing, you can write:
 
   RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();
   privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
 
   session.findObjectsInit(privateSignatureKeyTemplate);
   Object[] privateSignatureKeys;
 
   List signatureKeyList = new Vector(4);
   while ((privateSignatureKeys = session.findObjects(1)).length > 0) {
     signatureKeyList.add(privateSignatureKeys[0]);
   }
   session.findObjectsFinal();
 
 
Having chosen one of this keys, the application can create a signature value using it.
 
   // e.g. the encoded digest info object that contains an identifier of the
   // hash algorithm and the hash value
   byte[] toBeSigned;
 
   // toBeSigned = ... assign value
 
   RSAPrivateKey selectedSignatureKey;
 
   // selectedSignatureKey = ... assign one of the available signature keys
 
   // initialize for signing
   session.signInit(Mechanism.RSA_PKCS, selectedSignatureKey);
 
   // sign the data to be signed
   byte[] signatureValue = session.sign(toBeSigned);
 
 
If the application does not need the session any longer, it should close the session.
 
   session.closeSession();
 
 

Version:
1.0
Author:
Karl Scheibelhofer
See Also:
Object, Parameters, Session, SessionInfo

Inner Class Summary
static interface Session.UserType
          This interface defines the different user types of PKCS#11.
 
Field Summary
protected  Module module_
          A reference to the underlying PKCS#11 module to perform the operations.
protected  PKCS11 pkcs11Module_
          A reference to the underlying PKCS#11 module to perform the operations.
protected  long sessionHandle_
          The session handle to perform the operations with.
protected  Token token_
          The token to perform the operations on.
 
Constructor Summary
protected Session(Token token, long sessionHandle)
          Constructor taking the token and the session handle.
 
Method Summary
 void cancelFunction()
          Legacy function that will normally throw an PKCS11Exception with the error-code PKCS11Constants.CKR_FUNCTION_NOT_PARALLEL.
 void closeSession()
          Closes this session.
 Object copyObject(Object sourceObject, Object templateObject)
          Copy an existing object.
 Object createObject(Object templateObject)
          Create a new object on the token (or in the session).
 byte[] decrypt(byte[] data)
          Decrypts the given data with the key and mechansim given to the decryptInit method.
 byte[] decryptDigestUpdate(byte[] part)
          Dual-function.
 byte[] decryptFinal()
          This method finalizes a decrpytion operation and returns the final result.
 void decryptInit(Mechanism mechanism, Key key)
          Initializes a new decryption operation.
 byte[] decryptUpdate(byte[] encryptedPart)
          This method can be used to decrypt multiple pieces of data; e.g.
 byte[] decryptVerifyUpdate(byte[] encryptedPart)
          Dual-function.
 Key deriveKey(Mechanism mechanism, Key baseKey, Key template)
          Derives a new key from a specified base key unsing the given mechanism.
 void destroyObject(Object object)
          Destroy a certain object on the token (or in the session).
 byte[] digest(byte[] data)
          Digests the given data with the mechansim given to the digestInit method.
 byte[] digestEncryptedUpdate(byte[] part)
          Dual-function.
 byte[] digestFinal()
          This method finalizes a digesting operation and returns the final result.
 void digestInit(Mechanism mechanism)
          Initializes a new digesting operation.
 void digestKey(SecretKey key)
          This method is similar to digestUpdate and can be combined with it during one digesting operation.
 void digestUpdate(byte[] part)
          This method can be used to digest multiple pieces of data; e.g.
 byte[] encrypt(byte[] data)
          Encrypts the given data with the key and mechansim given to the encryptInit method.
 byte[] encryptFinal()
          This method finalizes an encrpytion operation and returns the final result.
 void encryptInit(Mechanism mechanism, Key key)
          Initializes a new encryption operation.
 byte[] encryptUpdate(byte[] part)
          This method can be used to encrypt multiple pieces of data; e.g.
 boolean equals(java.lang.Object otherObject)
          Compares the sessionHandle and token_ of this object with the other object.
 Object[] findObjects(int maxObjectCount)
          Finds objects that match the template object passed to findObjectsInit.
 void findObjectsFinal()
          Finalizes a find operation.
 void findObjectsInit(Object templateObject)
          Initializes a find operations that provides means to find objects by passing a template object.
 Object generateKey(Mechanism mechanism, Object template)
          Generate a new secret key or a set of domain parameters.
 KeyPair generateKeyPair(Mechanism mechanism, Object publicKeyTemplate, Object privateKeyTemplate)
          Generate a new public key - private key key-pair and use the set attributes of the template objects for setting the attributes of the new public key and private key objects.
 byte[] generateRandom(int numberOfBytesToGenerate)
          Generates a certain number of random bytes.
 Object getAttributeValues(Object objectToRead)
          Reads all the attributes of the given Object from the token and returns a new Object that contains all these attributes.
 void getFunctionStatus()
          Legacy function that will normally throw an PKCS11Exception with the error-code PKCS11Constants.CKR_FUNCTION_NOT_PARALLEL.
 Module getModule()
          Get the Module which this Session object operates with.
 long getObjectSize(Object object)
          Get the size of the specified object in bytes.
 byte[] getOperationState()
          Get the current operation state.
 long getSessionHandle()
          Get the handle of this session.
 SessionInfo getSessionInfo()
          Get information about this session.
 Token getToken()
          Get the token that created this Session object.
 int hashCode()
          The overriding of this method should ensure that the objects of this class work correctly in a hashtable.
 void initPIN(char[] pin)
          Initializes the user-PIN.
 boolean isSetUtf8Encoding()
          Returns whether UTF8 encoding is set.
 void login(boolean userType, char[] pin)
          Logs in the user or the security officer to the session.
 void logout()
          Logs out this session.
 void seedRandom(byte[] seed)
          Mixes additional seeding material into the random number generator.
 void setAttributeValues(Object objectToUpdate, Object templateObject)
          Gets all present attributes of the given template object an writes them to the object to update on the token (or in the session).
 void setOperationState(byte[] operationState, Key encryptionKey, Key authenticationKey)
          Sets the operation state of this session to a previously saved one.
 void setPIN(char[] oldPin, char[] newPin)
          Set the user-PIN to a new value.
 byte[] sign(byte[] data)
          Signs the given data with the key and mechansim given to the signInit method.
 byte[] signEncryptUpdate(byte[] part)
          Dual-function.
 byte[] signFinal()
          This method finalizes a signing operation and returns the final result.
 void signInit(Mechanism mechanism, Key key)
          Initializes a new signing operation.
 byte[] signRecover(byte[] data)
          Signs the given data with the key and mechansim given to the signRecoverInit method.
 void signRecoverInit(Mechanism mechanism, Key key)
          Initializes a new signing operation for signing with recovery.
 void signUpdate(byte[] part)
          This method can be used to sign multiple pieces of data; e.g.
 java.lang.String toString()
          Returns the string representation of this object.
 Key unwrapKey(Mechanism mechanism, Key unwrappingKey, byte[] wrappedKey, Object keyTemplate)
          Unwraps (decrypts) the given encrypted key with the unwrapping key using the given mechanism.
 void verify(byte[] data, byte[] signature)
          Verifies the given signature against the given data with the key and mechansim given to the verifyInit method.
 void verifyFinal(byte[] signature)
          This method finalizes a verification operation.
 void verifyInit(Mechanism mechanism, Key key)
          Initializes a new verification operation.
 byte[] verifyRecover(byte[] signature)
          Signs the given data with the key and mechansim given to the signRecoverInit method.
 void verifyRecoverInit(Mechanism mechanism, Key key)
          Initializes a new verification operation for verification with data recovery.
 void verifyUpdate(byte[] part)
          This method can be used to verify a signature with multiple pieces of data; e.g.
 byte[] wrapKey(Mechanism mechanism, Key wrappingKey, Key key)
          Wraps (encrypts) the given key with the wrapping key using the given mechanism.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

module_

protected Module module_
A reference to the underlying PKCS#11 module to perform the operations.

pkcs11Module_

protected PKCS11 pkcs11Module_
A reference to the underlying PKCS#11 module to perform the operations.

sessionHandle_

protected long sessionHandle_
The session handle to perform the operations with.

token_

protected Token token_
The token to perform the operations on.
Constructor Detail

Session

protected Session(Token token,
                  long sessionHandle)
Constructor taking the token and the session handle.
Parameters:
token - The token this session operates with.
sessionHandle - The session handle to perform the operations with.
Method Detail

initPIN

public void initPIN(char[] pin)
             throws TokenException
Initializes the user-PIN. Can only be called from a read-write security officer session. May be used to set a new user-PIN if the user-PIN is locked.
Parameters:
pin - The new user-PIN. This parameter may be null, if the token has a protected authentication path. Refer to the PKCS#11 standard for details.
Throws:
TokenException - If the session has not the right to set the PIN of if the operation fails for some other reason.

setPIN

public void setPIN(char[] oldPin,
                   char[] newPin)
            throws TokenException
Set the user-PIN to a new value. Can only be called from a read-write sessions.
Parameters:
oldPin - The old (current) user-PIN.
newPin - The new value for the user-PIN.
Throws:
TokenException - If setting the new PIN fails.

closeSession

public void closeSession()
                  throws TokenException
Closes this session.
Throws:
TokenException - If closing the session failed.

equals

public boolean equals(java.lang.Object otherObject)
Compares the sessionHandle and token_ of this object with the other object. Returns only true, if those are equal in both objects.
Overrides:
equals in class java.lang.Object
Parameters:
otherObject - The other Session object.
Returns:
True, if other is an instance of Token and the session handles and tokens of both objects are equal. False, otherwise.

hashCode

public int hashCode()
The overriding of this method should ensure that the objects of this class work correctly in a hashtable.
Overrides:
hashCode in class java.lang.Object
Returns:
The hash code of this object. Gained from the sessionHandle.

getSessionHandle

public long getSessionHandle()
Get the handle of this session.
Returns:
The handle of this session.

getSessionInfo

public SessionInfo getSessionInfo()
                           throws TokenException
Get information about this session.
Returns:
An object providing information about this session.
Throws:
TokenException - If getting the information failed.

getModule

public Module getModule()
Get the Module which this Session object operates with.
Returns:
The module of this session.

getToken

public Token getToken()
Get the token that created this Session object.
Returns:
The token of this session.

getOperationState

public byte[] getOperationState()
                         throws TokenException
Get the current operation state. This state can be used later to restore the operation to exactly this state.
Returns:
The current operation state as a byte array.
Throws:
TokenException - If saving the state fails or is not possible.
See Also:
setOperationState(byte[],Key,Key)

setOperationState

public void setOperationState(byte[] operationState,
                              Key encryptionKey,
                              Key authenticationKey)
                       throws TokenException
Sets the operation state of this session to a previously saved one. This method may need the key used during the saved operation to continue, because it may not be possible to save a key into the state's byte array. Refer to the PKCS#11 standard for details on this function.
Parameters:
operationState - The previously saved state as returned by getOperationState().
encryptionKey - A encryption or decryption key, if a encryption or decryption operation was saved which should be continued, but the keys could not be saved.
authenticationKey - A signing, verification of MAC key, if a signing, verification or MAC operation needs to be restored that could not save the key.
Throws:
TokenException - If restoring the state fails.
See Also:
getOperationState()

isSetUtf8Encoding

public boolean isSetUtf8Encoding()
Returns whether UTF8 encoding is set.
Returns:
true, if UTF8 is used as character encoding for character array attributes and PINs.

login

public void login(boolean userType,
                  char[] pin)
           throws TokenException
Logs in the user or the security officer to the session. Notice that all sessions of a token have the same login state; i.e. if you login the user to one session all other open sessions of this token get user rights.
Parameters:
userType - UserType.SO for the security officer or UserType.USER to login the user.
pin - The PIN. The security officer-PIN or the user-PIN depending on the userType parameter.
Throws:
TokenException - If login fails.

logout

public void logout()
            throws TokenException
Logs out this session.
Throws:
TokenException - If logging out the session fails.

createObject

public Object createObject(Object templateObject)
                    throws TokenException
Create a new object on the token (or in the session). The application must provide a template that holds enough information to create a certain object. For instance, if the application wants to create a new DES key object it creates a new instance of the DESSecretKey class to serve as a template. The application must set all attributes of this new object which are required for the creation of such an object on the token. Then it passes this DESSecretKey object to this method to create the object on the token. Example: DESSecretKey desKeyTemplate = new DESSecretKey(); // the key type is set by the DESSecretKey's constructor, so you need not do it desKeyTemplate.setValue(myDesKeyValueAs8BytesLongByteArray); desKeyTemplate.setToken(Boolean.TRUE); desKeyTemplate.setPrivate(Boolean.TRUE); desKeyTemplate.setEncrypt(Boolean.TRUE); desKeyTemplate.setDecrypt(Boolean.TRUE); ... DESSecretKey theCreatedDESKeyObject = (DESSecretKey) userSession.createObject(desKeyTemplate); Refer to the PKCS#11 standard to find out what attributes must be set for certain types of objects to create them on the token.
Parameters:
templateObject - The template object that holds all values that the new object on the token should contain. (this is not a java.lang.Object!)
Returns:
A new PKCS#11 Object (this is not a java.lang.Object!) that serves holds all the (readable) attributes of the object on the token. In contrast to the templateObject, this object might have certain attributes set to token-dependent default-values.
Throws:
TokenException - If the creation of the new object fails. If it fails, the no new object was created on the token.

copyObject

public Object copyObject(Object sourceObject,
                         Object templateObject)
                  throws TokenException
Copy an existing object. The source object and a template object are given. Any value set in the template object will override the corresponding value from the source object, when the new object ist created. See the PKCS#11 standard for details.
Parameters:
sourceObject - The source object of the copy operation.
templateObject - A template object which's attribute values are used for the new object; i.e. they have higher priority than the attribute values from the source object. May be null; in that case the new object is just a one-to-one copy of the sourceObject.
Returns:
The new object that is created by copying the source object and setting attributes to the values given by the templateObject.
Throws:
TokenException - If copying the object fails for some reason.

setAttributeValues

public void setAttributeValues(Object objectToUpdate,
                               Object templateObject)
                        throws TokenException
Gets all present attributes of the given template object an writes them to the object to update on the token (or in the session). Both parameters may refer to the same Java object. This is possible, because this method only needs the object handle of the objectToUpdate, and gets the attributes to set from the template. This means, an application can get the object using createObject of findObject, then modify attributes of this Java object and then call this method passing this object as both parameters. This will update the object on the token to the values as modified in the Java object.
Parameters:
objectToUpdate - The attributes of this object get updated.
templateObject - This methods gets all present attributes of this template object and set this attributes at the objectToUpdate.
Throws:
TokenException - If updateing the attributes fails. All or no attributes are updated.

getAttributeValues

public Object getAttributeValues(Object objectToRead)
                          throws TokenException
Reads all the attributes of the given Object from the token and returns a new Object that contains all these attributes. The given objectToRead and the returned Object are different Java objects. This method just uses the object handle of the given object, it does not modify anything in this object.
Parameters:
objectToRead - The object to newly read from the token.
Returns:
A new Object holding all attributes that this method just read from the token.
Throws:
TokenException - If reading the attributes fails.

destroyObject

public void destroyObject(Object object)
                   throws TokenException
Destroy a certain object on the token (or in the session). Give the object that you want to destroy. This method uses only the internal object handle of the given object to identify the object.
Parameters:
object - The object that should be destroyed.
Throws:
TokenException - If the object could not be destroyed.

getObjectSize

public long getObjectSize(Object object)
                   throws TokenException
Get the size of the specified object in bytes. This size specifies how much memory the object takes up on the token.
Parameters:
object - The object to get the size for.
Returns:
The object's size bytes.
Throws:
TokenException - If determining the size fails.

findObjectsInit

public void findObjectsInit(Object templateObject)
                     throws TokenException
Initializes a find operations that provides means to find objects by passing a template object. This method get all set attributes of the template object ans searches for all objects on the token that match with these attributes.
Parameters:
templateObject - The object that serves as a template for searching. If this object is null, the find operation will find all objects that this session can see. Notice, that only a user session will see private objects.
Throws:
TokenException - If initializing the find operation fails.

findObjects

public Object[] findObjects(int maxObjectCount)
                     throws TokenException
Finds objects that match the template object passed to findObjectsInit. The application must call findObjectsInit before calling this method. With maxObjectCount the application can specifay how many objects to return at once; i.e. the application can get all found objects by susequent calls to this method like maxObjectCount(1) until it receives an empty array (this method never returns null!).
Parameters:
maxObjectCount - Specifies how many objects to return with this call.
Returns:
An array of found objects. The maximum size of this array is maxObjectCount, the minimum length is 0. Never returns null.
Throws:
TokenException - A plain TokenException if something during PKCS11 FindObject went wrong, a TokenException with a nested TokenException if the Exception is raised during object parsing.

findObjectsFinal

public void findObjectsFinal()
                      throws TokenException
Finalizes a find operation. The application must call this method to finalize a find operation before attempting to start any other operation.
Throws:
TokenException - If finalizing the current find operation was not possible.

encryptInit

public void encryptInit(Mechanism mechanism,
                        Key key)
                 throws TokenException
Initializes a new encryption operation. The application must call this method before calling any other encrypt* operation. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for encrpytion and the key for this oepration. The key must have set its encryption flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.DES_CBC.
key - The decryption key to use.
Throws:
TokenException - If initializing this operation failed.

encrypt

public byte[] encrypt(byte[] data)
               throws TokenException
Encrypts the given data with the key and mechansim given to the encryptInit method. This method finalizes the current encryption operation; i.e. the application need (and should) not call encryptFinal() after this call. For encrypting multiple pices of data use encryptUpdate and encryptFinal.
Parameters:
data - The data to encrpyt.
Returns:
The encrpyted data.
Throws:
TokenException - If encrypting failed.

encryptUpdate

public byte[] encryptUpdate(byte[] part)
                     throws TokenException
This method can be used to encrypt multiple pieces of data; e.g. buffer-size pieces when reading the data from a stream. Encrypts the given data with the key and mechansim given to the encryptInit method. The application must call encryptFinal to get the final result of the encryption after feeding in all data using this method.
Parameters:
part - The piece of data to encrpt.
Returns:
The intermediate encryption result. May not be available. To get the final result call encryptFinal.
Throws:
TokenException - If encrypting the data failed.

encryptFinal

public byte[] encryptFinal()
                    throws TokenException
This method finalizes an encrpytion operation and returns the final result. Use this method, if you fed in the data using encryptUpdate. If you used the encrypt(byte[]) method, you need not (and shall not) call this method, because encrypt(byte[]) finalizes the encryption itself.
Returns:
The final result of the encryption; i.e. the encrypted data.
Throws:
TokenException - If calculating the final result failed.

decryptInit

public void decryptInit(Mechanism mechanism,
                        Key key)
                 throws TokenException
Initializes a new decryption operation. The application must call this method before calling any other decrypt* operation. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for decrpytion and the key for this oepration. The key must have set its decryption flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.DES_CBC.
key - The decryption key to use.
Throws:
TokenException - If initializing this operation failed.

decrypt

public byte[] decrypt(byte[] data)
               throws TokenException
Decrypts the given data with the key and mechansim given to the decryptInit method. This method finalizes the current decryption operation; i.e. the application need (and should) not call decryptFinal() after this call. For decrypting multiple pices of data use decryptUpdate and decryptFinal.
Parameters:
data - The data to decrpyt.
Returns:
The decrpyted data.
Throws:
TokenException - If decrypting failed.

decryptUpdate

public byte[] decryptUpdate(byte[] encryptedPart)
                     throws TokenException
This method can be used to decrypt multiple pieces of data; e.g. buffer-size pieces when reading the data from a stream. Decrypts the given data with the key and mechansim given to the decryptInit method. The application must call decryptFinal to get the final result of the encryption after feeding in all data using this method.
Parameters:
encryptedPart - The piece of data to decrpt.
Returns:
The intermediate decryption result. May not be available. To get the final result call decryptFinal.
Throws:
TokenException - If decrypting the data failed.

decryptFinal

public byte[] decryptFinal()
                    throws TokenException
This method finalizes a decrpytion operation and returns the final result. Use this method, if you fed in the data using decryptUpdate. If you used the decrypt(byte[]) method, you need not (and shall not) call this method, because decrypt(byte[]) finalizes the decryption itself.
Returns:
The final result of the decryption; i.e. the decrypted data.
Throws:
TokenException - If calculating the final result failed.

digestInit

public void digestInit(Mechanism mechanism)
                throws TokenException
Initializes a new digesting operation. The application must call this method before calling any other digest* operation. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for digesting for this oepration. For the mechanism the application may use a constant defined in the Mechanism class.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.SHA_1.
Throws:
TokenException - If initializing this operation failed.

digest

public byte[] digest(byte[] data)
              throws TokenException
Digests the given data with the mechansim given to the digestInit method. This method finalizes the current digesting operation; i.e. the application need (and should) not call digestFinal() after this call. For digesting multiple pices of data use digestUpdate and digestFinal.
Parameters:
data - The data to digest.
Returns:
The digested data.
Throws:
TokenException - If digesting the data failed.

digestUpdate

public void digestUpdate(byte[] part)
                  throws TokenException
This method can be used to digest multiple pieces of data; e.g. buffer-size pieces when reading the data from a stream. Digests the given data with the mechansim given to the digestInit method. The application must call digestFinal to get the final result of the digesting after feeding in all data using this method.
Parameters:
part - The piece of data to digest.
Throws:
TokenException - If digesting the data failed.

digestKey

public void digestKey(SecretKey key)
               throws TokenException
This method is similar to digestUpdate and can be combined with it during one digesting operation. This method digests the value of the given secret key.
Parameters:
key - The key to digest the value of.
Throws:
TokenException - If digesting the key failed.

digestFinal

public byte[] digestFinal()
                   throws TokenException
This method finalizes a digesting operation and returns the final result. Use this method, if you fed in the data using digestUpdate and/or digestKey. If you used the digest(byte[]) method, you need not (and shall not) call this method, because digest(byte[]) finalizes the digesting itself.
Returns:
The final result of the digesting; i.e. the message digest.
Throws:
TokenException - If calculating the final message digest failed.

signInit

public void signInit(Mechanism mechanism,
                     Key key)
              throws TokenException
Initializes a new signing operation. Use it for signatures and MACs. The application must call this method before calling any other sign* operation. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for signing and the key for this oepration. The key must have set its sign flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.RSA_PKCS.
key - The signing key to use.
Throws:
TokenException - If initializing this operation failed.

sign

public byte[] sign(byte[] data)
            throws TokenException
Signs the given data with the key and mechansim given to the signInit method. This method finalizes the current signing operation; i.e. the application need (and should) not call signFinal() after this call. For signing multiple pices of data use signUpdate and signFinal.
Parameters:
data - The data to sign.
Returns:
The signed data.
Throws:
TokenException - If signing the data failed.

signUpdate

public void signUpdate(byte[] part)
                throws TokenException
This method can be used to sign multiple pieces of data; e.g. buffer-size pieces when reading the data from a stream. Signs the given data with the mechansim given to the signInit method. The application must call signFinal to get the final result of the signing after feeding in all data using this method.
Parameters:
part - The piece of data to sign.
Throws:
TokenException - If signing the data failed.

signFinal

public byte[] signFinal()
                 throws TokenException
This method finalizes a signing operation and returns the final result. Use this method, if you fed in the data using signUpdate. If you used the sign(byte[]) method, you need not (and shall not) call this method, because sign(byte[]) finalizes the signing operation itself.
Returns:
The final result of the signing operation; i.e. the signature value.
Throws:
TokenException - If calculating the final signature value failed.

signRecoverInit

public void signRecoverInit(Mechanism mechanism,
                            Key key)
                     throws TokenException
Initializes a new signing operation for signing with recovery. The application must call this method before calling signRecover. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for signing and the key for this oepration. The key must have set its sign-recover flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.RSA_9796.
key - The signing key to use.
Throws:
TokenException - If initializing this operation failed.

signRecover

public byte[] signRecover(byte[] data)
                   throws TokenException
Signs the given data with the key and mechansim given to the signRecoverInit method. This method finalizes the current sign-recover operation; there is no equivalent method to signUpdate for signing with recovery.
Parameters:
data - The data to sign.
Returns:
The signed data.
Throws:
TokenException - If signing the data failed.

verifyInit

public void verifyInit(Mechanism mechanism,
                       Key key)
                throws TokenException
Initializes a new verification operation. You can use it for verifying signatures and MACs. The application must call this method before calling any other verify* operation. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). There are exceptions for dual-function operations. This method requires the mechansim to use for verification and the key for this oepration. The key must have set its verify flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.RSA_PKCS.
key - The verification key to use.
Throws:
TokenException - If initializing this operation failed.

verify

public void verify(byte[] data,
                   byte[] signature)
            throws TokenException
Verifies the given signature against the given data with the key and mechansim given to the verifyInit method. This method finalizes the current verification operation; i.e. the application need (and should) not call verifyFinal() after this call. For verifying with multiple pices of data use verifyUpdate and verifyFinal. This method throws an exception, if the verification of the signature fails.
Parameters:
data - The data that was signed.
signature - The signature or MAC to verify.
Throws:
TokenException - If verifying the signature fails. This is also the case, if the signature is forged.

verifyUpdate

public void verifyUpdate(byte[] part)
                  throws TokenException
This method can be used to verify a signature with multiple pieces of data; e.g. buffer-size pieces when reading the data from a stream. To verify the signature or MAC call verifyFinal after feeding in all data using this method.
Parameters:
part - The piece of data to verify against.
Throws:
TokenException - If verifying (e.g. digesting) the data failed.

verifyFinal

public void verifyFinal(byte[] signature)
                 throws TokenException
This method finalizes a verification operation. Use this method, if you fed in the data using verifyUpdate. If you used the verify(byte[]) method, you need not (and shall not) call this method, because verify(byte[]) finalizes the verification operation itself. If this method verified the signature successfully, it returns normally. If the verification of the signature fails, e.g. if the signature was forged or the data was modified, this method throws an exception.
Parameters:
signature - The signature value.
Throws:
TokenException - If verifying the signature fails. This is also the case, if the signature is forged.

verifyRecoverInit

public void verifyRecoverInit(Mechanism mechanism,
                              Key key)
                       throws TokenException
Initializes a new verification operation for verification with data recovery. The application must call this method before calling verifyRecover. Before initializing a new operation, any currently pending operation must be finalized using the appropriate *Final method (e.g. digestFinal()). This method requires the mechansim to use for verification and the key for this oepration. The key must have set its verify-recover flag. For the mechanism the application may use a constant defined in the Mechanism class. Notice that the key and the mechanism must be compatible; i.e. you cannot use a DES key with the RSA mechanism.
Parameters:
mechanism - The mechanism to use; e.g. Mechanism.RSA_9796.
key - The verification key to use.
Throws:
TokenException - If initializing this operation failed.

verifyRecover

public byte[] verifyRecover(byte[] signature)
                     throws TokenException
Signs the given data with the key and mechansim given to the signRecoverInit method. This method finalizes the current sign-recover operation; there is no equivalent method to signUpdate for signing with recovery.
Parameters:
signature - The data to sign.
Returns:
The signed data.
Throws:
TokenException - If signing the data failed.

digestEncryptedUpdate

public byte[] digestEncryptedUpdate(byte[] part)
                             throws TokenException
Dual-function. Continues a multipart dual digest and encryption operation. This method call can also be combined with calls to digestUpdate, digestKey and encryptUpdate. Call digestFinal and encryptFinal to get the final results.
Parameters:
part - The piece of data to digest and encrypt.
Returns:
The intermediate result of the encryption.
Throws:
TokenException - If digesting or encrypting the data failed.

decryptDigestUpdate

public byte[] decryptDigestUpdate(byte[] part)
                           throws TokenException
Dual-function. Continues a multipart dual decrypt and digest operation. This method call can also be combined with calls to digestUpdate, digestKey and decryptUpdate. It is the recovered plaintext that gets digested in this method call, not the given encryptedPart. Call digestFinal and decryptFinal to get the final results.
Parameters:
part - The piece of data to decrypt and digest.
Returns:
The intermediate result of the decryption; the decrypted data.
Throws:
TokenException - If decrypting or digesting the data failed.

signEncryptUpdate

public byte[] signEncryptUpdate(byte[] part)
                         throws TokenException
Dual-function. Continues a multipart dual sign and encrypt operation. Calls to this method can also be combined with calls to signUpdate and encryptUpdate. Call signFinal and encryptFinal to get the final results.
Parameters:
part - The piece of data to sign and encrypt.
Returns:
The intermediate result of the encryption; the encrypted data.
Throws:
TokenException - If signing or encrypting the data failed.

decryptVerifyUpdate

public byte[] decryptVerifyUpdate(byte[] encryptedPart)
                           throws TokenException
Dual-function. Continues a multipart dual decrypt and verify operation. This method call can also be combined with calls to decryptUpdate and verifyUpdate. It is the recovered plaintext that gets verified in this method call, not the given encryptedPart. Call decryptFinal and verifyFinal to get the final results.
Parameters:
encryptedPart - The piece of data to decrypt and verify.
Returns:
The intermediate result of the decryption; the decrypted data.
Throws:
TokenException - If decrypting or verifying the data failed.

generateKey

public Object generateKey(Mechanism mechanism,
                          Object template)
                   throws TokenException
Generate a new secret key or a set of domain parameters. It uses the set attributes of the template for setting the attributes of the new key object. As mechanism the application can use a constant of the Mechanism class.
Parameters:
mechanism - The mechanism to generate a key for; e.g. Mechanism.DES to generate a DES key.
template - The template for the new key or domain parameters; e.g. a DESSecretKey object which has set certain attributes.
Returns:
The newly generated secret key or domain parameters.
Throws:
TokenException - If generating a new secert key or domain parameters failed.

generateKeyPair

public KeyPair generateKeyPair(Mechanism mechanism,
                               Object publicKeyTemplate,
                               Object privateKeyTemplate)
                        throws TokenException
Generate a new public key - private key key-pair and use the set attributes of the template objects for setting the attributes of the new public key and private key objects. As mechanism the application can use a constant of the Mechanism class.
Parameters:
mechanism - The mechanism to generate a key for; e.g. Mechanism.RSA to generate a new RSA key-pair.
publicKeyTemplate - The template for the new public key part; e.g. a RSAPublicKey object which has set certain attributes (e.g. public exponent and verify).
privateKeyTemplate - The template for the new private key part; e.g. a RSAPrivateKey object which has set certain attributes (e.g. sign and decrypt).
Returns:
The newly generated key-pair.
Throws:
TokenException - If generating a new key-pair failed.

wrapKey

public byte[] wrapKey(Mechanism mechanism,
                      Key wrappingKey,
                      Key key)
               throws TokenException
Wraps (encrypts) the given key with the wrapping key using the given mechanism.
Parameters:
mechanism - The mechanism to use for wrapping the key.
wrappingKey - The key to use for wrapping (encrypting).
key - The key to wrap (encrypt).
Returns:
The wrapped key as byte array.
Throws:
TokenException - If wrapping the key failed.

unwrapKey

public Key unwrapKey(Mechanism mechanism,
                     Key unwrappingKey,
                     byte[] wrappedKey,
                     Object keyTemplate)
              throws TokenException
Unwraps (decrypts) the given encrypted key with the unwrapping key using the given mechanism. The application can also pass a template key to set certain attributes of the unwrapped key. This creates a key object after unwrapping the key and returns an object representing this key.
Parameters:
mechanism - The mechanism to use for unwrapping the key.
unwrappingKey - The key to use for unwrapping (decrypting).
wrappedKey - The encrypted key to unwrap (decrypt).
keyTemplate - The template for creating the new key object.
Returns:
A key object representing the newly created key object.
Throws:
TokenException - If unwrapping the key or creating a new key object failed.

deriveKey

public Key deriveKey(Mechanism mechanism,
                     Key baseKey,
                     Key template)
              throws TokenException
Derives a new key from a specified base key unsing the given mechanism. After deriving a new key from the base key, a new key object is created and a representation of it is returned. The application can provide a template key to set certain attributes of the new key object.
Parameters:
mechanism - The mechanism to use for deriving the new key from the base key.
baseKey - The key to use as base for derivation.
template - The template for creating the new key object.
Returns:
A key object representing the newly derived (created) key object or null, if the used mechanism uses other means to return its values; e.g. the CKM_SSL3_KEY_AND_MAC_DERIVE mechanism.
Throws:
TokenException - If deriving the key or creating a new key object failed.

seedRandom

public void seedRandom(byte[] seed)
                throws TokenException
Mixes additional seeding material into the random number generator.
Parameters:
seed - The seed bytes to mix in.
Throws:
TokenException - If mixing in the seed failed.

generateRandom

public byte[] generateRandom(int numberOfBytesToGenerate)
                      throws TokenException
Generates a certain number of random bytes.
Parameters:
numberOfBytesToGenerate - The number of random bytes to generate.
Returns:
An array of random bytes with length numberOfBytesToGenerate.
Throws:
TokenException - If generating random bytes failed.

getFunctionStatus

public void getFunctionStatus()
                       throws TokenException
Legacy function that will normally throw an PKCS11Exception with the error-code PKCS11Constants.CKR_FUNCTION_NOT_PARALLEL.
Throws:
TokenException - Throws always an PKCS11Excption.

cancelFunction

public void cancelFunction()
                    throws TokenException
Legacy function that will normally throw an PKCS11Exception with the error-code PKCS11Constants.CKR_FUNCTION_NOT_PARALLEL.
Throws:
TokenException - Throws always an PKCS11Excption.

toString

public java.lang.String toString()
Returns the string representation of this object.
Overrides:
toString in class java.lang.Object
Returns:
the string representation of this object

IAIK PKCS#11 Wrapper
version 1.5

IAIK JavaSecurity Website http://jce.iaik.tugraz.at/

IAIK at Graz University of Technology, Austria, Europe
Copyright 2001-2004, IAIK, Graz University of Technology, Inffeldgasse 16a, 8010 Graz, Austria. All Rights Reserved.
version 1.5