Are there any cracking tolls for RSA

Java Smartcard support under Linux


1 Authors: Jan Keller, KI00 Carla Schaffner, KI00 Lecturer: Prof. Dr. Andreas Steffen Diploma thesis: DA Sna 03/3 Period: September 5, October 2003

2 Table of Contents Table of Contents Legal Disclaimer ... V Task ... VI Summary ... VII Abstract ... VIII 1. Introduction Project planning Network plan Project schedule Specification Functional requirements Non-functional requirements Basics Hash function Certificates Cryptography Encrypt (Decrypt) Sign ( Sign) Verify (Verify) Smartcards What are Smartcards? Field of application of the smartcards? File system of the smartcards PC / SC Padding PKCS # 1 v1.5 Padding RSA OAEP RSA PSS Digest Info Problem analysis Use cases Read certificates from the Smartcard Create signature Verify signature PKCS # 11 / Cryptoki OpenSC Java Native Interface (JNI) Java Cryptography Architecture / Extension (JCA / JCE) Jan Keller Carla Schaffner I

3 Table of contents 6. Solution concepts Overview of solution variants PC / SC implementation State diagram of the Smartcard PKCS # 11 API C_Sign / pmechanism Digest Info in OpenSC Macros in C Implementation of the Java Native Interface Implementation of the provider Communication of the components Class diagrams Sequence diagrams Components used Hardware Cryptoflex 8k Reflex 72 V2 RS232 Reader Software Java Classes C Tests SignatureWithRSA.class CertificateFactoryX509.class CertificateReader.class Util.class JNIForJLinProvider.class Problems ASCII to Hex C Java Decrypt with C_Decrypt JCE Service CertificateFactory Decision and solution Sign the provider Digest Info Use the provided OpenSC files Use the dynamic provider Embed Static embed Use the provider's service signature Use the provider's service certificate factory Verify the created signature Jan Keller Carla Schaffner II

4 Table of contents 11. Open points Conclusion Appendix A. Glossary B. Return values ​​PKCS # C. Source code D. CD Table of contents E. List of sources E.1. Books E.2. Left E.3. Reference person F. Installation instructions G. Operating / configuration instructions H. Example application Jan Keller Carla Schaffner III

5 List of figures List of figures Figure 1: Encrypt process ... 8 Figure 2: Decrypt process ... 9 Figure 3: Sign process ... so files Figure 33: LD_LIBRARY_PATH Figure 34: Client / Server GUI Figure 35: Send random number Figure 36: Certificates and random numbers Figure 37: Empty parameter Gui Figure 38: Completed parameter Gui Figure 39: After the signature process Figure 40: Verification successful Figure 41: Verification failed Jan Keller Carla Schaffner IV

6 Introduction Legal Disclaimer 2003 Zurich University of Applied Sciences Winterthur (ZHW). All rights reserved. No part of this documentation may be reproduced in any form (photocopy, microfilm or any other mechanical or electronic process), not even for the purposes of teaching, or stored, processed, duplicated or distributed using electronic systems without the written consent of the authors or the ZHW . The authors and the ZHW do not accept any liability for the correctness of the information in this work. Furthermore, the authors or the ZHW are under no circumstances liable for indirect or direct consequential damage or special consequences that arise from or in connection with this documentation, regardless of whether they arise due to unauthorized actions, a contract or other reasons in connection with this documentation . Companies and product names mentioned and / or used in this documentation are trademarks and / or trademarks of the associated companies. Note In order to improve the fluency of reading, the feminine form is not used. It goes without saying that both male and female persons are addressed equally. Jan Keller Carla Schaffner V.

7 Introduction Tasks Final diploma examination Practical diploma thesis Lecturer: Prof. Dr. Andreas Steffen Course: KI Year: 2003 Student: Jan Keller Issue: September 5th, 2003 Carla Schaffner Submission: October 27th, 2003 Description: The OpenSC project (allows smart cards and crypto tokens to be addressed via a manufacturer-independent PC / SC interface under the Linux operating system . With the PKSC # 11 Cryptographic Token Interface Standard there is a standardized, C-based API with the help of which cryptographic operations can be outsourced to the smart card. In the proposed diploma thesis, a Cryptographic Service Provider (CPS) is to be based on the existing PKCS # 11 API. can be made available under Java by embedding the C function calls from OpenSC in a Java Native Interface (JNI). The Java Smartcard support gained under Linux can then be used, for example, within the framework of the Apache XML Security project (/ security) to create XML signatures Objectives: Understand the Java Cryptography Extension (JCE) Understanding the PKCS # 11 interface Creation of a cryptographic service provider (CPS) under Java, which is implemented by embedding OpenSC functions.Minimal functions of the CSP: o Retrieving certificates stored on the smart card o RSA signature of an MD5 or SHA 1 hash value Creation of a small Java demo application on the smart card, which calls the implemented JCE functions Jan Keller Carla Schaffner VI

8 Introduction Summary This thesis deals with the use of smart cards in connection with the popular and frequently used RSA public key algorithm, more precisely with its functions of digital signature and encryption. From a security point of view, smart cards are an ideal storage medium for objects worth protecting because the private key stored on the card can no longer leave the smart card. The main task of this diploma thesis was to implement a Cryptographic Service Provider (CSP) for Java on the Linux platform. Its main function is to ensure the authenticity of the signer and the integrity of the data by signing data. The provider could not be developed in pure Java because the PKCS # 11 API used for accessing the smart card is written in C. The JNI (Java Native Interface) from SUN was used to link C and Java. Nevertheless, a significant part had to be coded in C in order to take full advantage of the PKCS # 11 API. To ensure that the KelschaJLin provider can be used by any Java application, it was implemented according to JCA / JCE (Java Cryptography Architecture / Extension). These interfaces specify how a provider must be implemented in order to be able to use its functions. The OpenSC and PKCS # 11 libraries were available to us for the C programming language. The KelschaJLin Provider Version 1.0 created in this practical work has so far been equipped with two services: On the one hand, it is possible to generate an MD5 or SHA 1 hash of any data, which is then signed on the smart card and, on the other hand, all of them can be saved on the smart card Certificates are obtained. Using an OpenSC release from October 1, 2003, according to the developers, it would also be possible to expand the KelschaJLin provider to include the decryption function. Date: Jan Keller Carla Schaffner Jan Keller Carla Schaffner VII

9 Introduction Abstract This diploma paper deals with the widespread RSA Public Key Algorithm and its functions sign and encrypt in conjunction with keys stored on a smart card. Because of the fact that a private key once stored on a smart card can never be retrieved or even read, smart cards are a very secure place to save secret objects. The essential part of this diploma thesis was to develop a Cryptographic Service Provider (CSP) for Java based on the Linux operating system. This provider offers functions to sign data whereby the authenticity of the sender and the integrity of the data are guaranteed. Due to the fact that the PKCS # 11 API provided by the OpenSC workgroup is written in C, it was not possible to develop the provider in pure Java. Therefore Sun's JNI (Java Native Interface) was used to link the pieces of C code with Java. To ensure that the provider can be properly used by any application it is built according to the Java Cryptography Architecture / Extension (JCA / JCE). These interfaces describe the structure of the provider and designate how the functions have to be called. The actual version 1.0 of the KelschaJLin provider supports two features: Generation of a MD5 or SHA 1 hash that gets signed on the smart card. Retrieval of the certificates stored on the smart card Equipped with an OpenSC library released after October, it should be possible according to the developers to supply the provider KelschaJLin with an decryption function. Jan Keller Carla Schaffner VIII

10 Introduction 1. Introduction This report describes the work that was carried out over the course of 7 weeks for the implementation of the Cryptographic Service Provider. The purpose of the report is to document the status of the work and to create the conditions for the work to be continued at a later point in time. The report is divided into the following areas: Chapters 2 and 3 describe the planning and requirements of the project. In chapters 4 and 5, the technical basics of the methods and solutions used are created and a problem analysis is carried out. Chapters 6 and 7 describe the procedures, solutions and resources that were used to solve the tasks. The last part of the report, Chapter 8 11, is intended to provide an overview of the end product and its use and expansion. These chapters also describe the test results that confirm that the tasks have been completed. In the appendix, the most important information about the completed tasks and the sources of information are included in the report. Planning / Procedure (Page 2 4) Project plan Functional specification Basics (Page 5 28) Basics Problem analysis Solution (Page 29 53) Solution concept Components End product (Page 55 82) Appendix (Page) Test Problems Use Conclusion Glossary Source Code References Instructions Jan Keller Carla Schaffner

11 Project planning 2. Project planning 2.1. Network plan Jan Keller Carla Schaffner

12 Project planning 2.2. Project schedule Parallel to the respective tasks, the documentation was worked on so that it only had to be compiled and adapted in the last few weeks. Jan Keller Carla Schaffner

13 Specification 3. Specification 3.1. Functional requirements [1] Tasks of the provider It must be possible to use this provider to call up all certificates stored on the smart card. In addition, it must support the functionality of signing a SHA 1 or MD5 hash value with the private key stored on the card. [2] Integration of the provider The provider should be able to be used in its own Java application by means of plug and play. To ensure this, the provider must be implemented according to JCE (Java Cryptographic Extension). [3] Integration of the PKCS # 11 API To access the smart card, the existing PKCS # 11 API should be used. The C function calls from OpenSC should then be embedded in a Java Native Interface (JNI) in order to be able to access them with the provider. Non-functional requirements [1] Platforms This provider is written for the Linux platform. The J2SDK1.4.1 must be installed and operational. In addition, the OpenSC tools from the OpenSC project and the driver for PC / SC reader Reflex 72v2 from Schlumberger must be installed. [2] Hardware The smart card reader used for this work is the Schlumberger Reflex 72v2., As well as the Crytoflex smart card from Schlumberger. Jan Keller Carla Schaffner

14 Basics 4. Basics 4.1. Hash function A one-way hash function is primarily used to compress a quantity of data to a certain length. The result of this function is the so-called hash or fingerprint. This hash is a unique checksum of a file or a data set. The hash value should depend on every single bit of the file so that the hash value is fundamentally changed with the slightest change in the file. It is important that a hash function works quickly and efficiently, since it must also be possible to pass gigabyte-sized files to a hash function. In addition, two different files must never result in the same hash. The most common hash functions are MD5 (Message Digest 5) and SHA 1 (Secure Hash Algoritm 1). This thesis does not go into the exact creation of a hash. Certificates A digital certificate is comparable to a passport. It also serves as proof of identity. More precisely, it confirms that a certain public key (which is contained in the certificate) also belongs to the person who claims to be its owner. Like the passport, the certificate is issued by a trustworthy authority, a so-called certification authority (CA) such as VeriSign. In contrast to the passport, however, there is no state certification body. Applications of certificates are, to name a few examples, electronic signatures, secure e-mails and authentication in client-server applications. The most widely used standard for digital certificates is the X.509 standard. A digital certificate is a coded file that must contain the following information: Name of the certification object Name of the issuing authority (e.g. VeriSign) Digital signature of the certification authority (MD5 or SHA 1) Public key (e.g. RSA 1024 bit key) Validity period 1 For further information see RFC 1321 (MD5) and FIPS PUBS (SHA1) Jan Keller Carla Schaffner

15 Basics 4.3. Cryptography Cryptography is the art and science of changing data in such a way that it is safe from unauthorized reading or modification. There are different algorithms in cryptography. This thesis deals with public key cryptography (asymmetric cryptography). In the asymmetrical algorithms, which are based on the principle of the public and private key (public / private key), encryption and decryption keys differ. It is difficult or, if the key length is sufficient, practically impossible to calculate the decryption key from the encryption key. 2 As the name suggests, the public key is publicly known; Anyone can use it to encrypt a message, but only the person in possession of the private key can decrypt and read the message. If the procedure is used in the opposite direction, this is called signing. One of the most popular public key algorithms is RSA. Public key cryptography is based on the principle of prime factorization. The following steps are necessary to calculate a key pair: Two large (1024 bit) prime numbers p and q are chosen at random. The product is now calculated from these two prime numbers p * q = n A public exponent e must be chosen, where it applies that e <(p 1) (q 1) and the e, (p 1) and (q 1) none have common prime factors. Now the private exponent can be calculated: d = e 1 mod (p 1) (1) according to the Euclean algorithm, the formula can be transformed as follows: d * e mod (p 1) * (q 1) = 1 The private key exists from the private exponent d and the modulus n. The public key consists of the public exponent e and the modulus n. The prime factors p and q are no longer needed after the key has been generated. For this reason, they should be deleted immediately after they have been used so that the calculation of the private key using these factors is no longer possible. If a plain text x is now to be encrypted, this is done with the function y = x e mod n. The decryption of the ciphertext y, however, is then calculated with the function x = y d mod n. 2 Jan Keller Carla Schaffner

16 Basics Simple calculation example: 1. p = 3, q ​​= n = p * q = (p 1) * (q 1) = 2 * 16 = 2 * 2 * 2 * 2 * 2 = 32 (public exponent must not be a 2nd 4. possible combinations of public and private exponents: ede * de * d mod With an RSA key pair, consisting of private and public key, various cryptographic operations can be carried out. The following operations are explained in more detail on the next few pages. Encrypt Decrypt Sign Verify Jan Keller Carla Schaffner

17 Basics Encrypt Sensitive data that is sent and may only be read by the recipient can be encrypted with the public key of this person. This encryption allows messages to be protected from unauthorized reading. This is the plain text that should be encrypted. Plain text that can only be read by an authorized person. Encryption with Public Key The data is encrypted with the recipient's public key. vbnzusianuezthwolmynz wpnchndakidhnekiadfkid nfkdosinkdosjdkkkad The ciphertext 3 is now transmitted over the public, insecure network (e.g. Internet). Figure 1: Encrypt process 3 encrypted text, ciphertext Jan Keller Carla Schaffner

18 Basics Decrypting (Decrypt) Data that has been encrypted for a specific person cannot be viewed. Therefore, they must first be decrypted using the person's private key. vbnzusianuezthwolmynz wpnchndakidhnekiadfkid nfkdosinkdosjdkkkad The received message is encrypted and cannot be deciphered. Decryption with Private Key The encrypted data can now be decrypted with your own private key. This is the plain text that should be encrypted.If the message has been encrypted with your own public key, the message can be read in plain text after decryption. Figure 2: Decrypting the process Signing (Sign) Every day, an enormous amount of data is sent via an insecure channel (e.g. the Internet). If the integrity of the data and the authenticity of the sender are to be ensured, the digital signature can be used. This is the message to be signed. This text should be signed. Hash Function First, a hash is created over the entire document. For example, the hash algorithms MD5 or SHA 1 can be used. The hash value is 128 (MD5) or 160 (SHA 1) bits long, depending on the algorithm. Encryption with Private Key Now the hash value is encrypted with the private key. Signature This results in the 1024-bit signature. Figure 3: Signing the process Jan Keller Carla Schaffner

19 Basics The sender sends the signature and the unencrypted text to the recipient. If the recipient is in possession of the sender's public key, he can verify the signature. Verify In order to verify a signed message, the recipient must be in possession of the sender's public key. Usually the certificate, which also contains the public key, is sent with signed messages. If this is not the case, the certificate must be downloaded elsewhere (e.g. from an LDAP server). The sender of the message gives you both the unencrypted message and the 1024-bit signature. This is the message to be signed. The received message to be checked for integrity and authenticity. Hash function The recipient also creates a hash value for the entire document. Receiver and sender must use the same algorithm. If the two hash values ​​match, the integrity of the data and authenticity of the sender is ensured. Decryption with Public Key This signature is decrypted with the sender's public key. This decryption results in a hash value that must match the hash created. Signature The signature received. Figure 4: Verifying the process Jan Keller Carla Schaffner

20 Basics 4.4. Smart cards What are smart cards? The term intelligent card describes a data carrier in credit card format with different capabilities. The smart card contains an embedded chip that processes data and stores it, protected by a number of security features. There are essentially three different types of smart cards: Memory cards This card can only store data and does not contain its own processor. It therefore needs a third-party processor outside the card to process data. This card type offers the lowest level of security. Microprocessor cards A microprocessor card has its own processor with operating system and can process data independently. If a card also has a numerical coprocessor, it is called a crypto card and is used for cryptographic applications. To communicate with the outside world, the card must be inserted into a card reader. With this type of card, the chip is visible from the outside. Contactless card These cards communicate with the computer via a radio signal within a certain minimum distance from an antenna. The chip and the antennas are usually not visible from the outside. Today, both contactless memory cards and contactless microprocessor cards are available. Field of application for smart cards The possible uses of smart cards are extremely varied and, thanks to the growing computing power and storage capacity, are constantly increasing. Only a small overview of some applications is given here. The smart cards quickly became known through their use as public telephone cards. In the meantime these cards are also used as health insurance cards, SIM cards for mobile phones, EC cards, and as in our work for Jan Keller Carla Schaffner

21 Basics of digital signatures. Abroad, smart cards are even used for toll systems 4 Smart card file system The chip card's ISO file system consists of 3 different file types: Elementary Files (EF) EFs are used for the actual data storage. Names, dates or serial numbers are stored in them. There are four different types of elementary files: Transparent EF Mainly used to store objects such as keys, certificates, etc. A transparent EF is a storage object without an internal structure (therefore transparent). When accessing, the offset and the number of bytes to be processed are specified. Fixed length linear EF The memory object is divided into different areas, so-called records. Each record is addressed by a unique number that is assigned when it is created. As the name suggests, the fixed length linear EF are divided into records of the same size. The size of the records is 0 to 255 bytes, the maximum number of records is 255. Variable length linear EF In contrast to the fixed length linear EF, records of various sizes can be created in the variable length linear EF. Here, too, the size is 0 to 255 bytes and the number of possible records is 255. Cyclic EF As with the fixed length linear EF, cyclic EF are divided into 0 to 255 records of the same size. However, addressing takes place in a ring in which the current record always has index 1. If the last record was written, the pointer jumps back to the first one, which is then overwritten. Cyclic EF s are mainly used to save the history of the last transactions. 4 Road tax systems 5 Further information can be found in the book Handbuch der Chipkarten by Wolfgang Rankel and Wolfgang Effing. Jan Keller Carla Schaffner

22 Basics of Dedicated Files (DF) A DF is a subdirectory in the file system and can contain further DFs or EFs. If there is a key file (e.g. CHV) in the directory, its PIN is used for the access rights. If this is not the case, a search is made in the next higher directory until one is found. This means that a key file is valid down the path until another one takes over the access control. Master File (MF) The MF is basically a normal DF with the designation 3F00, which is selected when the card processor starts up. It is the root directory of the file system. A new card or a card erased with the cryptoflex eraser has the following file structure: 3F Figure 5: File structure cryptoflex eraser Under the root directory MF (3F00) there are also an external key file (0011), a serial number file (0002) and a key file (0000) created. After creating the PKCS # 15 structure with the pkcs15 init tool, the file system of the card looks like this: wef 3F00 DF F Name Size Figure 6: PKCS # 15 file structure Jan Keller Carla Schaffner

23 Basics A detailed description of the individual files can be found in the table on page 16. If a certificate with the associated private key is loaded onto the card, we will find the following file structure: 3F FB Figure 7: Card with certificate and private key The two green files belong to the certificate, the red ones contain the private / public keys or the PIN / PUK in addition. PKCS # 1 creates a public key file 5201 with the corresponding pointer in directory 5015 by default. This means that the public key is available twice on the card. Once in file 5201 (PKCS # 1) and again in the Cryptoflex-specific directory 4B01 in the file.Firstly, because the public key is not particularly worth protecting and, secondly, it is also contained in the certificate, files 5201 and 1012 are rather irrelevant. If another certificate including the private key is added, PKCS # 15 creates another certificate file (5502), updates the pointer 4404 and creates a new directory (4B02) with the same file structure for the second private key. If the relationships are shown graphically in the file system, it becomes clear where the real data are: Jan Keller Carla Schaffner

24 Basics 3F F B Figure 8: Pointers and data files The red files contain the key, the blue rules the access (PIN / PUK), the green files contain the certificate and the orange files contain other information such as the serial number and manufacturer of the card. Apart from the Cryptoflex proprietary files below 4B01, all files are encoded in ASN.1. Jan Keller Carla Schaffner

25 Basics Description of the files: 3F00 Master file / root directory 0011 External key file manufacturing and transport key. Card is blocked if deleted Serial Number File B FF FF Card becomes unusable if deleted CHV key file Contains PIN and PUK of the current directory 5015 Directory 2F00 DIR Pointer to one or more PKCS # 15 directories (here 5015) 4401 DODF (Data Object Directory File ) Pointer to the directory with the private keys. 3F00 / 5015 / 4B ODF (Object Directory File) Points to the pointers that point to the various PKCS # 15 objects. (PrKey, PubKey, Cert,) 3F00 / 5015/4402, 4403 and TokInf OpenSC Project / OpenSC Card 5501 Cert x Certificate in ASN CDF (Certificate Directory File) Pointer to the certificate. 3F00 / 5015/5501 4B01 Directory 4402 PrKDF (Private Key Directory File) Pointer to one or more private keys. 3F00 / 5015 / 4B01 / Public Key (PKCS # 1) 4403 PuKDF (Public Key Directory File) Pointer to the public key. 3F00 / 5015 / Private Key 1012 Public Key (Cryptoflex) Table 1: Description of the files Jan Keller Carla Schaffner

26 Basics 4.5. PC / SC The PC / SC (Personal Computer / Smartcard) Workgroup, consisting of the core members Apple, Gemplus, Infineon, Ingenico, Microsoft, Philips, Schlumberger and Toshiba, set itself the goal of developing a manufacturer and platform-independent specification and thus to promote the use of smart cards in the PC sector. Under Linux, the PC / SC API is implemented as a 3 tier architecture and thus creates independence between the application and the smart card readers. This means that the application communicates with the middleware PC / SC, which in turn controls one or more readers. The PC / SC standard requires that the communication takes place on the lowest level according to ISO 7816. The architecture consists of the following components: ICC Aware Application 1 Tier Service Service Providers Providers 2 Tier ICC Resource Manager IFD Handler IFD Handler IFD Handler RS-232 PS / 2 PC Card IFD IFD IFD 3 Tier ICC ICC ICC Figure 9: PC / SC architecture Jan Keller Carla Schaffner

27 Basics ICC Aware Application Any program that would like to use the functions of a SmartCard. Service Providers The service provider is responsible for ensuring that the functions of a SmartCard are transparently available to the higher-level applications. This means that the application can access it regardless of the card, hardware or operating system and does not need to know the internal structure of the card. According to the specification, the service provider consists of two independent components: the ICC service provider and the cryptographic service provider. Although the whole thing can usually be found as one component, the division makes sense due to import / export restrictions of the different countries. ICC Service Provider The ICC Service Provider provides higher-level applications with SmartCard-specific access functions such as file access or authentication. Before a service provider can communicate with the SmartCard, it must register with the ICC Resource Manager. During this process, the service provider is given information about the card, which he then needs to control it. Cryptographic Service Provider The Cryptographic Service Provider provides higher-level applications with SmartCard-specific, cryptographic functions. These include: Key generation Key management Digital signatures Hashing Encryption services If one or more of these functions are subject to import or export restrictions, the service provider will be delivered without a cryptographic service provider and the SmartCard application will run perfectly except for these functions. ICC Resource Manager As one of the most important components in the PC / SC architecture, the ICC Resource Manager is responsible for the management of ICC resources and secure access to the SmartCard. This system level component is usually provided by the operating system supplier and may only be installed once per system. Communication takes place via RPC. Jan Keller Carla Schaffner

28 Basics The ICC Resource Manager deals with the following problems in connection with access to several IFDs and ICCs: Provision of information about installed IFDs and smart card types and their supported functions. Monitoring the insertion and removal of ICCs for providing information on operational smart cards. Regulation of access to the ICCs under several applications. Definition of transaction primitives. Since smart cards are single threaded devices, several commands have to be executed for one function. Transaction primitives ensure that, in multi-program operation, these command sequences also run atomically and are not interrupted. IFD handler The IFD handler is supplied by the manufacturer of the reader and is the actual driver for the IFD. It enables the higher-level components to access the reader, regardless of the hardware and properties of the card. From the IFD handler down to the smart card, communication takes place in accordance with the ISO standard. IFD The interface device (or smart card reader) is the physical connection between the chip card and the computer. The smart card is connected to the reader via several contacts and is thus supplied with power, clock and data line. PS / 2, RS 232, PCMCIA or USB are used as the physical connection. IFD as well as ICC must conform to ISO standards, 2,3. ICC Integrated Chip Card. Smart card or chip card. Jan Keller Carla Schaffner

29 Basics 4.6. Padding In the case of an RSA signature, a data block to be signed is 128 or 160 bits long and the resulting signature is 1024 bits long. Padding describes the method of how the remaining 896 or 864 bits are filled and has the purpose of adding randomness to the signature of a text. Randomness, so that the signature process of a text also produces different signatures through different applications and thus to protect them from Chosen Ciphertext attacks PKCS # 1 v1.5 Padding PKCS # 1 v1.5 Padding is still included in the RSA standard, but only for reasons of compatibility older applications. The use of OAEP or PSS is strongly recommended for new applications. With PKCS # 1 v1.5 padding, the space to be filled (using SHA1 as an example: 1024 bit signature minus 160 bit hash equals 864 bit padding) is mainly filled with random non-zero bytes. In order to be able to distinguish the actual data from the padding, a 0 byte is inserted at the beginning and at the end of the padding. After the 0 byte at the beginning, a block type byte is inserted that defines the type of the RSA operation. For example, it is 0x02 for encryption / decryption operations and 0x01 for signature / verification operations. plaintext hashing J.åì ± .š.L.só / é.I 20 byte SHA1 Padding 0 2 random 0 J.åì ± .š.L.só / é.I 20 byte hash byte padding signing! òCÉÏ'æ6Œƒà "É8Á [qå- + Ÿ [æø b / ü4èf "` pajä¼çá "ó # r" 128 Byte Signature Figure 10: Padding process with PKCS # 1 v1.5 Jan Keller Carla Schaffner

30 Basics After the so-called Million Message Attack by Bleichenbacher became known in 1998, in which answers to the key could be closed in an SSL session by the transmission of a large number of randomly constructed ciphertexts with the help of the server, RSA brought an improved version (2.0 ) of the standard. As it turned out, however, the new version was even more vulnerable to a slightly modified attack. While version 1.5 required around a million modified ciphertexts, version 2.0 only needed a few thousand. Digitally signed emails or texts are not affected by this attack. Since the victim receives at least a few thousand encrypted messages and has to evaluate them, only one machine can be used. The use of the PKCS # 11 v1.5 padding procedure should therefore be problem-free for such digital signatures RSA OAEP RSA OAEP (Optimal Asymmetric Encryption Padding), developed by Bellare and Rogaway in 1994 and included in the RSA standard since version 2.0, is one of the most secure methods to encode data for RSA encryption. The process, which is much more complicated than that of PKCS # 1 v1.5 padding, is outlined below. The following are given: mhash hash value of plain text mlen length of plain text P parameters phash hash of parameters PS padding string emlen length of signature hash hash function hlen length of hash MGF mask generation function 1. choose a random string seed 2. put string PS (padding string ) together, consisting of emlen, mlen, hlen and a 0 byte 3. calculate phash = hash (P) 4. data block DB = phash + PS + M 5. dbmask = MGF (seed, Len) 6. maskeddb = dbmask XOR DB 7. seedmask = MGF (maskedDB, Len) Jan Keller Carla Schaffner

31 Basics 8. maskedseed = seed XOR seedmask 9. EM = maskedseed + masked DB 10. the padded hash is now signed with the private key seed mhash PS phash data block MGF maskeddb MGF maskedseed padded hash Figure 11: Padding process with OAEP OAEP RSA encrypted is considered provably safe. More precisely, if the hash functions in the MGF are really random, then RSA must be cracked to decrypt the message. To date, no vulnerabilities have been discovered in OAEP. Since OpenSC unfortunately does not yet support OAEP, the normal PKCS # 1 v1.5 padding method is used in the present work RSA PSS RSA PSS (Probabilistic Signature Scheme) has been included in the PKCS # 1 standard since version 2.1 and corresponds primarily to security today's requirements.Although the PKCS # 1 v1.5 signature scheme is currently still considered to be state of the art, RSA recommends a slow but secure transition to PSS. Jan Keller Carla Schaffner

32 Basics A PSS padding process works as follows: The following are given: mhash hash value of plain text padding Fixed value salt Random value 1. A random value salt is generated 2. Data block 1 is composed of padding, mhash and salt 3. Calculate hash H from data Block 1 4. Form data block 2 from padding 2 and salt 5. Apply the mask generation function MGF to data block 1 6. XOR link the mask with data block 2 7. Place padded hash from maskeddb, hash and bc together 8. Sign padded hash with the private key padding 1 mhash salt data block 1 padding 2 salt data block 2 hash MGF bc maskeddb H padded hash Figure 12: Padding process with PSS Like OAEP, PSS is not yet supported by OpenSC. Jan Keller Carla Schaffner

33 Basics 4.7. Digest Info So that a signature can be verified, the recipient's tool must know which hash algorithm the signature program used to create the message digest. For this reason, information must be appended to the hash before the message digest is signed (more precisely before a padding process is used). This information is packaged in the DER format in an ASN.1 construct. This construct looks like this: (asn1parse) 0: d = 0 hl = 2 l = 33 cons: SEQUENCE 2: d = 1 hl = 2 l = 9 cons: SEQUENCE 4: d = 2 hl = 2 l = 5 prime: OBJECT: e.g. sha1 11: d = 2 hl = 2 l = 0 prim: NULL 13: d = 1 hl = 2 l = 20 prim: OCTET STRING The first number of the asn1parse stands for the offset of the object in decimal, d indicates the depth, in which the object is located, hl is the header length and l is the length of the user data. plaintext J.åì ± .š.L.só / é.I 20 bytes SHA1 padding 0! J.åì ± .š.L.só / é.I 35 bytes ASN.1 construct 93 bytes padding 20 bytes HHH sha1 HH J.åì ± .š.L.só / é.I 35 bytes Figure 13: Padding with digest Info Jan Keller Carla Schaffner

34 Basics Both the signature and the digest info with the value SHA1 can be seen in the graphic. Each object has a header H of length 2. The yellow object has the value NULL and therefore consists of only one header. What a padding looks like without an OID is shown in Figure 10. Jan Keller Carla Schaffner

35 Problem analysis 5. Problem analysis 5.1. Use Cases This chapter shows possible scenarios for using applications that support smart cards. One possible application would be to implement a smartcard-supported login process. If a user wants to use a certain application, he has to authenticate himself. To do this, the server first reads all certificates from the card and then the client must sign a random value received from the server on its smart card. The signature can then be verified by the server using a public key. This application can be divided into three individual use cases: Reading certificates from the smart card In order for the server to be able to verify the signature received, it must have the user's public key. The system uses a provider to open the connection to the smart card. All slots are contacted and the stored certificate, if available, is retrieved. Create signature The system sends an arbitrary character string to the user. This signs the character string on the smart card. The system can now verify this signature with the user's public key and thus ensure the authenticity of the user. If the pin for the private key is incorrect, an error is displayed and no signature is made. If there is no private key in the specified slot, no signature is created and an error is displayed. Jan Keller Carla Schaffner

36 Problem analysis Verifying the signature The signature created by the client is verified by the server using the public key. If the verification is successful, a positive result is displayed to the client. If this is unsuccessful, an error message is displayed to the client. PKCS # 11 / Cryptoki PKCS # 11, also known as the Cryptographic Token Interface Standard, specifies an interface for applications that access tokens in order to carry out cryptographic operations. These tokens can be smart cards, USB dongles or PCMCIA cards. The implementation of this interface under Linux is briefly explained in the next section. OpenSC With its libopensc library, the OpenSC Workgroup implemented a PKCS # 11 API for access to smart cards under Linux. It provides basic functions such as SELECT FILE, READ BINARY, etc., which can be used to access any ISO compatible card. In addition, RSA crypto operations are possible on all PKCS # 15 compatible cards. Mainly the platforms Linux and Mac OS X are supported, certain functions have been ported to Windows. In addition to the library files, the OpenSC package contains the following tools: opensc tool for managing the readers, drivers and cards. opensc explorer for accessing the files on the card pkcs15 tool reads objects (certificates, keys) from the card pkcs15 crypt enables RSA decryption and digital signatures with PKCS # 15 cards pkcs15 init for configuring the card. Jan Keller Carla Schaffner

37 Problem analysis 5.4. Java Native Interface (JNI) Since the PKCS # 11 API only provides C functions, these must be made available to the Java classes using the Java Native Interface. In order to realize this, an interface must first of all be implemented on the Java side. This interface is created using native methods. A header file is then created from this interface in which all native methods are declared and which is integrated in the C file in which the functions are implemented. Function calls, parameter transfer and return values ​​must also be adapted in the C code. For this purpose, there are special data types in the JNI, which enable parameters to be transferred from Java to C and back using so-called Typcast s 6. Finally, the C file must be compiled in such a way that file is generated, with the help of which JNI can use the desired functions. It has to be so for the execution. File (in the Microsoft world this corresponds to a dll file) of the Java Virtual Machine (JVM) are available Java Cryptography Architecture / Extension (JCA / JCE) Since it should be possible to use the provider to be implemented in this thesis with any Java applications , it is necessary to use a defined interface. JCA and JCE prescribe how such a provider is to be implemented. It is possible to specify several providers to the system in order to be able to use several services. With the J2SDK1.4.1, some providers from SUN are supplied, which can be used without special configuration. 6 data types from Java are converted into data types from C and vice versa. Jan Keller Carla Schaffner

38 Solution Concepts 6. Solution Concepts 6.1. Overview Text 1024 Bit RSA Signature X.509 Certificate Application JNI Text (String) 128 Bit MD5 Hash 160 Bit SHA1 Hash Hash (String) Class Signature (byte []) SHA1WithRSAEncryption MD5WithRSAEncryption Signature (char) readcertificate Class SignatureWithRSA Certificate (DER) Certificate Object Java Method Method signhash getcert (slot) C PKCS # 11 Hash (char []) Signature (char []) Certificate (DER) * SD HW * 1 to n if several are available Figure 14: Overview Jan Keller Carla Schaffner

39 Solution concepts Application: Java application that uses the provider. The Signature and CertificateFactory services are offered. Java Various APIs are used at the Java level. On the one hand JCE, which guarantees that the provider can be used as prescribed. On the other hand, JNI is used to create the interface which makes the functions of the PKCS # 11 API written in C usable for Java. C The program parts in C are the interface between Java and the card. The functions of the Cryptoki API are used to access the card, as well as normal C functions that prepare the information for Java. HW Any ISO compatible smart card that is addressed via a PC / SC compatible reader. Solution variants Due to the fixed task and the specification of the APIs to be used, there were no really different solution variants. Apart from the case that an API did not fully meet the requirements, as described in Section 9.3 using the example of the CertificateFactory service. Therefore, possible variants are not discussed here. Jan Keller Carla Schaffner

40 Solution Concepts 6.3. PC / SC Implementation The implementation of PC / SC in the present work looks like this: Application KelschaJLin Service Provider PKCS # 11 Cryptoki Service Provider pcscd ICC Resource Manager slbreflex72v2 IFD Handler RS-232 Reflex 72 IFD Cryptoflex Figure 15: Implementation PC / SC Jan Basement Carla Schaffner

41 Solution Concepts 6.4. State diagram of the smart card Start End Figure 16: Smart card state diagram When using the smart card, various states have to be passed through so that the certificates can be read or the signature can be made. 1. First the reader is contacted. 2. If this was successful, a session can be opened on a specific slot. 3. Once the session has been opened, the object stored in this slot can be read if it is not secured by a pin. 4. If the object is secured by a pin, a login is required first. 5. After a correct login, the protected objects can also be used. However, it is never possible to read the private key from the card. 6. If a login has been carried out, it must be logged out again. 7. The session can then be closed. 8. At the end the connection is cleared down again. Jan Keller Carla Schaffner

42 Solution Concepts 6.5. PKCS # 11 API The following table provides a brief description of the most important Cryptoki functions used, which are contained in the header file pkcs11.h. To use it, the shared object file libopensc must be linked when the file SCConnection.c is compiled. Further information can be found in the RSA PKCS # 11 document. All functions return a constant CK_RV, which provides information about the success of the function. Since this constant is not a very meaningful number, it is converted into a user-friendly string using the CKK2Str () method. The possible values ​​of CK_RV can be found in Appendix B. CR_RV C_Initialize (pinitargs) C_Login (hsession usertype ppin ulpinlen) C_FindObjectsInit (hsession ptemplate ulcount) C_FindObjects (hsession phobject ulmaxobjectcount pulobjectcount) C_FindObjectsFinalizes the connection to the reader slot (hsession) and establishes the connection to the slot CryptObjectsFinal (hsessionSession). With Multi Threaded, pinitargs shows access to a parameter structure. Logs into a token. hsession is the desired session. usertype is the user type ppin points to the user PIN ulpinlen Contains the length of the PIN Prepares the search for tokens or session objects. hsession is the desired session. ptemplate points to a search pattern. ulcount contains the number of search patterns. To find all objects, ulcount has to be set to 0. Searches for objects. hsession is the desired session. phobject gets the array of objects. ulmaxobjectcount: maximum number of search results pulobjectcount points to the number of search results. Ends the search. hsession is the session in question. Opens a session on a specific slot. slotid is the ID of the slot flags define the session type papplication is an application-specific pointer Notify is the address of the callback function phsession receives the session handler Jan Keller Carla Schaffner

43 Solution Concepts C_GetSlotList (tokenpresent pslotlist pulcount) C_GetSlotInfo (slotid pinfo) C_GetAttributeValue (hsession hobject ptemplate ulcount) C_SignInit (hsession pmechanism hkey) C_Sign (helltession_cession_session_Celenism) (preservedSession) (C_Session) (preservedSession) C_Session (cession) (preservedSession_Celenism) (preservedSession_Celenism) (preservedSession) C_Session (C_Session_Cession_Cession_Cession in the system together. tokenpresent determines whether all slots or only the empty ones should be displayed. pslotlist points to the buffer that will receive the slot list. pulcount contains the number of slots. Collects information about a specific slot. slotid is the ID of the slot. pinfo points to the memory area that receives the information. Reads the attributes of an object. hsession is the desired session. hobject is the desired object. ptemplate is an array that contains the attributes to be read and receives the information. ulcount contains the number of attributes. Initializes a signature operation. hsession is the current session. pmechanism points to the signature mechanism. hkey is the key to use. Executes the signature. hsession is the desired session pdata is the data to be signed uldatalen is the length of the data psignature points to the area that receives the signature. pulsignaturelen is the length of the signature. Logs out of the desired session. hsession is the desired session. Closes the specified session. hsession is the desired session. Terminates the connection between the application and the Cryptoki library. preserved is reserved for future use and should be NULL. Jan Keller Carla Schaffner

44 Solution Concepts 6.6. C_Sign / pmechanism The function C_Sign, or more precisely C_SignInit (see chapter 6.5), must be given the parameter pmechanism, which tells it how to handle the pdata data. The following constants are available for the RSA signature: CKM_RSA_PKCS CKM_RSA_PKCS_OAEP CKM_RSA_PKCS_PSS CKM_RSA_X_509 CKM_MD5_RSA_PKCS CKM_SHA1_RSA_CSD sign. It doesn't care about the form of pdata. CKM_RSA_PKCS_OAEP Applies RSA OAEP (see chapter 4.6.2) and signs pdata. If CKM_RSA_PKCS_OAEP is used with OpenSC, the program terminates with the error CKR_MECHANISM_INVALID. CKM_RSA_PKCS_PSS Uses RSA PSS (see chapter 4.6.3) and signs pdata. If CKM_RSA_PKCS_OAEP is used with OpenSC, the program terminates with the error CKR_MECHANISM_INVALID. CKM_RSA_X509 Carries out a raw RSA signature operation according to X.509, but without padding. CKM_MD5_RSA_PKCS Generates an MD5 hash from pdata, padded according to PKCS # 1 v1.5 and then signs it. CKM_SHA1_RSA_PKCS Generates a SHA 1 hash from pdata, padded according to PKCS # 1 v1.5 and then signs it. Jan Keller Carla Schaffner

45 Solution Concepts CKM_SHA1_RSA_PKCS_PSS Generates a SHA 1 hash from pdata, padded according to RSA PSS (see chapter 4.6.3) and then signs it. In order to have to transfer as little data as possible between Java and C, the provider KelschaJLin generates the hash in Java. That means Java receives a text as input, generates the hash and forwards it to C. Therefore, in this case, the C_SignInit function uses the CKM_RSA_PKCS Digest Info mechanism in OpenSC. Roughly speaking, the C_Sign function is called with the pmechanism and pdata arguments for the signature of a hash value. pmechanism points to a mechanism described in Section 6.6, which defines the handling of the data, and pdata points to the data to be signed. As already mentioned, KelschaJLin uses the neutral mechanism CKM_RSA_PKCS. If a 160-bit long SHA 1 hash is transferred to C_Sign, a signature is returned which, after verification, contains digest information in addition to the original hash, although C_Sign was never told what type of hash the input pdata was . When asked about this phenomenon, we got the following answer from the OpenSC Developer mailing list: Hi, this is a ʹfeatureʹ of the opensc pkcs11 lib, that once appeared needed for Mozilla / Netscape. However, current versions of Mozilla / Netscape don't have this bug anymore, AFAIK, so I guess we should update to the correct way as well. (In fact, we allready agreed to change this, but it wasnʹt done yet out of fear for breaking something). For now, you could try to remove the lines with a in pkcs11 / framework pkcs15.c and rebuild. break; case 36: flags = SC_ALGORITHM_RSA_HASH_MD5_SHA1; / * SSL hash * / break; case 20: flags = SC_ALGORITHM_RSA_HASH_SHA1; / * SHA1 * / break; case 16: flags = SC_ALGORITHM_RSA_HASH_MD5; / * MD5 * / Jan Keller Carla Schaffner

46 solution concepts break; default: flags = SC_ALGORITHM_RSA_HASH_NONE; If that works for your card, I'll try to make a decent patch shortly. As can be seen from the source code, C_Sign determines which type of hash it is based on the length of the hash value transferred. SHA 1 for 20 bytes, MD5 for 16 bytes. Should problems arise (for example, if an MD2 hash is to be signed, which is known to have the same length as MD5) or if the digest info should not be included in the signature at all, the lines described above can be commented out Macros in C Using the method C_GetAttributeValue provides PKCS # 11 with a method with which various information about objects can be determined. KelschaJLin also uses this method to access information such as KEY_TYPE, MODULUS_BITS, LABEL, ID and many more. In order not to have to write a separate function for each piece of information, macros have been defined. In simple terms, macros define a text under a name. The precompiler then replaces the name with the text in the code. That means with the definition #define WRITE (format, text) printf (% #format \ n, text) every call in the code is WRITE (s, hello); through printf (% s \ n, hello); replaced. This macro doesn't make a lot of sense. The macros in KelschaJLin save a lot of paperwork: Jan Keller Carla Schaffner

47 Solution Concepts #define ATTR_METHOD (ATTR, TYPE) TYPE \ get ## attr (ck_session_handle sess, CK_OBJECT_HANDLE obj) \ {\ TYPE type; \ CK_ATTRIBUTE attr = {CKA _ ## ATTR, & type, sizeof (type)}; \ CK_RV rv; \ \ rv = C_GetAttributeValue (sess, obj, & attr, 1); \ if (rv! = CKR_OK) \ printf ("c_getattributevalue (" #ATTR ")% s \ n", CKR2Str (rv)); \ return type; \} A macro call is written for each required function: ATTR_METHOD (CLASS, CK_OBJECT_CLASS); When compiling, the precompiler then replaces each call with the macro definition as follows: CK_OBJECT_CLASS getclass (ck_session_handle sess, \ CK_OBJECT_HANDLE obj) {CK_OBJECT_CLASS type; CK_ATTRIBUTE attr = {CKA_CLASS, & type, sizeof (type)}; CK_RV rv; } rv = C_GetAttributeValue (sess, obj, & attr, 1); if (rv! = CKR_OK) printf ("c_getattributevalue (" CLASS ")% s \ n", CKR2Str (rv)); return type; This means that once the macro has been defined, it is possible to create an 8-line function with one line of code. The function can then normally through CK_OBJECT_CLASS getclass (ck_session_handle, ck_object_handle); CK_OBJECT_CLASS cls = getclass (session, obj); be called. Jan Keller Carla Schaffner

48 Solution Concepts 6.9. Implementation of the Java Native Interface 1. As already mentioned, functions written in C should be made visible in a Java class. The JNI is used for this. In the interface class, these C functions must be defined as public native static as shown below. package ch.zhwin.da03.kelscha.provider; public class JNIForJLinProvider {public native static String connect (); public native static String login (string pin); public native static String logout (); public native static String listobjects (); public native static String opensession (int slotnr); public native static String getslots (); public native static String signhash (string hash); public native static String disconnect (); public native static String getcert (); public native static int getnumberofslots (); public native static boolean getfatal (); public native static void setfatal (boolean fatal); } static {System.loadLibrary ("SCConnection"); } The command System.loadLibrary (SCConnection); loads the library into the Java class. The contains all C functions. 2. A header file must now be generated from this Java class, which is then integrated in the C file. The javah command is available for this purpose. In order to execute the command correctly, it is necessary to change to the directory in which the JNIForJ-LinProvider.class file is located. (If the class belongs to a package, this must of course be taken into account and specified when calling it). javah JNIForJLinProvider (without package) javah ch.zhwin.da03.kelscha.provider. JNIForJLinProvider (with package) This header file must now be copied into the directory in which the associated C file is located. Jan Keller Carla Schaffner

49 Solution Concepts 3. The header file just generated should look something like this. It should be noted here that with the correct header file, a function header was created for each method defined in the interface. For reasons of clarity, only one function header is shown here. / * DO NOT EDIT THIS FILE - it is machine generated * / #include / * Header for class ch_zhwin_da03_kelscha_provider_jniforjlinprovider * / #ifndef #define _Included_ch_zhwin_da03_kelscha_provider_JNIForJLinProvider _Included_ch_zhwin_da03_kelscha_provider_JNIForJLinProvider #ifdef cplusplus extern "C" {#endif / * * Class: ch_zhwin_da03_kelscha_provider_jniforjlinprovider * Method: connect * Signature: () Ljava / lang / String; * / JNIEXPORT jstring JNICALL Java_ch_zhwin_da03_kelscha_provider_JNIForJLinProvider_connect (JNIEnv *, jclass); #ifdef cplusplus} #endif #endif 4. The C functions must now be implemented with the function heads created so that JNI can find these functions. #include ch_zhwin_da03_kelscha_provider_jniforjlinprovider.h #include #include #include #include JNIEXPORT jstring JNICALL Java_chrovider_connect, JNIEXPORT jstring JNICALL java_chrovider_win (jNIEXPORT jstring JNICALL_chrovider_win (env_nrovider_win) (env_nrovider_win (jNICALL) output,""); rv = C_Initialize (NULL); if (rv == CKR_OK) {sprintf (output, "Connection established \ n"); } else {sprintf (output, "c_initialize failed:% s \ n", ckr2str (rv)); Jan Keller Carla Schaffner

50 solution concepts} fatal = TRUE; } jstring retstr = NULL; retstr = (* env) -> newstringutf (env, output); return retstr; To cast the parameters and return values ​​from C to Java 7, predefined methods can be used. An example is: 8 retstr = (* env) -> newstringutf (env, output); 5. The C file can now be compiled and linked with the following calls: gcc c fpic I / usr / lib / sunjava / include / I / usr / lib / sunjava / include / linux / SCConnection.c With the creation of the SCConnection file .o a .so file is generated which is loaded by the Java class. If further files are to be linked, this must be indicated with flags as follows: L / and l . A possible call is shown here: gcc shared L / user / local / lib / pkcs11 lpkcs11 lopensc-pkcs11 o SCConnection.o The Java Native Interface automatically searches for a * .so file with the prefix lib on UNIX systems. Therefore this does not have to be specified when calling in the SCConnection class (as shown above). In order to show the Java Virtual Machine where the generated, dynamically loadable library is located, either the environment variable LD_LIBRARY_PATH must be set correctly, or the file must be set to the correct location, namely to / usr / lib / sunjava / jre / lib / i386 copied. All paths are for Linux SUSE 8.2. The path names can differ for every other distribution. 7 Converting data types 8 Further information can be found in the book core JAVA 2. Jan Keller Carla Schaffner

51 Solution concepts Implementation of the provider 1. In order to implement a cryptographic service provider in accordance with JCE, the main class must be derived from the class. public final class KelschaJLinProvider extends Provider {In the constructor you can now call super (provider_name, version, info); the name under which the provider can be reached can be set. The version and some information about the provider can also be specified here. Afterwards, a property specification with key and value must be given for all services. put ("signature.sha1withrsaencryption", "ch.zhwin.da03.kelscha.provider.signaturewithrsa $ sha1withrsaencr yption"); This means that when the SHA1WithRSAEncryption algorithm is called with the JLin provider, the class ch.zhwin.da03.kelscha.provider.signaturewithras $ sha1withrsaencry ption is used. Signature s = Signature.getInstance (SHA1WithRSAEncription, JLin); Aliases can also be defined for each service. put ("alg.alias.signature.sha1withrsa", "SHA1WithRSAEncryption"); 2. The individual service classes at the KelschaJLin provider, the SignatureWithRSA and CertificateFactoryX509 classes, must be derived from special classes ( Spi) and their abstract methods must be implemented. public class SignatureWithRSA extends SignatureSpi {public class CertificateFactoryX509 extends CertificateFactorySpi {Which methods have been implemented is described in the chapter. Jan Keller Carla Schaffner

52 Solution concepts Communication of the components The following is an overview of the communication between the components using the example of a signature. In order not to overload the graphic, only commands that have to do with the signature are listed. The preceding or following have been omitted. The objects are listed on the left-hand side and, next to the arrows, the functions that are called or the information exchanged. As can be seen in Figure 17, the application that uses the KelschaJLin provider and instantiated a signature object calls the sign () method. This method in turn calls the enginsign () method. By instantiating the object, the object knows which method has to be called by which class. This implementation enables a plug and play provider to be used. The interface to the application remains the same, only a different provider makes the functions available. More on using the provider can be found in Chapter 10. Jan Keller Carla Schaffner

53 Solution Concepts Application KelschaJLinProvider signature.sign () enginesign () Provider (Java) JNIForJLinProvider.signHash () Provider (C) C_SignInit () C_Sign () opensc APDU s as string pcscd APDU CLA INS P1 P2 P3 binary APDU s RSA Signature C Data Get Response C0 C Length Driver APDUs as electrical signals card Figure 17: Communication of the components Jan Keller Carla Schaffner

54 Solution Concepts Class Diagrams Figure 18: KelschaJLinProvider class Figure 19: CertificateFactoryX509 class Figure 20: SignatureWithRSA class Jan Keller Carla Schaffner

55 Solution Concepts Figure 21: Class Util Figure 22: Class JNIForJLinProvider Sequence Diagrams Figure 23: Sequence Diagram Service CertificateFactory Jan Keller Carla Schaffner

56 Solution concepts Figure 24: Sequence diagram Service Signature Jan Keller Carla Schaffner

57 Components used 7. Components used 7.1. Hardware Cryptoflex 8k In the present work the Cryptoflex 8k Smartcard from Schlumberger was used. This is a microprocessor card with the following properties: Cryptographic functions: RSA signature / authentication with 512, 768 or 1024 bit RSA private key encryption / decryption 512, 768 or 1024 bit RSA key generation SHA1 and MD5 hashing DES and Triple DES encryption / decryption (EBC & CBC) Hardware: 7960 Bytes EEPROM bits / s Transfer rate Supported platforms: PC / SC PKCS # 11 Windows 2000 / XP Reflex 72 V2 RS232 Reader The Reflex 72 Reader is a peripheral device that communicates with the computer via the serial interface. The reader draws its power from the PS / 2 interface and is plugged into the keyboard port via a Y plug together with the keyboard. The reader also has a slot for the chip card. Technical specifications: 8 sliding contacts, designed for 100,000 insertions Supply: 5V from PS / 2 port Transfer rate to PC: 56,700 bps Transfer rate to card: 9600 to 115,200 bps API: PC / SC Jan Keller Carla Schaffner

58 Components used 7.2. Software Java classes All classes described below are self-developed. Often an existing interface was implemented or derived from an existing Java class. Class for the provider interface KelschaJLinProvider.class This class represents the actual provider. The possible services are specified here. The provider offers the Services Signature for MD5 and SHA1 hash values ​​and CertificateFactory to read all X509 certificates from the smart card. Methods public KelschaJLinProvider () Description Constructor for the provider. All services are specified here by means of algorithm names and the associated class. Classes for the Signature SignatureWithRSA.class service This class is responsible for the implementation of the signature. It is derived from the SignatureSpi and overrides the abstract methods of the super class. Methods public SignatureS- HA1WithRSA (String) protected void engineinitverify (publickey) protected void engineinit- Sign (PrivateKey) Description Constructor of the SignatureWithRSA class that implements the service for the signature. The algorithm is passed when the parameters are passed. This method can be used to set the public key for verifying the signature. This method could be used to set the private key for signing. If the signing is to be done with the KelschaJLin provider and a smart card, only zero can be specified when passing the parameters, as the private key must always be on the smart card. Jan Keller Carla Schaffner

59 Components used protected void engineupdate (byte) protected void engineupdate (byte []) protected void engineupdate (byte, int, int) protected byte [] enginesign () protected boolean engineverify (byte []) protected void enginesetparameter (AlgorithmParameterSpec) private byte [] callcfunctions (String, int, int) Method to set or update the data to be signed. The transferred byte is appended. Here plain text 9 can be supplemented with a byte []. This method can be used to supplement the data. The byte [] is inserted at the specified offset. The third parameter denotes the length of the byte []. When this method is called, the actual signing process is carried out. The return value contains the signature in the form of a byte [] s. A signature can be verified here. This method is used to set some parameters for the signature engine, if necessary (e.g. slot, pin) Private method that takes over communication with the smart card. The desired C functions are called using the JNI interface. This method returns a byte [] with the signature. If for whatever reason a signature could not be created, an empty byte [] is returned. Since an algorithm must be set for the signature, a separate class is written for each of the different algorithms. These classes are all derived from the SignatureWithRSA superclass so that all common methods can be inherited. So only the name of the algorithm has to be set for the constructor. The following two classes are such algorithm classes and contain only one constructor that calls the method super (algname) with the respective algorithm. SHA1WithRSAEncryption.class Methods Description public SHA1WithRASEncryption () Constructor of the class SHA1WithRSAEncryption. 9 Unencrypted data. Also known as plain text. Jan Keller Carla Schaffner

60 Components used MD5WithRSAEncryption.class Methods public MD5WithRASEncryption () Description Constructor of the MD5WithRSAEncryption class. SignatureParameterSpec.class This class was implemented to set some parameters for the signature. It implements the AlgorithmParameterSpec interface. Methods public SignatureParameterSpec (int, int) public int getpin () public int getslot () Description Two int values ​​must be passed to instantiate a SignatureParameterSpec object. These are necessary for the transfer of the slot and the pin of the private key. Returns the pin for the private key. This method returns the slot in which the private key is located. Classes for the CertificateFactory service CertificateFactoryX509.class This class implements the service of a CertificateFactory. It is derived from the CertificateFactorySpi class and implements all of the abstract methods of this superclass. Methods public CertificateFactoryX509 () public Certificate enginegeneratecertificate (InputStream) public Collection enginegeneratecertificates (InputStream) public CRL enginegeneratecertificate (InputStream) public Collection enginegeneratecrls (InputStream) Description Constructor for the class CertificateFactoryX509. This method is not supported by the KelschaJLin provider. Explanation see chapter 9.3. Method to read all certificates from the smart card and to generate a certificate object. Uses the CertificateReader auxiliary class. This method is also not implemented and throws an exception when called. This method is also not supported by the JLin provider. Jan Keller Carla Schaffner

61 Components used CertificateReader.class This class is a class of its own and is not derived from a JCE service provider interface. The CertificateReader class actually generates the certificates after they have been read from the smart card. Methods public CertificateReader () public CertificateReader (int) public Vector getcerts () private Certificate makex509cert (string) private boolean readcertfromsmartcard (int) Description Constructor for the CertificateReader class. If no argument is passed, all slots on the smart card are searched for certificates. If an int is passed when the CertificateReader class is instantiated, only the certificate is read from the specified slot (if one exists). This method returns a vector with all certificates. If there is no certificate in this slot, an exception is thrown. Method to generate a certificate object from the received hex stream, which was saved in a ByteArrayInutStream. A service from another provider supplied by JDK is used for this purpose. When this method is called, a connection to the smart card is opened and the certificate for the specified slot is read and written to a ByteArrayInutStream. Jan Keller Carla Schaffner

62 Components used Class for utilities that use both services Util.class This class provides some methods that are required by several classes. Methods public static String stringto- Hex (String) public static byte [] hex- StringToByteArray (String) public static void check- String (String) Description Converts an ASCII string into a string with its hex value. Converts a hex string into an ASCII string and returns it in a byte []. Tests a string whether it is an error output from C code. If so, this is output on the command line. C The C components establish the connection between the Java provider and the hardware-related Cryptoki API. All methods return a char string which is processed by Java.SCConnection.c methods JNIEXPORT jstring JNICALL Java_ch_zhwin_da03_kelscha_pro vider_jniforjlinprovider_conne ct (JNIEnv * env, jclass cl) JNIEXPORT jstring JNICALL Java_ch_zhwin_da03_kelscha_provi der_jniforjlinprovider_openses sion (JNIEnv * env, jclass cl, JINT SlotNr) JNIEXPORT jstring JNICALL Java_ch_zhwin_da03_kelscha_provi der_jniforjlinprovider_login (JNIEnv * env, jclass cl, jstring pin_input ) JNIEXPORT jstring JNICALL Java_ch_zhwin_da03_kelscha_provi der_jniforjlinprovider_listobj ects (JNIEnv * env, jclass cl) Description Initializes a connection to the ICC. If this fails, the reader cannot be addressed. Opens a session to the token in slot number slotno. Authenticates to the card of the current session. This makes the PIN protected objects visible. Returns all objects (keys, certificates) of the current session. The private key will not be returned without prior login. Jan Keller Carla Schaffner

63 Returns the number of slots in the current session. Returns all certificates of the current session in DER format. Signs the digest hash [] (hex) with the private key of the current session and returns the signature as a hex value. Returns the variable fatal. In the event of a fatal error, this is TRUE and the program should be stopped. Set fatal to TRUE or FALSE depending on the call. Logout of the current session. Terminates the connection to the smart card. Jan Keller Carla Schaffner