Class PKCS11Token


  • public class PKCS11Token
    extends Object
    This is a PKCS#11 token with session management.
    Author:
    xipki
    • Constructor Detail

      • PKCS11Token

        public PKCS11Token​(Token token,
                           boolean readOnly,
                           char[] pin)
                    throws TokenException
        The simple constructor.
        Parameters:
        token - The token
        readOnly - True if this token is read only, false if read-write.
        pin - The PIN of user type CKU_USER. May be null.
        Throws:
        TokenException - If accessing the PKCS#11 device failed.
      • PKCS11Token

        public PKCS11Token​(Token token,
                           boolean readOnly,
                           long userType,
                           char[] userName,
                           List<char[]> pins,
                           Integer numSessions)
                    throws TokenException
        The advanced constructor.
        Parameters:
        token - The token
        readOnly - True if this token is read only, false if read-write.
        userType - The user type. In general, it is CKU_USER.
        userName - The user name. In general, it is null.
        pins - The PINs. May be null and empty list.
        numSessions - Number of sessions. May be null.
        Throws:
        TokenException - If accessing the PKCS#11 device failed.
    • Method Detail

      • setTimeOutWaitNewSession

        public void setTimeOutWaitNewSession​(int timeOutWaitNewSessionMs)
      • setMaxMessageSize

        public void setMaxMessageSize​(int maxMessageSize)
        Sets the maximal message size sent to the PKCS#11 device in one command.
        Parameters:
        maxMessageSize - the maximal message size in bytes.
      • getMechanisms

        public Set<Long> getMechanisms()
      • getMechanismInfo

        public MechanismInfo getMechanismInfo​(long mechanism)
        Gets the MechanismInfo for given mechanism code.
        Parameters:
        mechanism - The mechanism code.
        Returns:
        the MechanismInfo.
      • 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.
      • 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.
      • closeAllSessions

        public void closeAllSessions()
        Closes all sessions.
      • getTokenId

        public long getTokenId()
        Get the token (slot) identifier of this token.
        Returns:
        the slot identifier of this token.
      • getToken

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

        public boolean isReadOnly()
        Returns whether this token is read-only.
        Returns:
        true if read-only, false if read-write.
      • logInSecurityOfficer

        public void logInSecurityOfficer​(char[] userName,
                                         char[] pin)
                                  throws TokenException
        Login this session as CKU_SO (Security Officer).
        Parameters:
        userName - User name of user type CKU_SO.
        pin - PIN.
        Throws:
        TokenException - If logging in the session fails.
      • createObject

        public long createObject​(AttributeVector template)
                          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 AttributesTemplate 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: AttributesTemplate desKeyTemplate = AttributesTemplate.newSecretKey(CKK_DES3); // the key type is set by the DESSecretKey's constructor, so you need not do it desKeyTemplate.value(myDesKeyValueAs8BytesLongByteArray) .token(true) .private(true); .encrypt(true); .decrypt(true); ... long theCreatedDESKeyObjectHandle = 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:
        template - The template object that holds all values that the new object on the token should contain.
        Returns:
        A new PKCS#11 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.
      • createECPrivateKeyObject

        public long createECPrivateKeyObject​(AttributeVector template,
                                             byte[] ecPoint)
                                      throws TokenException
        Create EC private key object in the PKCS#11 device.
        Parameters:
        template - Template of the EC private key.
        ecPoint - The encoded EC-Point. May be null.
        Returns:
        object handle of the new EC private key.
        Throws:
        TokenException - if creating new object failed.
      • copyObject

        public long copyObject​(long sourceObjectHandle,
                               AttributeVector template)
                        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 is created. See the PKCS#11 standard for details.
        Parameters:
        sourceObjectHandle - The source object of the copy operation.
        template - A template object whose 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 template.
        Throws:
        TokenException - If copying the object fails for some reason.
      • setAttributeValues

        public void setAttributeValues​(long objectToUpdateHandle,
                                       AttributeVector template)
                                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:
        objectToUpdateHandle - The attributes of this object get updated.
        template - This methods gets all present attributes of this template object and set this attributes at the objectToUpdate.
        Throws:
        TokenException - If updating the attributes fails. All or no attributes are updated.
      • destroyObject

        public void destroyObject​(long objectHandle)
                           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:
        objectHandle - The object handle that should be destroyed.
        Throws:
        TokenException - If the object could not be destroyed.
      • destroyObjects

        public long[] destroyObjects​(long... objectHandles)
                              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:
        objectHandles - The object handles that should be destroyed.
        Returns:
        objects that have been destroyed.
        Throws:
        TokenException - If could not get a valid session.
      • getObjectSize

        public long getObjectSize​(long objectHandle)
                           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:
        objectHandle - The object to get the size for.
        Returns:
        The object's size bytes.
        Throws:
        TokenException - If determining the size fails.
      • generateUniqueId

        public byte[] generateUniqueId​(AttributeVector template,
                                       int idLength,
                                       Random random)
                                throws TokenException
        Generate a unique CKA_ID.
        Parameters:
        template - The search criteria for the uniqueness.
        idLength - Length of the CKA_ID.
        random - random to generate the random CKA_ID.
        Returns:
        the unique CKA_ID.
        Throws:
        TokenException - If executing operation fails.
      • findAllObjects

        public long[] findAllObjects​(AttributeVector template)
                              throws TokenException
        Finds all objects that match the template.
        Returns:
        An array of found objects. The maximum size of this array is maxObjectCount, the minimum length is 0. Never returns null.
        Throws:
        TokenException - if finding objects failed.
      • findObjects

        public long[] findObjects​(AttributeVector template,
                                  int maxObjectCount)
                           throws TokenException
        Finds objects that match the template.
        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 - if finding objects failed.
      • encrypt

        public byte[] encrypt​(Mechanism mechanism,
                              long keyHandle,
                              byte[] plaintext)
                       throws TokenException
        Encrypts the given data with the key and mechanism.
        Parameters:
        mechanism - The mechanism to use; e.g. Mechanism.DES_CBC.
        keyHandle - The decryption key to use.
        plaintext - the to-be-encrypted data
        Returns:
        the encrypted data. Never returns null.
        Throws:
        TokenException - If encrypting failed.
      • encrypt

        public int encrypt​(OutputStream out,
                           Mechanism mechanism,
                           long keyHandle,
                           InputStream plaintext)
                    throws TokenException,
                           IOException
        This method can be used to encrypt large data.
        Parameters:
        out - Stream to which the cipher text is written.
        mechanism - The mechanism to use.
        keyHandle - The decryption key to use.
        plaintext - Input-stream of the to-be-encrypted data
        Returns:
        length of the encrypted data.
        Throws:
        TokenException - If encrypting the data failed.
        IOException
      • decrypt

        public byte[] decrypt​(Mechanism mechanism,
                              long keyHandle,
                              byte[] ciphertext)
                       throws TokenException
        Decrypts the given data with the key and mechanism.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The decryption key to use.
        ciphertext - the to-be-decrypted data
        Returns:
        the decrypted data. Never returns null.
        Throws:
        TokenException - If encrypting failed.
      • decrypt

        public int decrypt​(OutputStream out,
                           Mechanism mechanism,
                           long keyHandle,
                           InputStream ciphertext)
                    throws TokenException,
                           IOException
        This method can be used to decrypt large data.
        Parameters:
        out - Stream to which the plain text is written.
        mechanism - The mechanism to use.
        keyHandle - The decryption key to use.
        ciphertext - Input-stream of the to-be-encrypted data
        Returns:
        length of the decrypted data.
        Throws:
        TokenException - If decrypting the data failed.
        IOException
      • digest

        public byte[] digest​(Mechanism mechanism,
                             byte[] data)
                      throws TokenException
        Digests the given data with the mechanism.
        Parameters:
        mechanism - The mechanism to use; e.g. Mechanism.SHA_1.
        data - the to-be-digested data
        Returns:
        the message digest. Never returns null.
        Throws:
        TokenException - If digesting the data failed.
      • digestKey

        public byte[] digestKey​(Mechanism mechanism,
                                long keyHandle)
                         throws TokenException
        Digests the given key with the mechanism.
        Parameters:
        mechanism - The mechanism to use; e.g. Mechanism.SHA_1.
        keyHandle - handle of the to-be-digested key.
        Returns:
        the message digest. Never returns null.
        Throws:
        TokenException - If digesting the data failed.
      • digest

        public byte[] digest​(Mechanism mechanism,
                             InputStream data)
                      throws TokenException,
                             IOException
        Digests the large data with the mechanism.
        Parameters:
        mechanism - The mechanism to use; e.g. Mechanism.SHA_1.
        data - the to-be-digested data
        Returns:
        the message digest. Never returns null.
        Throws:
        TokenException - If digesting the data failed.
        IOException - if reading data from stream failed.
      • sign

        public byte[] sign​(Mechanism mechanism,
                           long keyHandle,
                           byte[] data)
                    throws TokenException
        Signs the given data with the key and mechanism.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The signing key to use.
        data - The data to sign.
        Returns:
        The signed data. Never returns null.
        Throws:
        TokenException - If signing the data failed.
      • sign

        public byte[] sign​(Mechanism mechanism,
                           long keyHandle,
                           InputStream data)
                    throws TokenException,
                           IOException
        This method can be used to sign large data.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The signing key to use.
        data - Input-stream of the to-be-signed data
        Returns:
        length of the signature.
        Throws:
        TokenException - If signing the data failed.
        IOException - If reading data stream failed.
      • signRecover

        public byte[] signRecover​(Mechanism mechanism,
                                  long keyHandle,
                                  byte[] data)
                           throws TokenException
        Sign-recovers the given data with the key and mechanism.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The signing key to use.
        data - The data to sign-recovers.
        Returns:
        The signed data. Never returns null.
        Throws:
        TokenException - If signing the data failed.
      • verify

        public boolean verify​(Mechanism mechanism,
                              long keyHandle,
                              byte[] data,
                              byte[] signature)
                       throws TokenException
        Verifies the given signature against the given data with the key and mechanism. This method throws an exception, if the verification of the signature fails.
        Parameters:
        mechanism - The mechanism to use; e.g. Mechanism.RSA_PKCS.
        keyHandle - The verification key to use.
        data - The data that was signed.
        signature - The signature or MAC to verify.
        Returns:
        true if signature is invalid, false otherwise.
        Throws:
        TokenException - If verifying the signature fails.
      • verify

        public boolean verify​(Mechanism mechanism,
                              long keyHandle,
                              InputStream data,
                              byte[] signature)
                       throws TokenException,
                              IOException
        This method can be used to verify large data.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The signing key to use.
        data - Input-stream of the to-be-verified data
        signature - the signature.
        Returns:
        true if signature is invalid, false otherwise.
        Throws:
        TokenException - If signing the data failed.
        IOException - If reading data stream failed.
      • verifyRecover

        public byte[] verifyRecover​(Mechanism mechanism,
                                    long keyHandle,
                                    byte[] data)
                             throws TokenException
        Verify-recovers the given data with the key and mechanism.
        Parameters:
        mechanism - The mechanism to use.
        keyHandle - The signing key to use.
        data - The data to be verify-recovered.
        Returns:
        The verify-recovered data. Never returns null.
        Throws:
        TokenException - If signing the data failed.
      • generateKey

        public long generateKey​(Mechanism mechanism,
                                AttributeVector 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 secret key or domain parameters failed.
      • generateKeyPair

        public PKCS11KeyPair generateKeyPair​(Mechanism mechanism,
                                             KeyPairTemplate template)
                                      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.
        template - The template for the new keypair.
        Returns:
        The newly generated key-pair.
        Throws:
        TokenException - If generating a new key-pair failed.
      • wrapKey

        public byte[] wrapKey​(Mechanism mechanism,
                              long wrappingKeyHandle,
                              long keyHandle)
                       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.
        wrappingKeyHandle - The key to use for wrapping (encrypting).
        keyHandle - The key to wrap (encrypt).
        Returns:
        The wrapped key as byte array. Never returns null.
        Throws:
        TokenException - If wrapping the key failed.
      • unwrapKey

        public long unwrapKey​(Mechanism mechanism,
                              long unwrappingKeyHandle,
                              byte[] wrappedKey,
                              AttributeVector 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.
        unwrappingKeyHandle - 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 long deriveKey​(Mechanism mechanism,
                              long baseKeyHandle,
                              AttributeVector 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.
        baseKeyHandle - 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.
      • 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.
      • generateRandom

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

        public byte[][] encryptMessages​(Mechanism mechanism,
                                        long keyHandle,
                                        EncryptMessageBytesEntry[] entries)
                                 throws TokenException
        Encrypts the given messages using the given mechanism and key
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the encryption key.
        entries - Arrays of plaintexts in byte[] with additional parameters to be encrypted.
        Returns:
        Array of ciphertexts. The result at index i is the ciphertext of entries[i].
        Throws:
        TokenException - If encrypting failed.
      • encryptMessages

        public int[] encryptMessages​(Mechanism mechanism,
                                     long keyHandle,
                                     EncryptMessageStreamEntry[] entries)
                              throws TokenException,
                                     IOException
        Encrypts the given messages using the given mechanism and key,.
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the encryption key.
        entries - Arrays of plaintexts in stream with additional parameters to be encrypted.
        Returns:
        Array of lengths of ciphertext. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If encrypting failed.
        IOException - if reading or writing stream failed.
      • decryptMessages

        public byte[][] decryptMessages​(Mechanism mechanism,
                                        long keyHandle,
                                        DecryptMessageBytesEntry[] entries)
                                 throws TokenException
        Decrypts the given ciphertexts using the given mechanism and key,.
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the encryption key.
        entries - Arrays of ciphertexts in byte[] with additional parameters to be encrypted.
        Returns:
        Array of lengths of ciphertext. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If encrypting failed.
        IOException - if reading or writing stream failed.
      • decryptMessages

        public int[] decryptMessages​(Mechanism mechanism,
                                     long keyHandle,
                                     DecryptMessageStreamEntry[] entries)
                              throws TokenException,
                                     IOException
        Decrypts the given ciphertexts using the given mechanism and key,.
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the encryption key.
        entries - Arrays of ciphertexts in stream with additional parameters to be encrypted.
        Returns:
        Array of lengths of ciphertext. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If encrypting failed.
        IOException - if reading or writing stream failed.
      • signMessages

        public byte[][] signMessages​(Mechanism mechanism,
                                     long keyHandle,
                                     SignMessageBytesEntry[] entries)
                              throws TokenException
        Signs the given messages using the given mechanism and key.
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the signing key.
        entries - Arrays of messages in byte[] with additional parameters to be encrypted.
        Returns:
        Array of signatures. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If signing failed.
      • signMessages

        public byte[][] signMessages​(Mechanism mechanism,
                                     long keyHandle,
                                     SignMessageStreamEntry[] entries)
                              throws TokenException,
                                     IOException
        Signs the given messages using the given mechanism and key.
        Parameters:
        mechanism - The encryption mechanism
        keyHandle - Handle of the signing key.
        entries - Arrays of messages in stream with additional parameters to be encrypted.
        Returns:
        Array of signatures. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If signing failed.
        IOException - if reading or writing stream failed.
      • verifyMessages

        public boolean[] verifyMessages​(Mechanism mechanism,
                                        long keyHandle,
                                        VerifyMessageStreamEntry[] entries)
                                 throws TokenException,
                                        IOException
        Verify the signatures over given messages using the given mechanism and key.
        Parameters:
        mechanism - The signature verification mechanism
        keyHandle - Handle of the verification key.
        entries - Arrays of messages in stream with additional parameters to be verified.
        Returns:
        Array of signature verification result. The result at index i corresponds to entries[i].
        Throws:
        TokenException - If verifying failed.
        IOException - if reading or writing stream failed.
      • toString

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

        public AttributeVector getAttrValues​(long objectHandle,
                                             long... attributeTypes)
                                      throws TokenException
        Gets give attributes for the given object handle.
        Parameters:
        objectHandle - the object handle.
        attributeTypes - types of attributes to be read.
        Returns:
        attributes for the given object handle.
        Throws:
        TokenException - if getting attributes failed.
      • getAttrValues

        public AttributeVector getAttrValues​(long objectHandle,
                                             List<Long> attributeTypes)
                                      throws TokenException
        Gets give attributes for the given object handle.
        Parameters:
        objectHandle - the object handle.
        attributeTypes - types of attributes to be read.
        Returns:
        attributes for the given object handle.
        Throws:
        TokenException - if getting attributes failed.
      • getDefaultAttrValues

        public AttributeVector getDefaultAttrValues​(long objectHandle)
                                             throws TokenException
        Gets all attributes for the given object handle.
        Parameters:
        objectHandle - the object handle.
        Returns:
        all attributes for the given object handle.
        Throws:
        TokenException - if getting attributes failed.