Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
// Copyright (c) 2002 Graz University of Technology. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. The end-user documentation included with the redistribution, if any, must
// include the following acknowledgment:
//
// "This product includes software developed by IAIK of Graz University of
// Technology."
//
// Alternately, this acknowledgment may appear in the software itself, if and
// wherever such third-party acknowledgments normally appear.
//
// 4. The names "Graz University of Technology" and "IAIK of Graz University of
// Technology" must not be used to endorse or promote products derived from
// this software without prior written permission.
//
// 5. Products derived from this software may not be called "IAIK PKCS Wrapper",
// nor may "IAIK" appear in their name, without prior written permission of
// Graz University of Technology.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package iaik.pkcs.pkcs11;
import java.util.Vector;
import iaik.pkcs.pkcs11.objects.Key;
import iaik.pkcs.pkcs11.objects.KeyPair;
import iaik.pkcs.pkcs11.objects.Object;
import iaik.pkcs.pkcs11.objects.PrivateKey;
import iaik.pkcs.pkcs11.objects.PublicKey;
import iaik.pkcs.pkcs11.objects.SecretKey;
import iaik.pkcs.pkcs11.parameters.Parameters;
import iaik.pkcs.pkcs11.parameters.SSL3KeyMaterialParameters;
import iaik.pkcs.pkcs11.parameters.SSL3MasterKeyDeriveParameters;
import iaik.pkcs.pkcs11.parameters.VersionParameters;
import iaik.pkcs.pkcs11.wrapper.Constants;
import iaik.pkcs.pkcs11.wrapper.Functions;
import iaik.pkcs.pkcs11.wrapper.PKCS11Constants;
import iaik.pkcs.pkcs11.wrapper.PKCS11Exception;
import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;
import sun.security.pkcs11.wrapper.CK_MECHANISM;
import sun.security.pkcs11.wrapper.CK_SESSION_INFO;
import sun.security.pkcs11.wrapper.CK_SSL3_KEY_MAT_PARAMS;
import sun.security.pkcs11.wrapper.CK_SSL3_MASTER_KEY_DERIVE_PARAMS;
import sun.security.pkcs11.wrapper.PKCS11;
/**
* 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.");
* // the token prompts the PIN by other means; e.g. PIN-pad
* session.login(Session.UserType.USER, null);
* } 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();
*
*
*
* @see iaik.pkcs.pkcs11.objects.Object
* @see iaik.pkcs.pkcs11.parameters.Parameters
* @see iaik.pkcs.pkcs11.Session
* @see iaik.pkcs.pkcs11.SessionInfo
* @author Karl Scheibelhofer
* @version 1.0
* @invariants (pkcs11Module_ <> null)
*/
@SuppressWarnings("restriction")
public class Session {
/**
* This interface defines the different user types of PKCS#11.
*
* @author Karl Scheibelhofer
* @version 1.0
* @invariants
*/
public interface UserType {
/**
* This constant stands for the security officer.
*/
public static boolean SO = false;
/**
* Thsi constant stands for the user (token owner).
*/
public static boolean USER = true;
}
/**
* A reference to the underlying PKCS#11 module to perform the operations.
*/
protected Module module_;
/**
* A reference to the underlying PKCS#11 module to perform the operations.
*/
protected PKCS11 pkcs11Module_;
/**
* The session handle to perform the operations with.
*/
protected long sessionHandle_;
/**
* The token to perform the operations on.
*/
protected Token token_;
/**
* Constructor taking the token and the session handle.
*
* @param token
* The token this session operates with.
* @param sessionHandle
* The session handle to perform the operations with.
* @preconditions (token <> null)
* @postconditions
*/
protected Session(Token token, long sessionHandle) {
token_ = Util.requireNonNull("token", token);
module_ = token_.getSlot().getModule();
pkcs11Module_ = module_.getPKCS11Module();
sessionHandle_ = sessionHandle;
}
/**
* 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.
*
* @param 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.
* @exception TokenException
* If the session has not the right to set the PIN of if the
* operation fails for some other reason.
* @preconditions
* @postconditions
*/
/*
public void initPIN(char[] pin)
throws TokenException {
pkcs11Module_.C_InitPIN(sessionHandle_, pin, useUtf8Encoding_);
}*/
/**
* Set the user-PIN to a new value. Can only be called from a read-write
* sessions.
*
* @param oldPin
* The old (current) user-PIN.
* @param newPin
* The new value for the user-PIN.
* @exception TokenException
* If setting the new PIN fails.
* @preconditions
* @postconditions
*/
/*
public void setPIN(char[] oldPin, char[] newPin)
throws TokenException {
pkcs11Module_.C_SetPIN(sessionHandle_, oldPin, newPin,
useUtf8Encoding_);
}*/
/**
* Closes this session.
*
* @exception TokenException
* If closing the session failed.
* @preconditions
* @postconditions
*/
public void closeSession()
throws TokenException {
try {
pkcs11Module_.C_CloseSession(sessionHandle_);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* Compares the sessionHandle and token_ of this object with the other
* object. Returns only true, if those are equal in both objects.
*
* @param otherObject
* The other Session object.
* @return True, if other is an instance of Token and the session handles
* and tokens of both objects are equal. False, otherwise.
* @preconditions
* @postconditions
*/
@Override
public boolean equals(java.lang.Object otherObject) {
if (this == otherObject) {
return true;
}
if (!(otherObject instanceof Session)) {
return false;
}
Session other = (Session) otherObject;
if (this.sessionHandle_ != other.sessionHandle_) {
return false;
}
return this.token_.equals(other.token_);
}
/**
* The overriding of this method should ensure that the objects of this
* class work correctly in a hashtable.
*
* @return The hash code of this object. Gained from the sessionHandle.
* @preconditions
* @postconditions
*/
@Override
public int hashCode() {
return (int) sessionHandle_;
}
/**
* Get the handle of this session.
*
* @return The handle of this session.
* @preconditions
* @postconditions
*/
public long getSessionHandle() {
return sessionHandle_;
}
/**
* Get information about this session.
*
* @return An object providing information about this session.
* @exception TokenException
* If getting the information failed.
* @preconditions
* @postconditions (result <> null)
*/
public SessionInfo getSessionInfo()
throws TokenException {
CK_SESSION_INFO ckSessionInfo;
try {
ckSessionInfo = pkcs11Module_.C_GetSessionInfo(sessionHandle_);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
return new SessionInfo(ckSessionInfo);
}
/**
* Get the Module which this Session object operates with.
*
* @return The module of this session.
* @preconditions
* @postconditions
*/
public Module getModule() {
return module_;
}
/**
* Get the token that created this Session object.
*
* @return The token of this session.
* @preconditions
* @postconditions
*/
public Token getToken() {
return token_;
}
/**
* Get the current operation state. This state can be used later to restore
* the operation to exactly this state.
*
* @return The current operation state as a byte array.
* @exception TokenException
* If saving the state fails or is not possible.
* @see #setOperationState(byte[],Key,Key)
* @preconditions
* @postconditions (result <> null)
*/
public byte[] getOperationState()
throws TokenException {
try {
return pkcs11Module_.C_GetOperationState(sessionHandle_);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* 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.
*
* @param operationState
* The previously saved state as returned by getOperationState().
* @param 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.
* @param authenticationKey
* A signing, verification of MAC key, if a signing, verification
* or MAC operation needs to be restored that could not save the
* key.
* @exception TokenException
* If restoring the state fails.
* @see #getOperationState()
* @preconditions
* @postconditions
*/
public void setOperationState(byte[] operationState,
Key encryptionKey,
Key authenticationKey)
throws TokenException {
try {
pkcs11Module_.C_SetOperationState(sessionHandle_, operationState,
encryptionKey.getObjectHandle(),
authenticationKey.getObjectHandle());
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* 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.
*
* @param userType
* UserType.SO for the security officer or UserType.USER to login
* the user.
* @param pin
* The PIN. The security officer-PIN or the user-PIN depending on
* the userType parameter.
* @exception TokenException
* If login fails.
* @preconditions
* @postconditions
*/
public void login(boolean userType, char[] pin)
throws TokenException {
long lUserType = (userType == UserType.SO)
? PKCS11Constants.CKU_SO : PKCS11Constants.CKU_USER;
try {
pkcs11Module_.C_Login(sessionHandle_, lUserType, pin);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
public void login(long userType, char[] pin)
throws TokenException {
try {
pkcs11Module_.C_Login(sessionHandle_, userType, pin);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* Logs out this session.
*
* @exception TokenException
* If logging out the session fails.
* @preconditions
* @postconditions
*/
public void logout()
throws TokenException {
try {
pkcs11Module_.C_Logout(sessionHandle_);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* 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.
*
* @param templateObject
* The template object that holds all values that the new object on
* the token should contain. (this is not a java.lang.Object!)
* @return 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.
* @exception TokenException
* If the creation of the new object fails. If it fails, the no
* new object was created on the token.
* @preconditions (templateObject <> null)
* @postconditions (result <> null)
*/
public Object createObject(Object templateObject)
throws TokenException {
CK_ATTRIBUTE[] ckAttributes = Object.getSetAttributes(templateObject);
long objectHandle;
try {
objectHandle = pkcs11Module_.C_CreateObject(sessionHandle_,
ckAttributes);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
return Object.getInstance(this, objectHandle);
}
/**
* 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.
*
* @param sourceObject
* The source object of the copy operation.
* @param 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.
* @return The new object that is created by copying the source object and
* setting attributes to the values given by the templateObject.
* @exception TokenException
* If copying the object fails for some reason.
* @preconditions (sourceObject <> null)
* @postconditions
*/
public Object copyObject(Object sourceObject, Object templateObject)
throws TokenException {
long sourceObjectHandle = sourceObject.getObjectHandle();
CK_ATTRIBUTE[] ckAttributes = Object.getSetAttributes(templateObject);
long newObjectHandle;
try {
newObjectHandle = pkcs11Module_.C_CopyObject(sessionHandle_,
sourceObjectHandle, ckAttributes);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
return Object.getInstance(this, newObjectHandle);
}
/**
* 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.
*
* @param objectToUpdate
* The attributes of this object get updated.
* @param templateObject
* This methods gets all present attributes of this template object
* and set this attributes at the objectToUpdate.
* @exception TokenException
* If update of the attributes fails. All or no attributes are
* updated.
* @preconditions (objectToUpdate <> null) and (template <> null)
* @postconditions
*/
public void setAttributeValues(Object objectToUpdate, Object templateObject)
throws TokenException {
long objectToUpdateHandle = objectToUpdate.getObjectHandle();
CK_ATTRIBUTE[] ckAttributesTemplates =
Object.getSetAttributes(templateObject);
try {
pkcs11Module_.C_SetAttributeValue(sessionHandle_,
objectToUpdateHandle, ckAttributesTemplates);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* 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.
*
* @param objectToRead
* The object to newly read from the token.
* @return A new Object holding all attributes that this method just read
* from the token.
* @exception TokenException
* If reading the attributes fails.
* @preconditions (objectToRead <> null)
* @postconditions (result <> null)
*/
public Object getAttributeValues(Object objectToRead)
throws TokenException {
long objectHandle = objectToRead.getObjectHandle();
return Object.getInstance(this, objectHandle);
}
/**
* 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.
*
* @param object
* The object that should be destroyed.
* @exception TokenException
* If the object could not be destroyed.
* @preconditions (object <> null)
* @postconditions
*/
public void destroyObject(Object object)
throws TokenException {
long objectHandle = object.getObjectHandle();
try {
pkcs11Module_.C_DestroyObject(sessionHandle_, objectHandle);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* Get the size of the specified object in bytes. This size specifies how
* much memory the object takes up on the token.
*
* @param object
* The object to get the size for.
* @return The object's size bytes.
* @exception TokenException
* If determining the size fails.
* @preconditions (object <> null)
* @postconditions
*/
/*
public long getObjectSize(Object object)
throws TokenException {
long objectHandle = object.getObjectHandle();
return pkcs11Module_.C_GetObjectSize(sessionHandle_, objectHandle);
}*/
/**
* Initializes a find operations that provides means to find objects by
* passing a template object. This method gets all set attributes of the
* template object and searches for all objects on the token that match with
* these attributes.
*
* @param 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.
* @exception TokenException
* If initializing the find operation fails.
* @preconditions
* @postconditions
*/
public void findObjectsInit(Object templateObject)
throws TokenException {
CK_ATTRIBUTE[] ckAttributes = Object.getSetAttributes(templateObject);
try {
pkcs11Module_.C_FindObjectsInit(sessionHandle_, ckAttributes);
} catch (sun.security.pkcs11.wrapper.PKCS11Exception ex) {
throw new PKCS11Exception(ex);
}
}
/**
* Finds objects that match the template object passed to findObjectsInit.
* The application must call findObjectsInit before calling this method.
* With maxObjectCount the application can specify how many objects to
* return at once; i.e. the application can get all found objects by
* subsequent calls to this method like maxObjectCount(1) until it receives
* an empty array (this method never returns null!).
*
* @param maxObjectCount
* Specifies how many objects to return with this call.
* @return An array of found objects. The maximum size of this array is
* maxObjectCount, the minimum length is 0. Never returns null.
* @exception 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.
* @preconditions
* @postconditions (result <> null)
*/
public Object[] findObjects(int maxObjectCount)
throws TokenException {
Vector