Softlock Smart Token Security

Document Sample
Softlock Smart Token Security Powered By Docstoc
					Softlock Smart Token Security

          Experiment
Experiment                                                                                                Softlock Smart Token Security



CONTENTS
OBJECTIVES......................................................................................................................................1

GETTING STARTED ...........................................................................................................................2

   SMART TOKEN OVERVIEW ......................................................................................................... 2
   SMART TOKEN SPECIFICATION .................................................................................................... 4
APPLICATIONS .................................................................................................................................5

   GENERATE SELF SIGNED CERTIFICATE .......................................................................................... 5
   DOCUMENT SECURITY ............................................................................................................... 9
   WEB SECURITY ...................................................................................................................... 12
       Install IIS 6.0 on Windows 2003 Server (Web server). ................................................................. 13
       Install the Web Site Certificate .................................................................................................... 13
       Trust the Root Certificate ............................................................................................................ 15
       Configure the Web Site to Require a Client Certificate and use Basic Authentication ................ 17
       Web Authentication Using the Installed Certificate in the Token ............................................... 18

SMART TOKEN DEVELOPMENT ......................................................................................................22

   SMART TOKEN DEVELOPMENT INTERFACES ................................................................................ 22
   SMART TOKEN SDK INTERFACE ................................................................................................ 24
   CSP INTERFACE ..................................................................................................................... 32
ABOUT SOFTLOCK ..........................................................................................................................35
Experiment                                                              Softlock Smart Token Security




OBJECTIVES
This experiment provides student with detailed description of Smart Token device. In addition to
how to configure, manage and use the solution to configure the secure log in to secure web server.
Moreover, the student is also provided with information on how to enhance his/her intellectual
properties security such as Microsoft Office documents for example, and how to use security
infrastructure.

In spite of the fact that the student should be familiar with the basic concepts of cryptography
programming, the use of digital certificates and PKI, some introductory material is provided on
cryptography and PKI as well. This guide covers the required information to start developing Smart
Token based components to build larger security solutions layers.

This guide is divided into the following sections:

    1- GETTING STARTED
       This section provides the user with an overall description of the Smart Token features, as
       well as brief intro to the world of security and PKI.

    2- APPLICATION SECTION
       This section provides the user with a detailed description of Smart Token integration in
       Secure log in over the internet, generate self signed certificates and Microsoft office
       documents security using the Smart Token.

    3- DEVELOPMENT SECTION
       This section provides the student with a detailed description of Smart token development
       interface and how to use it to create simple security application.




                                                                                                   1
Experiment                                                                 Softlock Smart Token Security




GETTING STARTED
Smart Token Overview
A Smart Token (or sometimes a hardware token, hard token, authentication token, USB token,
cryptographic token, or key fob) may be a physical device that an authorized user of computer
services is given to ease authentication. The term may also refer to software tokens.

Security tokens are used to prove one's identity electronically (as in the case of a customer trying to
access their bank account). The token is used in addition to or in place of a password to prove that
the customer is who they claim to be. The token acts like an electronic key to access something.

Hardware tokens are typically small enough to be carried in a pocket or purse and often are
designed to attach to the user's keychain. Some may store cryptographic keys, such as a digital
signature, or biometric data, such as a finger print. Some designs feature tamper resistant
packaging, while others may include small keypads to allow entry of a PIN or a simple button to start
a generating routine with some display capability to show a generated key number. Special designs
include a USB connector, RFID functions or Bluetooth wireless interface to enable transfer of a
generated key number sequence to a client system.

Smart Token provides data security features, including:

Confidentiality

    Softlock Smart Token encrypts data so that only the user and those he/she authorizes can
    decrypt and read it.

Authentication

     Smart Token checks the digital signature of the person who signed the data to ensure that the
    data really came from that person. A digital signature is like a handwritten signature as both
    can guarantee someone’s identity.

Non-repudiation

    Smart Token, by providing digital signature capability, shows that only the person whose digital
    signature appears on a piece of data is the one who have signed that data. Therefore, a person
    cannot deny involvement in a legitimately signed transaction.

Integrity

    Smart Token ensures that protected data is unchanged. A valid digital signature on a piece of
    data shows that the data has not been altered since it was signed.




                                                                                                      2
Experiment                                                                 Softlock Smart Token Security


Why the Hardware Security is better than the Software Security?

Based on the researches on the field of digital security, and the recommendation of security
institutes (Example: FIPS140-2) secure data must be generated, stored and processed in a separate
environment outside the computer. This will protect sensitive user data from digital attacks. In the
other side software based security solutions cannot provide the minimum security requirements, it
cannot provide the required level of protection for both secure information or secure operations.

Hardware based security must provide following:

    1.   Secure storage for secure information (digital keys, private and public data). Know that it is
         required to store some public data in the token for portability reasons (User do not have to
         carry two storage one for public and other for private).
    2.   Supports internal methods for key generation.
    3.   Supports internal methods to deal with secure information like encryption, decryption,
         signing, verification, hashing and keys wrapping and unwrapping.

By providing (1, 2 and 3) there is no need to expose securing information outside the hardware, and
this decreases the possibilities of digital attacks.

What is the difference between hardware based security solutions?

Different hardware brands provide different level of services. The ultimate security is to perform
everything inside the token. However due to the lake of speed, the limited storage and the
expensive cost, some hardware models provides a subset of the requirements and moves the others
outside the hardware.

For that reason it is important to know:

        Keys Capacity: How many keys can be stored in the tokens
        Memory Capacity: How big the internal storage to hold both public and private data.
        Keys Generation: The ability to generate the keys internally
        Keys Strength: The strength and the type of the internal generated keys
        Secure Keys Exchange: The ability of the hardware to import external keys in a warped
         format (wrapping is a mechanism to transfer the keys from without exposing them)
        Secure Operations: What is the allowed operations
             o Does is support encryption/decryption
             o Does is support signing/verification
             o Does is support data hashing
        Operations Speed: How long it takes to perform different operations




                                                                                                      3
Experiment                                                               Softlock Smart Token Security



Smart Token Specification
Support Operating System   Windows 2K, XP, 2003, Vista, 7, 2008 and Linux

Compatible Applications    Office, Outlook and Internet Explorer, Mozilla, Thunderbird, Netscape,
                           Google Chrome and Acrobat Reader/Writer

Hardware Interface         Plug and Play USB/HID. No driver is required.

Software Interface         PKCS, CSP, SDK library and SDK COM

Supported Standards        PKCS (1, 5, 7, 8, 10, 11 2.2 and 12), X5.09, CSP and FIPS 14-2-L2

Onboard Cryptography       RSA-1024 key generation, RSA-2048 sign/verify, DES, 3DS, AES, MD2,
                           MD5, SHA1, SHA256, SHA384, SHA512, HMAC and DH

Custom Onboard             ECC, DSA, Twofish, Blowfish, Cast, RC4 and RC6
Cryptography

Storage                    100 KB, 10 PKI Slots and 40 Symmetric Slots

Session Capabilities       20 Session, 5 PKI Slots, 20 Symmetric Slots

Fingerprint Sensor         Provided with eSign PRO model.
                              o      o
Operating Temperature      -25 to 85 C
Range

Memory Retention           10000 write cycle and 10 years data retention




                                                                                                    4
Experiment                                                                  Softlock Smart Token Security




 APPLICATIONS
Generate Self Signed Certificate
In cryptography, a digital certificate (also known as identity certificate) is an electronic document
which uses a digital signature to bind together a public-private key pair with an identity information
such as the name of a person or an organization, their address, and so forth. The certificate can be
used to verify that a public key belongs to an individual.
In a typical public key infrastructure (PKI) scheme, the signature will be of a certificate authority
(CA). In a web of trust scheme, the signature is of either the user (a self-signed certificate) or other
users ("endorsements"). In either case, the signatures on a certificate are attestations by the
certificate signer that the identity information and the public key belong together.
In our first application we will learn how to use smart token admin tool to generate self signed
certificate for each user so that each student can use it in the next application in (encrypt, decrypt,
sign) Microsoft office documents.

         1- Open the start menu then programs and select Softlock Smart token admin tool. From
            the expanded menu select Smart toke administration Utility.




         2- Be sure that you plug the token to one of the USB slots in your PC.




         3- Click on the certificate Tab, you will be asked to enter the Token owner user pin to log
            in as user. Enter it and press the ok button




                                                                                                       5
Experiment                                                             Softlock Smart Token Security


        4- Right click on the certificate tree and select the “Generate self signed certificate”
           option.




        5- Enter the new certificate information and press the ok button.




        6- A message box will inform you that the generation process take about 2 minutes, press
           ok to continue. Then press ok in the successful generation message.




                                                                                                  6
Experiment                                                               Softlock Smart Token Security




        7- In the certificate tree right click on your new certificate and select the set as default
           option. To make it your default certificate.




        8- Select the certificate and click export.




        9- Select (.cer) file type, which is a public certificate. Write the name you want to save
           your new certificate with and browse to the location which you want to save it in and
           press “Save”.




                                                                                                    7
Experiment                                       Softlock Smart Token Security




        10- Click ok in the successes message.




                                                                            8
Experiment                                                               Softlock Smart Token Security



Document Security
In this application we are going to use the created self signed certificate to perform some security
operations in Microsoft office document.

H OW TO SIGN M ICROSOFT OFFICE DOCUMENT
        1-open the office document your want to sign and don’t forget to attach the token to the
        PC.

        2- Place your pointer in the place where your want to place your certificate.




        3- In the insert Tab double click on “Signature Line” option.

        4- Click ok in the appeared wizard.




        5- Fill in the signature line details as shown and click ok




        6- The following line of signature will appear.




                                                                                                    9
Experiment                                                                Softlock Smart Token Security




        7- In the last steps you add a signature line but you don’t sign the document yet with the
           certificate installed on your Token.

        8- Double click on the signature line. In the appeared wizard you have either to Wright
           your name or insert images that contain your hard copy signature. Enter your name
           and click the sign button.




        9- You will be asked about the token PIN enter it and the document will be signed

        10- Now you can find your signature in the document

        11- Double click again on the signature, click on “trust the certificate link”. Normally self
            signed certificates are not trusted.




                                                                                                    10
Experiment                                                            Softlock Smart Token Security




How to verify signature on Microsoft office document

    1.   Double click on the signature in the document
    2.   If the appeared message box till you that this is a trusted signature and the document
         didn’t changed as shown so this is a valid signature otherwise it is not valid




                                                                                                11
Experiment                                                                    Softlock Smart Token Security



Web Security
In this application we are going to apply the concept of PKI infrastructure in securing the web
application log in process. As well as use the smart token to prove the identity of the web
application user.

Note:-

    1- A Certification Authority (CA) is a trusted entity whose central responsibility is to certify
       the identity of users. The function of a CA is like that of a federal government’s passport
       office. A passport is a citizen’s secure document that is issued by an appropriate authority
       and certifies that the citizen is who he or she claims to be; it is a paper identity. Any other
       country that trusts the authority of this government passport office also trusts the citizen’s
       passport. This is a good example of third-party trust.

    2- The CA is a server application that creates secure, authorized digital identities for users.
       These identities are issued in the form of electronic certificates. The CA certifies these
       certificates by digitally signing them using the CA’s signing private key. Users can check the
       validity of a certificate by verifying the signature on the certificate. This is done using the
       CA’s verification public key. If the verification is successful, users can trust the certificate. If
       the verification fails, users know not to trust that certificate.




    3- in our application we assumed that we get both the client and server certificates from a
       third party trusted certificate like (Comodo or VeriSign ). So we you should have the
       following certificates:-

             a.   Root Certificate: This is the certificate of the trusted Root that generates both the
                  client and server certificate. Any certificate generated from the same root is
                  trusted from both the client and the server. it should be of type “Certificate
                  Authority ”.




                                                                                                        12
Experiment                                                                     Softlock Smart Token Security


              b.   Server certificate:- this is the certificate generated by the trusted root and will be
                   used to identify the identity of the server it should be of type “SSL Certificate”.

              c.   Client certificate: Server certificate:- this is the certificate generated by the trusted
                   root and will be used to identify the identity of the server it should be of type
                   “General Purpose”.

Let’s go now in our applications step by step:-

Install IIS 6.0 on Windows 2003 Server (Web server).
Perform the following steps to install the IIS 6.0 WWW service on the Windows Server 2003
machine that will act as the Web server:

    1.        Click Start and point to Control Panel. Click the Add or Remove Programs link.
    2.        In the Add or Remove Programs window, click the Add/Remove Windows Components
              button.
    3.        In the Windows Components window, click the Application Server entry in the
              Components list and then click Details.
    4.        In the Application Server dialog box, put a checkmark in the Internet Information
              Services (IIS) checkbox. Click OK.
    5.        Click next on the Windows Components page.
    6.        Click OK on the Insert Disk dialog box. In the Files needed dialog box, enter the path to
              the i386 folder on the Windows Server 2003 CD in the Copy files from text box. Click
              OK.
    7.        Click Finish when the Wizard is completed.

Install the Web Site Certificate
In this step we are going to install the website certificate on windows server 2003 machine so that
the website (server) will use it to identify itself to any user. We’ll begin by installing the Web site
certificate and then we’ll install the CA certificate.

Perform the following steps to install the Web site certificate on the Web server:

         1.    At the Web server machine, click Start and point to Administrative Tools. Click the
               Internet Information Services (IIS) Manager link.
         2.    Expand the Web Sites node in the left pane of the console and then click on the
               Default Web Site. Right click on the Default Web Site and click Properties.
         3.    In the Default Web Site Properties dialog box, click the Directory Security tab.
         4.    On the Directory Security tab, click the Server Certificate button.
         5.    Click next on the Welcome to the Web Server Certificate Wizard page.
         6.    On the IIS Certificate Wizard, select the Import a Certificate from a .PFX file and press
               next. And select web site certificate.




                                                                                                         13
Experiment                                                              Softlock Smart Token Security




        7.    On the SSL Port page, accept the default SSL port, which are 443. Click Next.
        8.    On the Certificate Summary page, review your settings and click next.
        9.    Click Finish on the Completing the Web Server Certificate Wizard page.
        10.   On the Directory Security tab, click the View Certificate button.
        11.   In the Certificate dialog box, click the General tab. Note that the Issued to name is
              test. This is the common name on the certificate.




        12.   Click OK in the Certificate dialog box.




                                                                                                  14
Experiment                                                                   Softlock Smart Token Security


         13.     Click OK in the Default Web Site Properties dialog box.

Trust the Root Certificate
We need to install the Root CA certificate in the Trusted Root Certification Authorities store on the
Web server machine. This allows the Web server to trust the Web site certificate installed on the IIS
Web site. And will let the web server trust any certificate issued from the same root.

Perform the following steps to install the root CA certificate into the machine’s certificate store:

    1.       Click Start and then click the Run command.
    2.       In the Run dialog box, enter mimic in the Open text box and click OK.
    3.       In the Console1 window, click the File menu and click the Add/Remove Snap-in command.
    4.       In the Add/Remove Snap-in dialog box, click the Add button.
    5.       In the Add Standalone Snap-in dialog box, select the Certificates entry in the Available
             Standalone Snap-ins dialog box and click Add.




    6.       On the Certificates snap-in page, select the Computer account option and click Next.




                                                                                                       15
Experiment                                                                   Softlock Smart Token Security




    7.       On the Select Computer page, select the Local computer option and click Finish.

    8.       Click Close in the Add Standalone Snap-in dialog box.

    9.       Click OK in the Add/Remove Snap-in dialog box.

    10.      Expand the Certificates node and then expand the Trusted Root Certification Authorities
             node and click on the Certificates node. Right click on the Certificates node, point to All
             Tasks and click Import.




    11.      Click next on the Welcome to the Certificate Import Wizard page.




                                                                                                       16
Experiment                                                                     Softlock Smart Token Security


    12.      On the File to Import page, click the Browse button and locate the certificate of the root
             CA that we have generated before ( “Softlock CA “ certificate ) . Click Next.

    13.      On the Certificate Store page, accept the default setting, Place all certificates in the
             following store and click next.

    14.      Click Finish on the Completing the Certificate Import page.

    15.      Click OK in the Certificate Import Wizard dialog box informing you that the import was
             successful.




Configure the Web Site to Require a Client Certificate and use Basic
Authentication
Now that our certificates are in place, we can configure the Web server’s authentication and SSL
settings. Since we want a secure Web server, we’ll force users to use SSL when connecting to the
site. SSL will encrypt the user credentials and data moving between the Web client and the Web
server. We will also force integrated authentication, which is more secure than basic authentication.
However, the type of authentication used is not so important in this scenario, since the user
credentials are protected by SSL. Finally we will configure the Web site to require a user certificate.

Perform the following steps to configure the security settings on the Web site:

    1.       Click Start and point to Administrative Tools. Click Internet Information Services (IIS)
             Manager.

    2.       In the Internet Information Services (IIS) Manager console, expand the server name and
             expand the Web Sites node. Click on Default Web Site and right click on it. Click
             Properties.

    3.       In the Default Web Site Properties dialog box, click the Directory Security tab.

    4.       On the Directory Security tab, click the Edit button in the secure communications frame.

    5.       Place a checkmark in the require secure channel (SSL) checkbox and put a checkmark in
             the Require 128-bit encryption checkbox. Select the require client certificates option in
             the Client certificates frame. Click OK in the Secure Communications dialog box.




                                                                                                         17
Experiment                                                                     Softlock Smart Token Security




    6.       Click Apply and then click OK in the Default Web Site Properties dialog box




Web Authentication Using the Installed Certificate in the Token
Now we’re ready to see if our settings actually work! Perform the following steps to connect to the
secure Web site:

    1.       Before the user can log in to the website the user certificate must be placed in the user
             Smart Token.
    2.       Plug in the user smart token then Double click the client.pfx certificate a certificate import
             wizard will be appeared click next then next.




    3.       The wizard will ask you to enter the certificate password that we entered before during
             the certificate generation enter it and select “Mark this key as exportable” then click next.




                                                                                                         18
Experiment                                                                     Softlock Smart Token Security


    4.       Accept the defaults in the certificate store window and click next then finish.




    5.       You will be asked for the place to store the certificate select “Softlock certificate store “
             then click ok
    6.       The token will ask you to enter the User PIN to insure that only the token owner can store
             certificates on it. Enter the pin then click ok.




    7.       A message box will appear to inform you that the Clint certificate stored in the token
             successfully




    8.       Don’t forget to install the Root certificate on the client machine. Do that by click on the
             root.cer file and click on the install certificate button. The wizard will inform you that you
             are going to install new root click yes




    9.       Now be sure that the token is connected to the client PC,
    10.      Open Internet Explorer and enter the server access link or its IP into the Address bar. And
             make sure that you use the SSl in the URL in our case it will be “https://test“.
    11.      The browser will inform you that the server is from trusted Root. you can click view to see
             the server certificate. Click yes




                                                                                                         19
Experiment                                                                     Softlock Smart Token Security




    12.      Now the server require your certificate choose your installed the certificate from the
             token




    13.      You will be asked to enter the token pin. Enter it and click ok




                                                                                                         20
Experiment                                                               Softlock Smart Token Security




    14.      Now you are authenticated to see our demo website which is under construction




                                                                                                   21
Experiment                                                                         Softlock Smart Token Security




SMART TOKEN DEVELOPMENT
 This section introduces the students to Smart Token development solutions, getting him/her to
know in details how to:

    1.   Create cryptographic-based applications such as:
             a. Data Encryption/Decryption
             b. Data Hashing
             c. Data Signing/Verification


Smart Token Development Interfaces
Softlock smart token provides three different interfaces for developers to use, as follows:

    1.   Cryptography Service Provider (CSP) standard interface, provided by Microsoft
    2.   PKCS#11 standard interface, provided by RSA
    3.   SLSTSDK is a smart token interface provided by

                       Custom                     PKCS #11
                                                                                      CSP applications
                     applications                applications




                                                                                       CSP Module




                                                                PKCS #11 Module




                                            Smart Token SDK Module




                                           Operating System HID Layer




             Fingerprint
                                                          Smart Token Firmware
              Firmware




             Software Application      High Level Interface             Low Level Interface         Hardware




                                                                                                               22
Experiment                                                            Softlock Smart Token Security




CSP Module: This module is built on the PKCS #11 modules, providing the standard interface
required by Microsoft to build CSP interface library.

PKCS #11 Module: This module is based on the Smart Token SDK Module, providing the standard
interface required by RSA to build PKCS #11 interface library.

Smart Token SDK Module: This module communicates directly with the Smart Token hardware and
provides all token functionality via set of APIs. The communication with hardware is performed
using standard HID (Human Interface Device) communication protocol.

Operating System HID Layer: This layer is already installed with many operating systems such as,
Windows, Linux, MAC-OS, etc., in addition to being responsible for recognizing and communicating
with HID device. Hence, Softlock uses HID communication to eliminate driver installation.

Smart Token Firmware: This module is responsible for implementing all cryptographic operations,
session handling, flash-memory management and HID communication protocol.




                                                                                                23
Experiment                                                               Softlock Smart Token Security



Smart Token SDK Interface
This module is responsible for providing all cryptographic, token, session and user management
operations to external software applications. Those operations are provided through a set of APIs
(SDK) to support the cryptographic needs of other applications.
SDK operation can be divided into the following groups:

    1.   Library Management:
              a. Initializing and finalizing the library.
    2.   Token Management:
              a. Enumerating the avaliable tokens connected to the computer, and bring back their
                  IDs.
              b. Providing general information about the selected token.
              c. Opening and closing working sessions in the token, and allowing users and security
                  officers to login and logout.
              d. Preparing and formating the token.
              e. Updating the token firmware.
    3.   Memory Management
              a. Reading/Writing all memeory sections; public and private.
    4.   Random Functions
              a. Seting up and generating a random sequence.
    5.   Symmetric Cryptographic Functions
              a. Allocating and Initiating a symmetric cryptographic objects inside the token.
              b. Performing symmetric encryption, decryption, key wrapping and key unwrapping.
              c. Deallocating the cryptographic objects.
    6.   Asymmetric Cryptographic Functions
              a. Allocatimg and Initiating an asymmetric cryptographic objects inside the token.
              b. Performing symmetric encryption, decryption, signing, verification, key wrapping
                  and key unwrapping.
              c. Deallocating the cryptographic objects.
    7.   Hash Functions
              a. Allocating and Initiating a cryptographic hashing objects inside the token.
              b. Performing data and key hashing.
              c. Deallocating the cryptographic objects

All the SDK operations all fully implemented in C++ so to enable calling the SDK operations from any
other languge such as C# a SLSTCOM object is implemented .



W HAT IS COM OBJECT ?




                                                                                                   24
Experiment                                                                Softlock Smart Token Security


Component Object Model (COM) is a binary-interface standard for software component introduced
by Microsoft in 1993. It is used to enable interposes communication and dynamic object creation in
a large range of programming languages. The term COM is often used in the Microsoft software
development industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX,
COM+ and DCOM technologies.
Although Softlock Smart Token APIs can be interfaced directly from SDK DLL (Dynamic link library)
Softlock Smart Token APIs are also support COM (Common Object Model) interface beside DLL
interface.
SLSTCOM is a platform-independent, distributed, object-oriented system for creating binary
software components that can interact.. The main target of this module is to present an easy way to
interface Softlock Smart Token APIs with different languages and technologies such as:-
      C#(C-Sharp)
      VB (Visual Basic)
      Oracle
      Script languages (VBScript and JavaScript)

In the foolwoing section we are going to perform some cryptoghrapich operations using the smart
token by get use of SLSTCOM object in the C#.
To perform any operation you have first to
     1- Open visula studio -> new project -> select visual C# -> Windows application . and give your
         new project a name and location and click ok
     2- Right click your project name in the solution explorer tab and select “Add Refrence”
     3- From the add refrence wizard select the SLSTCOM from the COM tab.




    4- Include the SLSTCOMLib. And define the needed Global variables in your c# class as shown
       in the attached code




                                                                                                    25
Experiment                                                           Softlock Smart Token Security


 using System.IO;
 using SLSTCOMLib;

 namespace SLSTCOMLab
 {
     public partial class SLSTComLab : Form
     {

             /*define new object from the library
              to use it to call the library operations*/
             SLST ST = new SLST();

             /*this is the array that will hold the Tokens IDs
             many Token can be connected to the same machine*/
             UInt32[] TokensIDs;

             /*This is the variable that will hold the selected Token ID
             the token that we will use to perform the cryptograhpic operations*/
             uint TokenID;

             /*the variable that hold the session id
              * many session can be opend with the same Token*/
             uint SessionID;

             /*define the Key object that will be used in
             encryption and decryption operations "this is an symetric Key"*/
             SLSTSCryptKey CK = new SLSTSCryptKey();

             /*define the mechanism that will be used in encryption and decryption operations
              * in our case it is DES Mechanism*/
             SLSTSCryptMechanism CM = new SLSTSCryptMechanism();

             //this variable is used to get the returned error
             int ERR;




    5- Define the logInToken() function within your C# class to be apple to login the token as
       a normal user. And add the GetError () to get the returned error after each operation.
  public bool GetError()
        {
             /*the function get the last executed operation result and
if the error
              * not equal ok it out the error in a messsage box and
return tru=there is an error
              * else it return false=there is no error*/

            ERR = ST.GetLastError();
            if (ERR != 0)
            {
                MessageBox.Show("" +
ST.GetErrorMsg((uint)ST.GetLastError()));
                ST.SLSTCloseSession(SessionID);
                ST.SLSTFinalize();
                return true;




                                                                                               26
Experiment                                                             Softlock Smart Token Security


                  }
                  else return false;
             }

        private bool logInToken()
        {
            /*this function should be readed befor call the encrypt or
decrypt operation
             * the function enumerates all the tokens in the system
             * open session with the token
             * and log in the user*/
            ST.SLSTInitialize();
            if (GetError()) return false;
            TokensIDs = (UInt32[])ST.SLSTEnumerateTokens();
            if (GetError()) return false;

                  if (TokensIDs.Length > 0)
                  {
                      TokenID = TokensIDs[0];
                      SessionID = ST.SLSTOpenSession(TokenID);
                      if (GetError()) return false;

                 ST.SLSTLogin(SessionID, "",
(uint)SLSTCOM_USERTYPE.SLSTCOM_USERTYPE_USER);
                 if (!GetError())
                 {
                     MessageBox.Show("Welcome User ");
                     return true;
                 }
                 else return false;
            }
            else
            {
                 MessageBox.Show("Plug The Token Please ");
                 return false;
            }

             }



    6- To perform the Decryption operation define the Encryption() function within your class
private byte[] encrypt(byte[] OrgData)
        {
            /*The encrypt function*/

                 //define the encrypt algoirthm and key
                 CK.ALGID = (ushort)SLSTCOM_ALG.SLSTCOM_ALG_CRYPT_DES;
                 byte[] Key = { 0, 1, 2, 3, 4, 5, 6, 7 };
                 CK.Key = Key;
                 CM.ALGID = (ushort)SLSTCOM_ALG.SLSTCOM_ALG_CRYPT_DES;
                 //define the padding mechanism




                                                                                                 27
Experiment                                                             Softlock Smart Token Security


                 CM.Mode = (ushort)SLSTCOM_CRYPT_MODE.SLSTCOM_CRYPT_MODE_CBC_PAD;
                 CM.StreamBlockSize = 0;
                 byte[] IV = { 0, 1, 2, 3, 4, 5, 6, 7 };
                 CM.IV = IV;

                 //define the array that hold the encryption result
                 byte[] result = new byte[] { };
                 //initialize the encryption operation
                 uint ECryptoID = ST.SLSTCryptInitialize(SessionID, CK, CM);
                 if (!GetError())
                 {//if initialized correctly call the encryption function
                      result = (byte[])ST.SLSTCryptEncrypt(ECryptoID, OrgData, 1);
                      if (!GetError())
                      {
                          //finalize the encryption operation
                          ST.SLSTCryptFinalize(ECryptoID);

                     }
                     else MessageBox.Show("Problem during enrypting the file");
                 }
                 else MessageBox.Show("Problem during enrypting the file");
                 return result ;

             }



    7- To perform the Decryption operation define the Decryption() function within your class
 private byte[] Decrypt(byte[] EncData)
         {
             //the Decryption function
             /*the decryption mechanism and key defined in the encryption
 operation
              * you should call the decryption after the encryption operation
 in the same session
              or reinitialize the key and mechanism again here*/

                 //the result of the decryption operation
                 byte[] result = new byte[] { };
                 //initalize the decryption
                 uint DCryptoID = ST.SLSTCryptInitialize(SessionID, CK, CM);
                 if (!GetError())
                 {
                     //if initalize call the decryption operation
                     result= (byte[])ST.SLSTCryptDecrypt(DCryptoID, EncData, 1);
                     if (!GetError())
                     {

                         ST.SLSTCryptFinalize(DCryptoID);

                     }

                 }
                 return result;




                                                                                                 28
Experiment                                                                 Softlock Smart Token Security



             }



    8- In your GUI add three buttons as follow :-

              1- Login Button and add click event handler to it and call the logInToken()
              2- Encrypts Button and in its event handler call the Encrypt() function and give it the
                 content of the file you want to encrypt.
 private void DecryptBtn_Click(object sender, EventArgs e)
         {
             //The byte array that hold the Cipher Text generated from the
 encryption operation
             byte[] EncData = new byte[] { };
             /*The byte array that hold the decrypted Text generated from the
 decryption process*/
             byte[] DecData = new byte[] { };

             //show file dilaoge and get the selected file name
             openFileDialog.Filter = "Encrypted File|*.enc";
             openFileDialog.Title = "Select File to Decrypt";
             string FileName = "";
             if (openFileDialog.ShowDialog() == DialogResult.OK)
             {
                  FileName = openFileDialog.FileName;
                  FileStream fileStream1 = new FileStream(FileName,
 FileMode.Open, FileAccess.Read);
                  EncData = new byte[fileStream1.Length];
                  fileStream1.Read(EncData, 0, (int)fileStream1.Length);
                  fileStream1.Close();
                  DecData = Decrypt(EncData);
                  if (DecData != null)
                  {
                      saveFileDialog.Title = "Select Location to save the
 decrypted File";
                      saveFileDialog.Filter = "All files (*.*)|*.*";
                      string SavedfileName;
                      if (saveFileDialog.ShowDialog() == DialogResult.OK)
                      {
                          SavedfileName = saveFileDialog.FileName;
                          FileStream fileStream2 = new FileStream(SavedfileName,
 FileMode.CreateNew, FileAccess.Write);
                          fileStream2.Write(DecData, 0, DecData.Length);
                          fileStream2.Close();

                            }
                            MessageBox.Show("File Decrypted Successfully ");
                       }
                       else MessageBox.Show("Problem in Encrypt the file");
                  }
                  else
                  {
                       MessageBox.Show("You have to select a file");
                       return;
                  }




                                                                                                     29
 Experiment                                                       Softlock Smart Token Security


              }


          3- Decrypt Button and in its event handler call the decrypt()function and give it the
             content of the file you want to decrypt.
    private void encryptBtn_Click(object sender, EventArgs e)
        {
            //The byte array that hold the Palin Text to be encrypted
            byte[] OrgData;
            //The byte array that hold the Cipher Text generated from the
encryption operation
            byte[] EncData = new byte[] { };

            //show file dilaoge and get the selected file name
            openFileDialog.Filter="All files (*.*)|*.*";
            openFileDialog.Title = "Select File to Encrypt";
            string FileName="";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                 FileName = openFileDialog.FileName;
                 FileStream fileStream1 = new
FileStream(FileName,FileMode.Open, FileAccess.Read);
                 OrgData=new byte[fileStream1.Length];
                 fileStream1.Read(OrgData, 0,(int)fileStream1.Length);
                 fileStream1.Close();
                 EncData = encrypt(OrgData);
                 if (EncData!=null)
                 {
                     saveFileDialog.Title = "Select Location to save the
encrypted File";
                     saveFileDialog.Filter = "Encrypted File|*.enc";
                     string SavedfileName;
                     if (saveFileDialog.ShowDialog() == DialogResult.OK)
                     {
                         SavedfileName = saveFileDialog.FileName;
                         FileStream fileStream2 = new
FileStream(SavedfileName, FileMode.CreateNew, FileAccess.Write);
                         fileStream2.Write(EncData, 0, EncData.Length);
                         fileStream2.Close();

                             }
                             MessageBox.Show("File Encrypted Successfully ");
                         }

                  }
                  else
                  {
                         MessageBox.Show("You have to select a file");
                         return;
                  }




                                                                                            30
Experiment                                                               Softlock Smart Token Security




         }

             4- Run your application then click the login button you will be asked to enter the user
                Pin enter it and press ok
             5- Click on the encrypt button and see the result.
             6- Click on the decrypt button and see the result.




                                                                                                   31
Experiment                                                               Softlock Smart Token Security



CSP Interface
In Microsoft Windows, a Cryptographic Service Provider (CSP) is a software library that implements
the Cryptographic System Programming Interface (CSPI). CSPs implement encoding and decoding
functions, which computer's application programs may use. e.g. strong authentication of the user or
for secure email.CSPs are independent modules that can be used by different applications. A user
program calls CryptoAPI functions and these are redirected to CSPs functions. Since CSPs are
responsible for implementing cryptographic algorithms and standards, applications do not need to
concern about security details.in the following we are going to use the standard CSP interface to
call our smart token and perform the sign and versign operations.

    1- Create new windows application

    2- Include the CSP libraries as shown

    3- Define the needed global variables as shown

    4- Add the sign button and in its event handler add the code as shown

    5- Add the verify button and add its event handler code as shown

    6- Run your application and see the result


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//include the CSP Libraries
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace CSPCS
{
    public partial class CSPLab : Form
    {
        //this is the palin text that will be signed
        Byte[] orgdata = { 0, 1, 2, 3, 4, 5, 6, 7 };
        //this array will hold the signature
        Byte[] sign;
        //define new X509 Certificate
        X509Certificate2 certificate = new X509Certificate2();

             public CSPLab()
             {
                 InitializeComponent();




                                                                                                   32
Experiment                                             Softlock Smart Token Security


             }

             private void Sign_Click(object sender, EventArgs e)
             {
                 //define new Certificate store
                 X509Store store = new X509Store();
                 //open the certificate store
                 store.Open(OpenFlags.ReadWrite);
                 /*once opened the Store it will
                  * enumerates all the certificates in the Token
                  * or the machine itself*/

            if (store.Certificates.Capacity == 0)
            {
                 MessageBox.Show("No Certificates in the Token");
                 return;
            }
            //select the first certificate to use
            certificate = store.Certificates[0];
            //get the private key from the certificate to sign the data
           RSACryptoServiceProvider rsas =
(RSACryptoServiceProvider)certificate.PrivateKey;
            //sign the data
           sign = rsas.SignData(orgdata, new
SHA1CryptoServiceProvider());
           System.Text.ASCIIEncoding encoding = new
System.Text.ASCIIEncoding();
           string dsignedstring = encoding.GetString(sign);
           MessageBox.Show("This is the Signed Message \n"
+dsignedstring);


             }

        private void Verify_Click(object sender, EventArgs e)
        {
            //get the certificate public key to verify the signature
            RSACryptoServiceProvider rsav =
(RSACryptoServiceProvider)certificate.PublicKey.Key;

            //verify signature
            Boolean verified = rsav.VerifyData(orgdata, new
SHA1CryptoServiceProvider(), sign);

                 //out the result
                 if (verified)
                      MessageBox.Show("The signature is Correct");
                 else
                 MessageBox.Show("The signature is Incorrect");

             }




                                                                                 33
Experiment   Softlock Smart Token Security


     }
}




                                       34
Experiment                                                                  Softlock Smart Token Security




ABOUT SOFTLOCK
Softlock is the world’s leading progressive, innovative, expanding national and international
company in the field of digital security. Our aim is to gain customer satisfaction, on time and every
time. We are established since 1997 to create quality security and to keep the value for what’s
important in your life.

Our high quality service and excellent benefits and the ability of being reliable and responsible put
us as a leader on the top of digital security companies.

Softlock provides unique products and solutions, which cover many security areas fulfilling
customers need in different market sectors. We provide a set of products and solutions covering the
following areas: software protection, data encryption, security hardware, digital signature, secure
identification and authentication, secure online distribution of digital Contents.

Softlock supports different market sectors like; governmental institutes, organizations, banks,
software development companies, multimedia software and game producers, media and eBooks
publishers and individual users.

Softlock value comes from the continuous research, the integrated products, the realistic
implementations, and the successful support since 1997.

Softlock is recognized in the local market as the only owner and provider of digital security services.

Softlock is uniquely identified in the global market by the integrated products and the research
based development.



Website                   www.softlock.net

Email                     info@softlock.net, support@softlock.net, sales@softlock.net

Telephone                 +(202)26702267, +(202)26702269

Fax                       +(202)26702269




                                                                                                      35