Copyright Institute for Applied Information Processing and Communications, Graz University of Technology

Size: px
Start display at page:

Download "Copyright Institute for Applied Information Processing and Communications, Graz University of Technology"

Transcription

1 Today, the Internet yet has intruded nearly into all domains of the human society. Regardless of only sitting at home on the PC and surfing the World Wide Web, taking some business transaction or visiting an electronic shop, everyone who has access to some provider may use the various possibilities offered by the Internet. The great amount of personal data transfered over the Internet every day claims for particular security mechanism making it difficult for some non-authorized eavesdropper to access and manipulate the data. The standard protocols used by the Internet itself offer a highly insufficient protection against any data attack to be expected. One of the meanwhile leading protocols for providing a secure data transfer over the Internet has been developed by the Netscape Communications Corporation when introducing their Secure Sockets Layer (SSL) protocol for supporting peer authentication, data encryption and data integrity. This paper introduces isasilk, which implements the currently actual third Version of the Secure Sockets Layer protocol - SSLv3. isasilk is written in Java programming language and has been developed at the Institute for Applied Information Processing and Communications of the University of Technology in Graz, Austria. The paper is divided into three main parts. The first part gives a short overview of the Secure Sockets Layer protocol concentrating on the cipher suite concept used for negotiating security settings throughout an initial client- server handshake dialogue. The second part is a glossary summarizing the most usual terms that may arise within the isasilk SSLv3 environment. Thethird part actually introduces the main features of isasilk.. Copyright Institute for Applied Information Processing and Communications, Graz University of Technology

2 SSL Overview Introduction Today, the Internet yet has intruded nearly into all domains of the human society. Regardless of only sitting at home on the PC and surfing the World Wide Web, taking some business transaction or visiting an electronic shop, everyone who has access to some provider may use the various possibilities offered by the Internet. The great amount of personal data transfered over the Internet every day claims for particular security mechanism making it difficult for some non-authorized eavesdropper to access and manipulate the data. The standard protocols used by the Internet itself offer a highly insufficient protection against any data attack to be expected. One of the meanwhile leading protocols for providing a secure data transfer over the Internet has been developed by the Netscape Communications Corporation when introducing their Secure Sockets Layer (SSL) protocol for supporting peer authentication, data encryption and data integrity. This paper introduces isasilk, which implements the currently actual third Version of the Secure Sockets Layer protocol - SSLv3. isasilk is written in Java programming language and has been developed at the Institute for Applied Information Processing and Communications of the University of Technology in Graz, Austria. The paper is divided into three main parts. The first part gives a short overview of the Secure Sockets Layer protocol concentrating on the cipher suite concept used for negotiating security settings throughout an initial client- server handshake dialogue. The second part is a glossary summarizing the most usual terms that may arise within the isasilk SSLv3 environment. The third part actually introduces the main features of the isasilk SSLv3 implementation. Based on many program code examples, guidelines are presented for helping the user to realize her/his own SSLClient/SSLServer implementation. Spelling Conventions Normal text is written in Times New Roman, and program code examples are presented using Courier New. Classes, variables and methods declarations inherent to the isasilk IAIK-SSL package may be recognized by the Arial font. Screen Outputs also are shown using the Arial font. 2

3 SSL Overview Table Of Contents 1 SSL - AN OVERVIEW THE INITIAL HANDSHAKE PROCEDURE CIPHER SUITES GLOSSARY INTRODUCTION TO ISASILK SSLCLIENT: FROM SOCKET TO SSLSOCKET SSLSERVER: FROM SERVERSOCKET TO SSLSERVERSOCKET BASIC REQUIREMENTS PROVIDER HANDLING CERTIFICATES, KEYS AND PARAMETERS SSL SOCKET AND SSL CONTEXT CLASSES THE SSLCONTEXT CLASS The SSLClientContext Class Random Number Generator Enabled Cipher Suites Enabled Compression Methods The Session Manager public class SessionID public class Session public interface SessionManager public class DefaultSessionManager implements SessionManager The Trust Decider public interface TrustDecider public interface ServerTrustDecider extends TrustDecider public interface ClientTrustDecider extends TrustDecider Trust Deciding: What the SSLServer has to do Trust Deciding: What the SSLClient has to do Client Authentication: What the SSLServer has to do Client Authentication: What the SSLClient has to do SSLClientContext: Summary The SSLServerContext Class THE SSLSOCKET CLASS Connecting via a Proxy Obtaining the peer s certificate Security Parameter Renegotiation THE SSLSERVERSOCKET CLASS EXAMPLE: SSLCLIENT AND SSLSERVER A SSLCLIENT IMPLEMENTATION EXAMPLE A SSLSERVER IMPLEMENTATION EXAMPLE REFERENCES

4 SSL Overview 1 SSL - An Overview SSL is an abbreviation for Secure Sockets Layer and constitutes an application independent handshake protocol developed by the Netscape Communications Corporation for providing a secure data transfer over the Internet. Thereby, the connection security is marked by three basic properties ([SSL]): The connection is private. Encryption is used after an initial handshake to define a secret key. Data encryption is done by symmetric cryptography (e.g., DES, RC4, etc.). The peer s identity can be authenticated using asymmetric, or public key cryptography (e.g., RSA, DSS, etc.). The connection is reliable. Message transport includes a message integrity check based on a MAC. Secure hash functions (e.g. SHA, MD5) are used for MAC computations. SSL operates at the Socket interface used for TCP, additionally supplied with peer authentication and data encryption. So any higher level application protocol like HTTP, FTP, Telnet,... may be protected by a secure transmission channel. Using HTTP, a SSL connection can be recognized by means of the URL-type https (Port 443). Currently SSL (Version 3.0) is the most important protocol for encrypted data transfer over the WWW. It is supported not only by all the well known browsers like Netscape Navigator (as standard), Microsoft Internet Explorer or SSLMosaic but also by many servers like Netscape Server, Apache or NCSA. The following section gives a more general view about the SSL Handshake protocol. For a detailed description see [SSL]. 1.1 The Initial Handshake Procedure Before starting the actual data transfer, client and server perform a handshake protocol phase authenticating each other (optional) and exchanging a session key. Purpose of this handshake phase is the negotiation of cryptographic parameters, serving as a security basis for the following data transfer. The handshake procedure is initiated by the client that sends a compression methods and cipher suites list to the server containing the compression respectively cryptographic algorithms supported by the client. These algorithms are offered the server in the client s 4

5 SSL Initial Handshake preference order, meaning that the entries at the top of the particular list are favoured by the client. Now the server has to select one of the presented compression methods and cipher suites to define the compression policy as well as the key exchange, symmetric encryption and hash algorithms for the current session. If the server doesn t support any of the client s cipher suites, a handshake failure alert is triggered and the connection is closed. Otherwise the server authenticates itself by sending its certificate according to the selected cipher suite s key exchange algorithm. Generally, the certificate message will consist of a chain of X.509 certificates, starting with the server certificate and leading to the certificate of the signing root certification authority. The information derived from the certificate is used to create and exchange a shared secret (master key) between client and server. Based on this master key and some session dependent data, both client and server, generate two session keys - one of them for each data transfer direction. After all, the handshake phase is concluded by the client s and server s Finished messages, both already encrypted using the negotiated cryptographic algorithms and keys. If client and server successfully have verified the correctness of the received communication partner s finished message, they can enter the protected data transfer phase. Note that Client authentication is optional and only necessary if explicitly requested by the server. In this case, the server specifies the expected certificate type and the certification authorities it is willing to accept. If the client is not able to comply with the particular requirements, the server may close the connection, or it may continue the handshake thereby tolerating the anonymity of the client. Also it is possible to go into a completely anonymous session, meaning that neither server nor client authenticate themselves. However, such a communication would be highly vulnerable against man-in-the-middle attacks. The cryptographic parameters negotiated during some previous session may also be used for protecting the data transfer of the current session, making it superfluous to perform the whole handshake dialogue again. There is no real necessity for the user of the isasilk SSL implementation to have knowledge about all the concerning details - mainly it would be advantageously to be somewhat familiar with the cipher suite concept for negotiating the cryptographic algorithms of the current session. For that reason the following section tries to provide some basic understanding for the structure and using of cipher suites. 5

6 SSL Cipher Suites Cipher Suites A cipher suite defines the public key (asymmetric) algorithm used for peer authentication and key exchange (e.g., RSA, DSA) the symmetric algorithm for data encryption (e.g., DES, RC4,...) the secure hash function (e.g., SHA, MD5) for MAC computation Client and server must agree on a specific cipher suite for determining the cryptographic algorithms of the current session. At the beginning of the handshake dialogue the only active cipher suite is labeled as SSL_NULL_WITH_NULL_NULL, indicating the initial absence of any cryptographic specification. The terminology for describing a cipher suite can be introduced as: SSL_KeyExchangeAlgorithm_WITH_SymmetricEncryptionAlgorithm_HashAlgorithm Thus, cipher suite SSL_NULL_WITH_NULL_NULL states NULL key exchange, NULL symmetric encryption and NULL hash algorithm - hence initially none encryption is performed. The following table lists all the cipher suites supported by SSLv3 and denotes the corresponding key exchange, symmetric encryption and hash algorithms. Cipher suites that are marked with an asterisk (*) indicate an exportable method that falls under the restrictions of the current US export law. Except for Fortezza all the listed cipher suites are implemented by isasilk. Cipher Suite Name Key Exchange Algorithm Symmetric Encryption Algorithm Hash Algorithm SSL_NULL_WITH_NULL_NULL* NULL NULL NULL SSL_RSA_WITH_NULL_MD5* RSA NULL MD5 SSL_RSA_WITH_NULL_SHA* RSA NULL SHA SSL_RSA_EXPORT_WITH_RC4_40_MD5* RSA_EXPORT RC4_40 MD5 SSL_RSA_WITH_RC4_128_MD5 RSA RC4_128 MD5 SSL_RSA_WITH_RC4_128_SHA RSA RC4_128 SHA SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5* RSA_EXPORT RC2_CBC_40 MD5 SSL_RSA_WITH_IDEA_CBC_SHA RSA IDEA_CBC SHA SSL_RSA_EXPORT_WITH_DES40_CBC_SHA* RSA_EXPORT DES40_CBC SHA SSL_RSA_WITH_DES_CBC_SHA RSA DES_CBC SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA RSA 3DES_EDE_CBC SHA SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA* DH_DSS_EXPORT DES40_CBC SHA SSL_DH_DSS_WITH_DES_CBC_SHA DH_DSS DES_CBC SHA 6

7 SSL Cipher Suites SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA DH_DSS 3DES_EDE_CBC SHA SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA* DH_RSA_EXPORT DES40_CBC SHA SSL_DH_RSA_WITH_DES_CBC_SHA DH_RSA DES_CBC SHA SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA DH_RSA 3DES_EDE_CBC SHA SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA* DHE_DSS_EXPORT DES40_CBC SHA SSL_DHE_DSS_WITH_DES_CBC_SHA DHE_DSS DES_CBC SHA SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA DHE_DSS 3DES_EDE_CBC SHA SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA* DHE_RSA_EXPORT DES40_CBC SHA SSL_DHE_RSA_WITH_DES_CBC_SHA DHE_RSA DES_CBC SHA SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA DHE_RSA 3DES_EDE_CBC SHA SSL_DH_anon_EXPORT_WITH_RC4_40_MD5* DH_anon_EXPORT RC4_40 MD5 SSL_DH_anon_WITH_RC4_128_MD5 DH_anon RC4_128 MD5 SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA* DH_anon_EXPORT DES40_CBC SHA SSL_DH_anon_WITH_DES_CBC_SHA DH_anon DES_CBC SHA SSL_DH_anon_WITH_3DES_EDE_CBC_SHA DH_anon 3DES_EDE_CBC SHA SSL_FORTEZZA_DMS_WITH_NULL_SHA FORTEZZA_DMS NULL SHA SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA FORTEZZA_DMS FORTEZZA_CBC SHA *... exportable cipher suite Table 1.1: SSL Cipher Suite Algorithms The cipher suite negotiation process already has been discussed: the client offers a list of supported cipher suites in preference order. The server answers by selecting one of the presented cipher suites or generating a handshake failure alert. If the cipher suite negotiation has been successfully completed, usually the server authenticates itself by sending a X.509 certificate. The certificate message includes the server s public key that has to be appropriate for the key exchange algorithm of the cipher suite agreed upon. If the cipher suite defines a RSA certificate, the client gets the server s RSA public key for encrypting a premaster secret and sending it to the server. Following this, the server decrypts the received premaster secret with his RSA private key and both, client and server, hold the same shared secret, serving as starting point for computing the session keys which later are used for encrypting the data to be transfered. If the server sends a Diffie Hellman certificate, the client uses the server s Diffie Hellman public key and parameters (prime modulus and generator) to calculate the premaster secret. Furthermore the client generates his own public Diffie Hellman key and sends it to the server that now is able to calculate the same premaster secret from it s own private and the client s public key. For more information on Diffie Hellman key exchange see [SSL] and [Schneier]. If the server has no certificate, or the server certificate cannot be used for key exchanging, an extra server key exchange message has to be transmitted. The server certificate may be unsuitable for key exchanging for the following reasons: 7

8 SSL Cipher Suites The certificate is a sign-only certificate (e.g. DSA or sign-only RSA). Since, for instance, the DSA algorithm only can be used for signing, it is necessary to send the key within a separate message: the public DSA key is included in the certificate, and the following key exchange message transmits the, for instance, public DH key, signed by the server s private DSA key. The actual cipher suite falls under the US law export regulations forbidding RSA keys used for encryption to be longer than 512 Bits. However, there are no limits concerning the length of RSA keys that are used for signing only. So the server may send a temporary public RSA encryption key of a length less than (or equal) 512 Bits within a separate key exchange message, and signs this temporary key with the private key matching to the any length public key it has previously sent with its certificate. Notice, that if the cipher suite is an exportable one and the certificate s public key is longer than 512 Bits, the server has to take care for a temporary key pair since the certificate s any length public key is only allowed to be used for signing! The following table provides an overview of the specific certificate types, cryptographic keys respectively parameters required by the particular cipher suites. Cipher Suite Name Private Key + RSA Certificate RSA temporary key pair Private Key + DSA Certificate Private Key + DH Certificate DH temporary parameters SSL_NULL_WITH_NULL_NULL* SSL_RSA_WITH_NULL_MD5* x x 1) SSL_RSA_WITH_NULL_SHA* x x 1) SSL_RSA_EXPORT_WITH_RC4_40_MD5* x x 1) SSL_RSA_WITH_RC4_128_MD5 x SSL_RSA_WITH_RC4_128_SHA x SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5* x x 1) SSL_RSA_WITH_IDEA_CBC_SHA x SSL_RSA_EXPORT_WITH_DES40_CBC_SHA* x x 1) SSL_RSA_WITH_DES_CBC_SHA x SSL_RSA_WITH_3DES_EDE_CBC_SHA x SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA* x SSL_DH_DSS_WITH_DES_CBC_SHA x SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA x SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA* x SSL_DH_RSA_WITH_DES_CBC_SHA x SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA x SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA* x x 8

9 SSL Cipher Suites SSL_DHE_DSS_WITH_DES_CBC_SHA x x SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA x x SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA* x x SSL_DHE_RSA_WITH_DES_CBC_SHA x x SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA x x SSL_DH_anon_EXPORT_WITH_RC4_40_MD5* SSL_DH_anon_WITH_RC4_128_MD5 SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA SSL_DH_anon_WITH_DES_CBC_SHA SSL_DH_anon_WITH_3DES_EDE_CBC_SHA x x x x x *... exportable cipher suite x... required to support the particular cipher suite 1)... required if certificate RSA public key > 512 Bits Table 1.2: Cipher Suite Requirements Note, that a Diffie Hellman certificate for transmitting the DH parameters may be based either on RSA or on DSS signing (see table 1.3). It s quite obviously that the listed certificate types and keys only are predicted by the particular cipher suite s key exchange algorithm. Symmetric cipher and hash algorithm have no influence on the choice of the certificate type. The table below therefore briefly describes the several key exchange algorithms (see also [SSL]). Key Exchange Algorithm Description Key size limit for public keys used in exportable cipher suites NULL No key exchange N/A RSA RSA key exchange None RSA_EXPORT RSA key exchange RSA = 512 Bits DH_DSS DH with DSS-based certificates None DH_DSS_EXPORT DH with DSS-based certificates DH = 512 Bits DH_RSA DH with RSA-based certificates None DH_RSA_EXPORT DH with RSA-based certificates DH = 512 Bits, RSA = None DHE_DSS Ephemeral DH with DSS signatures None DHE_DSS_EXPORT Ephemeral DH with DSS signatures DH = 512 Bits DHE_RSA Ephemeral DH with RSA signatures None DHE_RSA_EXPORT Ephemeral DH with RSA signatures DH = 512 Bits, RSA = None DH_anon Anonymous DH, no signatures None DH_anon_EXPORT Anonymous DH, no signatures DH = 512 Bits Table 1.3: Key Exchange Algorithms 9

10 SSL Cipher Suites RSA denotes cipher suites where the server transmits its public RSA key of any length within a RSA certificate. RSA_EXPORT demands for an extra key exchange message for sending a temporary RSA public key of a length less than (or equal) 512 Bits according to the US law export restrictions if the certificate s public key is longer than 512 Bits. In this case, the temporary key pair is signed with the RSA private key that belongs to the any length RSA public key previously has been sent within the RSA certificate. DH_RSA, DH_DSS: the server s certificate transmits the Diffie Hellman parameters that are signed by the certification authority using the RSA respectively DSA algorithm. DH_RSA_EXPORT, DH_DSS_EXPORT: same as above, except for restricting the Diffie Hellman key length to a maximum of 512 Bits since the cipher suite is exportable. DHE_RSA, DHE_DSS: the Diffie Hellman parameters are sent within an extra key exchange message, signed by the key of a previously transmitted RSA respectively DSA certificate. DHE_RSA_EXPORT, DHE_DSS_EXPORT: same as above, except for restricting the Diffie Hellman key length to a maximum of 512 Bits since the cipher suite is exportable. DH_anon, DH_anon_EXPORT: since the communication is an entirely anonymous one, none certificate will be necessary. The DH parameters are sent within the server key exchange message. Summing up, the server has to take care for a RSA certificate (plus corresponding private key) if it intends to support a RSA or DHE_RSA cipher suite. Additionally a RSA temporary key pair will be necessary if the cipher suite is an exportable one and the RSA certificate s public key claims for more than 512 Bits. DHE_RSA require temporary DH parameters. A DH certificate (plus corresponding private key) must be provided for any kind of DH cipher suite. DHE_DSS cipher suites demand DSA certificates (plus corresponding private keys) and temporary DH parameters. And finally DH_anon cipher suites render any kind of certificate superfluous since the DH parameters are sent unsigned within a key exchange message. The symmetric algorithms used by SSL for data encryption can be divided into stream ciphers (RC4 with 40 or 128 Bit keys) and block ciphers (RC2 with 40 Bit keys, IDEA, DES40, DES, 3DES_EDE). All the block ciphers operate in CBC (Cipher Block Chaining) mode XORing each plaintext block with the previous ciphertext block before encrypting it. The message digest algorithms supported by SSL are MD5 which produces a 128 Bit hash, and SHA for providing a 160 Bit hash. All the various combinations are listed above in table 1.1 and can be consulted in [SSL] for a further increasing of knowledge. Descriptions of the several algorithms may be found in [Schneier]. Now, I suppose, quite enough has been said about the SSL cipher suites, and it s time to introduce IAIK s SSLv3 implementation isasilk. Before starting the discussion within the next chapters, a short glossary tries to pithy depict some of the most essential terms commonly emerging throughout the isasilk SSL environment. 10

11 SSL Glossary 2 Glossary API Application Programming Interface; programming interface of a software system. Applet Java program that is embedded into a HTML file for executing it directly by an appropriate browser. ASN.1 Abstract Syntax Notation One; language for describing data structures in an abstract and platform independent manner. Asymmetric Cipher Cryptographic algorithm using a public key for data encryption and a secret (private) key for data decryption. Anyone who has access to the public key can encrypt a message, but only the owner of the corresponding private key is able to decrypt the received message. Asymmetric - or public key algorithms - also are used for data signing. Messages that are signed with the private key of a specific entity can be verified with the matching public key. Authentication Someone s identity supported by voucher, usually done by means of a certificate. BER Basic Encoding Rules; set of rules for binary encoding ASN.1 objects. Block Cipher Symmetric algorithm that operates on - usually 64 Bit - blocks of plaintext and ciphertext. Browser Tool for viewing WWW sites. CA Certification Authority; trustworthy and independent institution for issuing and managing certificates. 11

12 SSL Glossary CBC Cipher Block Chaining mode; adds a feedback mechanism to a block cipher; before an plaintext block is encrypted, it is XORed with the previous ciphertext block (the first block is XORed with an inizialization vector). Certificate A special message for verifying someone s identity; usually a certificate will contain the user s name and public key - optionally additional information may be included - and is signed by a trustworthy entity (i.e. certification authority). The certificate syntax is specified by the ITU-T X.509 recommendation. Client Within a client/server architecture, one part - the server - provides some resources requested by the other part that is called the client. Server and client usually execute on different hosts. Data Integrity Certainty that the data has not been modified during the transmission. DER Distinguished Encoding Rules; subset of the Basic Encoding Rules for binary encoding ASN.1 objects. DER encoding is non ambiguously. There is definitely one way to encode an ASN.1 object as an octet string. BER encoding is ambiguously making it possible to represent an ASN.1 object in more than one ways as an octet string. DES Data Encryption Standard; the most popular symmetric block algorithm for data encryption. DH Diffie-Hellman; the first public key algorithm; used for key distribution. Digital Signature A possibility for ensuring the origin and integrity of data; the sender uses a public key algorithm and one way hash function to sign his message; the recipient can verify that the message has been signed by no one other than the sender, and that the message has reached the destination unchanged. 12

13 SSL Glossary DSA Digital Signature Algorithm; public-key digital signature algorithm, employed by the DSS. DSS Digital Signature Standard, proposes the digital signature algorithm for digital signing to verify the integrity of data and the identity of the sender. FTP File Transfer Protocol; protocol for managing file transfers over the net. Handshake A negotiation dialogue between the client and server arranging the cryptographic parameters for the following secure data transfer. Hash function Mathematical function for computing a fixed sized data value (hash) from input data of arbitrary size. The length of the hash value usually is shorter than that of the input data. In cryptography generally oneway hash functions are used, making it easy to compute the hash but hard to go the reverse way for calculating the input data when only the hash is known. HTML Hypertext Markup Language; formatting and structuring language for building WWW documents. HTTP Hypertext Transfer Protocol; the transfer protocol of the WWW. IDEA International Data Encryption Algorithm; ranks as one of the best and most secure block ciphers that are contemporary public available. IP Internet Protocol; basic Internet transport protocol. IV Initialization Vector for XORing with the first plaint text block when running a block cipher in CBC mode. 13

14 SSL Glossary Java Object oriented and platform independent programming language of Sun Microsystems Inc. JCA Java Cryptography Architecture; framework for accessing and developing cryptographic functionality for the Java Platform ([JCA]). JCE Java Cryptography Extension; extends the JCA API to include encryption and key exchange. Key Exchange Cryptographic technique where the data encryption of each particular session is done with a specific session key only used for this one single session. MAC Message Authentication Code; denotes a cryptocraphic checksum, which is derived by processing some given message (or the authentication elements of the message) using a secret key for ensuring the integrity of data. Master Secret 48-Byte shared secret between client and server that is used for generating encryption keys, MAC secrets and initialization vectors. MD5 Message Digest 5; one-way hash function for producing a 128-bit hash (message digest) from the input data. Message Digest Bit String of fixed length (hash), computed from input data of arbitrary length (see hash function). PKCS Public-Key Cryptography Standards; standards for public-key cryptography applications based on the RSA encryption method. Public Key Cryptography Asymmetric encryption method; one key is public and can be used by anyone interested; the corresponding private key is kept in secret by the key-pair owner. Data that is encrypted with the public key only can be decrypted with the corresponding private key. Data 14

15 SSL Glossary that is signed with the private key can be verified with the matching public key. RC2 RC4 Ron s Code 2 (Rivest Cipher 2); variable-key-size 64-Bit block cipher, developed by Ron Rivest for RSA Data Security, Inc. Ron s Code 4 (Rivest Cipher 4); variable-key-size stream cipher, developed by Ron Rivest for RSA Data Security, Inc. RSA Famous public-key algorithm, developed by Ron Rivest, Adi Shamir and Leonard Adleman in 1977; may be used for data encryption or digital signing. Server Within a client/server architecture, one part - the server - provides some resources requested by the other part that is called the client. Server and client usually execute on different hosts. Session A SSL session ([SSL]) is an association between a client and a server. Sessions are created by the handshake protocol. Sessions define a set of cryptographic security parameters, which can be shared among multiple connections. Sessions are used to avoid the expensive negotiation of new security parameters for each connection. A particular session is identified by a value (session identifier) generated by the server. SHA Secure Hash Algorithm; algorithm for computing a hash value; designed for use with the Digital Signature Standard (DSS); the corresponding standard is named Secure Hash Standard (SHS). S-HTTP Secure-Hypertext Transfer Protocol; extends the HTTP about some security capabilities. Socket Logical end-point of a network communication based on TCP or UDP. 15

16 SSL Glossary Stream Cipher Symmetric algorithm that operates on streams of plaintext and ciphertext one bit or byte at a time. Symmetric Cipher Encryption algorithm that uses the same - secret - key for both, data encryption and data decryption. TCP Transmission Control Protocol; connection based protocol that operates on the IP thereby extending it about reliability. TCP/IP Collection of protocols for managing data transfers over the Internet. URL Uniform Resource Locator; address of a WWWresource. WWW World Wide Web; multimedia information system of the Internet; based on Hypertext. X.509 ITU-T (International Telecommunication Union) recommendation for supposing an authentication system and certificate syntax. 16

17 Introduction 3 Introduction to isasilk isasilk (IAIK Java SSL) is an implementation of the SSL protocol version 3.0 as specified by Netscape Communications Corporation. isasilk operates on top of the IAIK-JCE packages, both developed at the Institute for Applied Information Processing and Communications of the University of Technology in Graz, Austria, but may be used with any alternative JCE provider (see 3.3.1). This paper gives an introduction to the main features of isasilk. After presenting some general outlines making you familiar with the essential programming requirements, some step-by-step examples intend to provide guidelines for implementing SSL connections. In chapter 1 - SSL Overview - it has been said that SSL operates at the Socket interface used for TCP, additionally supplied with peer authentication and data encryption. According to this, isasilk implements SSL connections by extending the Socket classes of the java.net package about SSL s inherent security features. So it would be a good practice to introduce isasilk by duplicating the process of going from a normal to a secure SSL connection. During the following discussion, we have to distinguish between the client s and the server s side of a connection. 3.1 SSLClient: From Socket To SSLSocket Perhaps you have read the Java tutorial for establishing TCP connections by means of the java.net.socket and java.net.serversocket classes ([javatut]) and remember the basic steps required for implementing the client side of the connection: 1. Open a socket. 2. Open an input stream and output stream to the socket. 3. Read from and write to the streams according to the server's protocol. 4. Close the streams. 5. Close the socket. In Java programming code the realization of these several tasks may look like (to simplify matters, exception handling is not included in the following code examples): 1. Socket s = null; s = new Socket(serverName, serverport); A variable of type Socket is defined and then instantiated thereby establishing a socket connection to a server previously specified by servername that is listening at port number serverport. 17

18 Introduction 2. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream()); An output and an input stream are opened on the socket to write to and read from the socket. 3. Do something useful Since this chapter only deals with the establishing and closing of connections, the actual client-server data transfer is not of interest at this state of discussion. 4. os.close(); is.close(); Close output and input streams. 5. s.close(); Close the socket. If we want to include exception handling, we must be aware that connecting to a server might raise an UnknownHostException and the several input/output stream operations might lead to an I/O Exception. Hence, the whole client program fragment for opening and closing a conventional socket connection may look like: Socket s = null; try { s = new Socket(serverName, serverport); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with server... os.close(); is.close(); s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); Now, after we have taken a look at the core work for realizing the client s side of a normal socket client-server connection, the question arises, what s to do when implementing a SSLClient using isasilk? If we - for the present - don t consider basic prerequisites like importing some necessary classes or installing a provider, the main steps don t differ greatly from the tasks for building a conventional client: 18

19 Introduction 1. Open a SSL socket. 2. Open an input stream and output stream to the SSL socket. 3. Read from and write to the streams according to the server s protocol. 4. Close the streams. 5. Close the SSL socket. In Java programming code the realization of these several tasks may look like (to simplify matters, exception handling is not included in the following code examples): 1. SSLSocket s = null; SSLClientContext context = new SSLClientContext(); s = new SSLSocket(serverName, serverport, context); Instead of creating a normal Socket object as above, a representative of SSLSocket is instantiated. The isasilk class SSLSocket inherits from the class Socket of the java.net package and extends it about the SSL security features. The specific security properties of a particular SSLSocket object mainly are determined by the context of the SSL socket and can be influenced by the user in creating a SSLClientContext object and supplying it with the desired settings (cipher suites, compression methods,...). When actually instantiating the SSLSocket object in line 3 of the code stated above, the constructor demands for a context object to define the client s security capabilities for going into a SSL handshake with the specified server listening on port serverport. If a context object only has been created but not equipped with special user inputs, a default context is taken and put to the SSLSocket. The SSLSocket and context classes are discussed in detail further below; for a first glance it should do to confirm with the default settings. 2. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream()); By means of exactly the same lines of program code as be usual for a conventional connection, an output and an input stream are opened on the SSL socket to write to and read from the socket. 3. Do something useful Since this chapter only deals with the establishing and closing of SSL connections, the actual client-server data transfer is not of interest at this state of discussion. 4. os.close(); is.close(); Close output and input streams. The output stream has to be closed before closing the input stream. 19

20 Introduction 5. s.close(); Close the SSL socket. Note, that when finishing an isasilk SSL connection there is no real necessity for explicitly closing the streams on the socket since this is automatically done when closing the socket in the step 5 listed above. If you want to explicitly close the streams, be sure to close the output stream before closing the input stream to ensure that the SSL connection finishes correctly. Again, we should be aware of UnknownHost and I/O Exceptions leading to the following program fragment as part for implementing the client side of a SSL connection: SSLSocket s = null; SSLClientContext context = new SSLClientContext(); try { s = new SSLSocket(serverName, serverport, context); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with server... os.close(); is.close(); s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); So far you have seen that the implementation of the basic steps for building a conventional Client or a SSLClient mainly differs in providing a context object that determines the security features of the SSL Socket connection. The next chapter will introduce the basic tasks for realizing the server side of a SSL connection. As you already might suppose, you will have to take care for a server context to manage the security properties of the SSLServer. 3.2 SSLServer: From ServerSocket To SSLServerSocket The basic steps for implementing the server side of a conventional socket connection can be summarized as follows: 20

21 Introduction 1. Open a server socket to listen on a specified port number for any client requests. 2. If a client wishes to connect to the server, try to accept the connection by creating a client socket. 3. Open an input stream and output stream to the client socket. 4. Read from and write to the streams. 5. Close the streams. 6. Close the sockets. In Java programming code the realization of these several tasks may look like (to simplify matters, exception handling is not included in the following code examples): 1. ServerSocket server = null; server = new ServerSocket(serverPort); A ServerSocket object is created for listening on a previously specified port serverport. 2. Socket s = null; s = server.accept(); The server, that listens on the specified port number, tries to accept a client request. If this successfully is done, the accept method returns a new socket object for communicating with the client. 3. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream()); An output and an input stream are opened on the socket to write to and read from the socket. 4. Do something useful Since this chapter only deals with the establishing and closing of connections, the actual client-server data transfer is not of interest at this state of discussion. 5. os.close(); is.close(); Close output and input streams. 6. s.close(); server.close(); Close (client) socket and server socket. 21

22 Introduction Considering exception handling on the server side, we must try to catch I/O exceptions if the server will not be able to listen on a specific port or if some Input/Output stream operation fails. Also the accept method may throw an I/O exception if an error occurs while waiting for a connection request. Hence, the whole server program fragment for listening and accepting conventional socket connection requests may look like: ServerSocket server = null; Socket s = null; try { server = new ServerSocket(serverPort); s = server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with client... os.close(); is.close(); s.close(); server.close(); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); Maybe, you don t want to close the server socket immediately after closing the client socket in order to be able for accepting further client requests. In this case, a while loop may be used for handling one client request after the other. The server socket is opened outside the while loop and continues listening for connection requests after the conversation with one particular client has been finished by closing the client socket : ServerSocket server = null; Socket s = null; try { server = new ServerSocket(serverPort); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); while (true) { try { s = server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with client... os.close(); is.close(); s.close(); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); 22

23 Introduction Now, after we have take a look at the core work for realizing the server s side of a normal socket client-server connection, what s to do when implementing a SSLServer using isasilk? If we - for the present - don t consider basic prerequisites like importing some necessary classes or installing a provider, the main steps don t differ greatly from the tasks for building a conventional server: 1. Open a SSL server socket to listen on a specified port number for any client requests. 2. If a client wishes to connect to the server, try to accept the connection by opening a SSL client socket. 3. Open an input stream and output stream to the client socket. 4. Read from and write to the streams. 5. Close the streams. 6. Close the SSL sockets. In Java programming code the realization of these several tasks may look like (to simplify matters, exception handling is not included in the following code examples): 1. SSLServerSocket server = null; SSLServerContext servercontext = new SSLServerContext(); server = new SSLServerSocket(serverPort, servercontext); Instead of creating a normal ServerSocket object as above, a representative of SSLServerSocket is instantiated. The isasilk class SSLServerSocket inherits from the class ServerSocket of the java.net package and extends it about the SSL security features. The specific security features of a particular SSLServerSocket object mainly are determined by the context of the SSL server socket and can be influenced by the user in creating a SSLServerContext object and supplying it with the desired settings (cipher suites, compression methods,...). When actually instantiating the SSLServerSocket object in line 3 of the code stated above, the constructor demands a context object to define the server s security capabilities for going into a SSL handshake with the a client requesting a connection at the port number the server is listening. If a context object only has been created but not equipped with special user inputs, a default context is taken and put to the SSLServerSocket. The SSLServerSocket and context classes are discussed in detail further below; for a first glance it should do to confirm with the default settings. 2. SSLSocket s = null; s = (SSLSocket)server.accept(); The server, that listens on the specified port number, tries to accept a client request. If this successfully is done, the accept method returns a new SSL socket object for communicating with the client. Since the accept method of the ServerSocket class by default returns a conventional Socket object, it is necessary to make an explicit cast for obtaining a SSLSocket object. 23

24 Introduction 3. PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream()); By means of exactly the same lines of program codes as be usual for a conventional connection, an output and an input stream are opened on the SSL socket to write to and read from the socket. 4. Do something useful Since this chapter only deals with the establishing and closing of SSL connections, the actual client-server data transfer is not of interest at this state of discussion. 5. os.close(); is.close(); Close output and input streams. The output stream has to be closed before closing the input stream. 6. s.close(); server.close(); Close the SSL (client) socket and the SSL server socket. Note, that in a isasilk SSL connection there is no real necessity for explicitly closing the streams on the client socket since this is automatically done when closing the client socket in the step 6 listed above. If you want to explicitly close the streams, be sure to close the output stream before closing the input stream to ensure that the SSL connection finishes correctly. Exceptions on the server side of a SSL connection may be thrown for the same reasons as they may appear when implementing a server in a conventional connection: we must try to catch I/O exceptions if the server will not be able to listen on a specific port or if some Input/Output stream operation fails. Also the accept method may throw an I/O exception if an error occurs while waiting for a connection request. Additionally we have to introduce the SSLException for capturing errors that may occur during the SSL handshake phase. Hence, the whole SSL server program fragment for listening and accepting SSL socket connection requests may look like: SSLServerSocket server = null; SSLServerContext servercontext = new SSLServerContext(); SSLSocket s = null; try { server = new SSLServerSocket(serverPort, servercontext); s = (SSLSocket)server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with client... 24

25 Introduction os.close(); is.close(); s.close(); server.close(); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); Again, you might wish to implement a SSL server permanently listening on client requests: SSLServerSocket server = null; SSLSocket s = null; SSLServerContext servercontext = new SSLServerContext(); try { server = new SSLServerSocket(serverPort, servercontext); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); while (true) { try { s = (SSLSocket)server.accept(); PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream());... communicate with client... os.close(); is.close(); s.close(); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); After these first glances onto the main steps for programming client and server of a SSL connection based on the isasilk SSLv3 implementation, we are ready to take a look behind the main properties of SSL Socket and Context classes. Before doing so, perhaps it would be advantageously to reflect the basic preconditions that are necessary for implementing SSL clients and SSL servers. 25

26 Introduction 3.3 Basic Requirements Within the previous sections we directly have stepped into program code fragments for implementing a SSL client and server, not concerning some fundamental requirements that have to be fulfilled for ensuring the correct working of our implementations. If you think of the cipher suite discussion of chapter 1 - SSL Overview - you will remember the several certificate types, cryptographic keys and parameters that are necessary for supporting the particular sorts of cipher suites (see table 1.2). In this section we introducing will scrutinize how isasilk fits into the JCA/JCE provider architecture. Following this, we will assume to implement a SSL server and discuss basic preconditions like taking care for particular certificates and cryptographic parameters necessary for cipher suite support Provider Handling The provider architecture has been introduced by the Java Cryptographic Architecture (JCA) making it possible for different cryptography implementations to operate on common interfaces. The term provider is an abbreviation for Cryptographic Package Provider and denotes a package or a set of packages supplying a concrete implementation of a subset of the cryptography aspects of the Java Security API (see [JCA]). The Java Development Kit offers a default provider - "SUN" - but everyone is free to create its own or use any other provider having access to it. Each provider may come up with its own particular implementation of any cryptographic algorithm to be used, and the user may decide to prefer, for instance, the DSA implementation of provider 1 instead of working with the DSA algorithm implemented by provider 2. For applications that operate on the Java Cryptography Extension (JCE) additionally to JCA providers at least one proper JCE provider - for instance the IAIK provider as described below - has to be made available. Precondition for being able to use some specific provider is to install and configure the corresponding provider package classes (see [JCA]). For generally accessing and using the algorithm implementations of specific providers, the Java Cryptography Architecture introduces the concept of engine classes and factory methods. Engine classes provide interfaces to the functionality of a type of cryptographic algorithms and factory methods are used for obtaining some specific implementation. So, for instance, an object of the MessageDigest engine class is instantiated by means of the getinstance factory method: MessageDigest md = MessageDigest.getInstance("AlgorithmName", "ProviderName"); 26

27 Introduction Specifying a particular provider is optional. If no provider is stated, all actual providers are searched until one is found that implements the required algorithm: MessageDigest md5 = MessageDigest.getInstance("MD5"); Otherwise the particular algorithm implementation of the explicitly specified provider will take precedence. A provider may realize implementations of digital signature algorithms, message digest algorithms and - if supported by JCE - encryption algorithms. The IAIK security provider package supports the following algorithms and security facilities: Signatures: - MD5/RSA (MD5 with RSA encryption) - SHA/RSA (SHA with RSA encryption) Key Management facilities: - RSA and DSA keys - RSA and DSA key pair generators - DH keys and key parameter generation Symmetric Ciphers: - DES - Triple DES - IDEA - RC4 - RC2 Precondition for being able to use some specific provider is to install and configure the corresponding provider package classes. When intending to use the IAIK security provider package, the first step of installing the provider already has been done by installing the IAIK-JCE implementation and updating the classpath variable according to the location of the iaik-jce.jar file. The second step of configuring the provider can be done either statically or dynamically. For detailed information about the configuration process you may consult the [JCA] documentation; in our example we will register the IAIK provider dynamically by adding it to the list of the providers in use: 27

28 Introduction IAIK provider = new IAIK(); Security.addProvider(provider); For supporting any alternative provider, isasilk is equipped with a specific interface class (iaik.security.ssl.provider.securityprovider) that has to be implemented by an application intending to use another than the IAIK provider. Everytime some provider related objects are required, isasilk will consult this SecurityProvider implementation to query for the provider dependent source by accessing one of the several getcryptographicobject methods: /** * Returns a DHPublicKey created from the values: y (public), p (prime modulus) and * g (base generator). * * This method only must be implemented if an application wants to use Diffie-Hellman * cipher suites. */ public abstract DHPublicKey getdhpublickey(biginteger y, BigInteger p, BigInteger g); /** * Returns a DHPrivateKey created from the values: x (private), p (prime modulus) and * g (base generator). * * This method only must be implemented if an application wants to use Diffie-Hellman * cipher suites. */ public abstract DHPrivateKey getdhprivatekey(biginteger x, BigInteger p, BigInteger g); /** * Returns a RSAPublicKey created from the values: modulus and publicexponent. * * This method only must be implemented if an application wants to use RSA cipher suites. */ public abstract RSAPublicKey getrsapublickey(biginteger modulus, BigInteger publicexponent); /** * Returns a X509Certificate created from a DER encoded byte array. */ public abstract X509Certificate getx509certificate(byte[] array) throws CertificateException; /** * Returns a Principal created from a DER encoded byte array. * * A Principal in Sun s point of view is the ASN.1 stucture: Name. This method is * the opposite of getencodedprincipal(principal). */ public abstract Principal getprincipal(byte[] array) throws IOException; 28

29 Introduction /** * Returns a DER encoded Name (Principal). * * A Principal in Sun s point of view is the ASN.1 stucture: Name. This method * is the opposite of getprincipal(byte[]). */ public abstract byte[] getencodedprincipal(principal principal); /** * Returns the desired MessageDigest object specified by the algorithm name. * * isasilk makes use of the following MessageDigest algorithms: * "SHA", "MD5" */ public abstract MessageDigest getmessagedigest(string algorithm) throws NoSuchAlgorithmException; /** * Returns the desired Signature object specified by the algorithm name. * * isasilk makes use of the following MessageDigest algorithms: * "DSA", "RawDSA" */ public abstract Signature getsignature(string algorithm) throws NoSuchAlgorithmException; /** * Returns the desired Cipher object specified by its transformation. * * isasilk makes use of the following cipher algorithms: * "RSA/1/PKCS1Padding", "RSA/2/PKCS1Padding", "RC4", "RC2/CBC", * "IDEA/CBC", "DES/CBC", "3DES/CBC" */ public abstract Cipher getcipher(string algorithm) throws NoSuchAlgorithmException; /** * Return a new instance of a SecureRandom number generator. This can be * the original java.security.securerandom or a better * generator if available (as when using IAIK JCE 2.5). */ public abstract SecureRandom getsecurerandom(); As you already might have seen, not all of these methods have to be implemented by an application that wants to use another than the IAIK security provider. If, for instance, an application don t intends to support Diffie Hellman cipher suites, there is no need for implementing getdhpublickey and getdhprivatekey. Also getrsapublickey is optionally, depending on whether to support RSA cipher suites or not. 29

30 Introduction For defining the default settings, the isasilk package includes a IAIK provider specific implementation of the SecurityProvider interface, which may serve as a guidance on how to implement this interface: iaik.security.ssl.iaikprovider: import java.io.ioexception; import java.math.biginteger; import java.security.nosuchalgorithmexception; import java.security.cert.x509certificate; import java.security.cert.certificateexception; import java.security.signature; import java.security.messagedigest; import java.security.principal; import javax.crypto.cipher; import javax.crypto.nosuchpaddingexception; import javax.crypto.interfaces.rsapublickey ; import javax.crypto.interfaces.dhpublickey; import javax.crypto.interfaces.dhprivatekey; import javax.crypto.spec.dhpublickeyspec; import javax.crypto.spec.dhprivatekeyspec; import iaik.asn1.structures.name; // This class implements the SecurityProvider interface for the provider // IAIK. public class IaikProvider implements iaik.security.ssl.provider.securityprovider { // default constructor public IaikProvider() { public DHPublicKey getdhpublickey(biginteger y, BigInteger p, BigInteger g) { return new iaik.security.dh.dhpublickey(new DHPublicKeySpec(y, p, g)); public DHPrivateKey getdhprivatekey(biginteger x, BigInteger p, BigInteger g) { return new iaik.security.dh.dhprivatekey(new DHPrivateKeySpec(x, p, g)); public RSAPublicKey getrsapublickey(biginteger modulus, BigInteger exponent) { return new iaik.security.rsa.rsapublickey(modulus, exponent); public X509Certificate getx509certificate(byte[] array) throws CertificateException { return new iaik.x509.x509certificate(array); public Principal getprincipal(byte[] array) throws IOException { try { return new Name(array); catch (Exception ex) { throw new IOException("Unable to parse Principal."); 30

31 Introduction public byte[] getencodedprincipal(principal principal) { return ((Name)principal).getEncoded(); public MessageDigest getmessagedigest(string algorithm) throws NoSuchAlgorithmException { if( algorithm.equals("md5") ) return new iaik.security.md.md5(); if( algorithm.equals("sha") ) return new iaik.security.md.sha(); try { return MessageDigest.getInstance(algorithm); catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); public Signature getsignature(string algorithm) throws NoSuchAlgorithmException { if( algorithm.equals("dsa") ) return new iaik.security.dsa.dsa(); if( algorithm.equals("rawdsa") ) return new iaik.security.dsa.rawdsa(); try { return Signature.getInstance(algorithm); catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); public Cipher getcipher(string algorithm) throws NoSuchAlgorithmException { try { return Cipher.getInstance(algorithm, "IAIK"); catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); /** * Return an instance of the default SecureRandom class set * in iaik.security.random.secrandom. */ public SecureRandom getsecurerandom() { return iaik.security.random.secrandom.getdefault(); For definitely knowing what type of objects have to be returned by the several getcryptographicobject methods, take a look at the import section of the IiakProvider source code printed above. Of interest are all the imported classes prefixed by java.security or javax.crypto that have no concern with any exception or specification: java.security.cert.x509certificate java.security.signature java.security.messagedigest java.security.principal javax.crypto.cipher javax.crypto.interfaces.rsapublickey (optional) javax.crypto.interfaces.dhpublickey (optional) 31

32 Introduction javax.crypto.interfaces.dhprivatekey (optional) isasilk will operate on any proper JCE implementation supported by a provider implementing/extending the several interfaces/classes stated above! In that way, isasilk offers a high degree on provider independence since all provider related code strictly is concentrated to the SecurityProvider interface having the only task to tell isasilk where to look for the requested cryptographic object implementations. If, for instance, an application wishes to support Diffie Hellman cipher suites thereby not using the IAIK default provider, the corresponding SecurityProvider interface implementing class has to contain implementations of the getdhpublickey and getdhprivatekey methods returning proper DHPublicKey respectively DHPrivateKey objects instantiated from classes that implement the DHPublicKey respectively DHPrivateKey interfaces of the javax.crypto.interfaces package. From this follows for the previous IiakProvider implementation example, that the iaik.security.dh.dhpublickey class is an (IAIK provider specific) implementation of the javax.crypto.interfaces.dhpublickey interface, since the getdhpublickey method accesses iaik.security.dh.dhpublickey for instantiating the DHPublilcKey object to be returned: public DHPublicKey getdhpublickey(biginteger y, BigInteger p, BigInteger g) { return new iaik.security.dh.dhpublickey(new DHPublicKeySpec(y,p,g)); Generally an implementation of the SecurityProvider interface may follow two ways for telling isasilk where to look for a provider specific implementation of some required cryptographic object: Specifying the provider s name (for instance IAIK for the IAIK provider when instantiating a MessageDigest object): public MessageDigest getmessagedigest(string algorithm) throws NoSuchAlgorithmException { try { return MessageDigest.getInstance(algorithm, "IAIK"); catch (Exception ex) { throw new NoSuchAlgorithmException(ex.toString()); Directly by accessing the class which implements the corresponding interface, respectively extends the corresponding class (for instance, in the case of a MessageDigest object, we have to distinguish between MD5 and SHA, since both are used by isasilk): 32

33 Introduction public MessageDigest getmessagedigest(string algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsignorecase("md5") { return new iaik.security.md.md5(); else if (algorithm.equalsignorecase("sha") { return new iaik.security.md.sha(); else { throw new NoSuchAlgorithmException("Algorithm "+algorithm+" not implemented."); Notice, that both classes, iaik.security.md.md5 and iaik.security.md.sha extend the java.security.messagedigest class. The second way has the advantage not to explicitly specify any provider which may be preferred when dealing with applets. After successfully implementing the SecurityProvider interface you finally have to tell isasilk not to use the IAIK default provider by setting the new SecurityProvider implementation through a call to the setsecurityprovider method of the iaik.security.ssl.sslcontext class (see 3.4.1) : public static void setsecurityprovider(securityprovider provider); Summing up, an application has to perform the following steps when intending to use some other than (or beside) the IAIK security provider: 1. Installing and configuring the particular provider in mind (see [JCA]). When you wish to configure the new provider dynamically, you may prefer to add it from inside your SecurityProvider implementation, so far as you don t need to access provider dependent implementations before creating a new context object. 2. Implementing the SecurityProvider interface of the iaik.security.ssl.provider package thereby implementing the RSAPublicKey (optional), DHPublicKey (optional), DHPrivateKey (optional), and Principal interfaces of the javax.crypto.interfaces respectively java.security packages, and extending the cert.x509certificate, Signature (isasilk supports "DSA" and "RawDSA"), MessageDigest (isasilk supports "SHA" and "MD5") and Cipher (isasilk supports "RSA/1/PKCS1Padding", "RSA/2/PKCS1Padding", "RC4", "RC2/CBC", "IDEA/CBC", DES/CBC", "3DES/CBC") classes of the java.security respectively javax.crypto packages. 33

34 Introduction Notice that "RSA/1/PKCS1Padding" and "RSA/2/PKCS1Padding" are not standardized in javax.crypto.cipher. The transformation string "RSA/1/PKCS1Padding" means that a RSA en/decryption will be performed using block formatting according to PKCS#1 with block type 1; "RSA/2/PKCS1Padding" uses blocktype 2. isasilk will follow the same principle as used for any other Cipher object when obtaining the corresponding provider dependent en/decryption object by accessing the getcipher method of the actual SecurityProvider implementation (assuming that provider denotes the particular SecurityProvider implementation): Cipher rsa = provider.getcipher("rsa/1/pkcs1padding"); rsa.init(encrypt_mode, key); respectively rsa.init(decrypt_mode, key); byte[] rsa_crypted = rsa.dofinal(data); 3. Setting the SecurityProvider implementation by calling the setsecurityprovider method of the iaik.security.ssl.sslcontext class: SSLContext.setSecurityProvider(securityProvider); If no particular SecurityProvider interface implementation is requested, per default the IAIK security provider will be prefered Certificates, Keys and Parameters Since our SSL server shall be able to support all the cipher suites implemented by isasilk - and that are all the SSLv3 cipher suites except for Fortezza - it is necessary to provide all the certificate types, keys and parameters that may be required throughout a SSL handshake procedure (remember table 1.2): ΠΠΠCertificate types: RSA, DH, DSA Private keys: RSA, DH, DSA Temporary keys/parameters: RSA, DH 34

35 Introduction As introduced in sections 3.1 and 3.2, the security features of a SSL socket respectively SSL server socket mainly are determined by their appropriate contexts. For the current task of providing the different certificates and keys, the following consequence has be drawn for the further proceeding: At first it has to be obtained the particular certificate/key/parameter. Following this, the particular certificate/key/parameter must be presented to the actual context, and finally the context has to be incorporated into the socket object claiming for it. For the first step we will assume that all the required server certificates and keys - except for temporary DH parameters which we will generate separately - are stored as DER encoded IAIK KeyAndCertificate structures on the local host in.der files located in a sub folder certs of the actual calling directory. DER denotes the distinguished encoding rules for encoding ASN.1 structures. However, for our current task it is not of main interest, how to create or get certificates 1 and keys. Rather we want to load them into the actual server context thereby assuming that the several certificate and key files already exist in the certs directory. Each particular application may follow its own strategy for obtaining certificates and key material from some available source. For our specific example, we will read in the required entities from DER encoded files. Since certificate chain and belonging private key of each specific type are stored within the same file, we have to perform the following steps for obtaining the requested authentication material : 1. Reading in certificate chain and private key from the actual DER file thereby creating a KeyAndCertificate object of the iaik.utils package: import iaik.utils.keyandcertificate;... KeyAndCertificate kac; kac = new KeyAndCertificate("certs/serverRSA1024.der"); respectively kac = new KeyAndCertificate("certs/serverDSA1024.der"); respectively kac = new KeyAndCertificate("certs/serverDH1024.der"); 2. Decrypting the password based encrypted private key according to PKCS#8 Private Key Information Syntax Standard after extracting it from the just created KeyAndCertificate object: import iaik.pkcs.pkcs8.encryptedprivatekeyinfo;... 1 Note that the demo samples included in the isasilk distribution use a keystore for obtaining keys and certificates (see the corresponding information html files) 35

36 Introduction EncryptedPrivateKeyInfo epki; epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); Making an anticipation to the discussion of the SSL context and socket classes within section 3.4, setting the several properties of a context object is done by means of particular setproperty methods. Now, if we assume that we already have created a SSLServerContext object by writing SSLServerContext servercontext = new SSLServerContext(); we are ready to set the context s certificate and private key entries: // set the RSA certificate/private key for RSA cipher suites servercontext.setrsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DSA certificate/private key for DSA cipher suites servercontext.setdsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DH certificate/private key for DH cipher suites servercontext.setdhcertificate(kac.getcertificatechain(), epki.getprivatekey());; Note that KeyAndCertifcate s method getcertificatechain() returns a X.509v3 certificate chain as required by the SSL protocol, starting with the server certificate and leading to the root certification authority. The several private keys are presented the server context object simultaneously with the corresponding certificates by means of the set*certificate methods. In order for being able to support ephemeral and anonymous Diffie Hellman cipher suites, and exportable RSA cipher suites if the certificate s public key claims for more than 512 bits, the actual context has to be supplied with the required temporary keys. RSA temporary key pairs again may be read in from a DER encoded files holding a DER encoded private key structure 1. First a RSA private key object is created from a DER file, then the corresponding public key is filtered out, and at last the temporary RSA key pair is generated from the private and public key: RSAPrivateKey tsk = new RSAPrivateKey( new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getpublickey(); KeyPair tempkeypair = new KeyPair(tpk, tsk); 1 Note that the demo samples included in the isasilk distribution use a keystore for obtaining keys and certificates (see the corresponding information html files) 36

37 Introduction Instead of using an AlgorithmParameterGenerator, we will directly construct the temporary Diffie Hellman parameters using the BigInteger class of the java.math package and the DHParameterSpec class of the javax.crypto.spec package: BigInteger p = new BigInteger("da583c16d ", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); The demo SSLServer implementation of the isasilk library also includes an example for using the AlgorithmParameterGenerator class of the java.security.spec package. After creating temporary RSA key pair and DH parameters, they have to be put to the server context object: servercontext.setrsatempkeypair(tempkeypair); servercontext.setdhparameter(dhparam); Throughout the process of providing the several certificates, keys and parameters different failures may occur that should be treated by a proper exception handling. A GeneralSecurityException may be thrown when dealing with security objects (JDK 1.2), key management may cause a InvalidKeyException, trying to access a not implemented algorithm may lead to a NoSuchAlgorithmException, and finally, file operations make it necessary to include I/O exception handling, leading to the following program code fragment for supplying the several certificate types and keys in order to support all the cipher suites: SSLServerContext servercontext = new SSLServerContext(); try { // specify the DH parameters: BigInteger p = new BigInteger("da583c16d ", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral cipher suites servercontext.setdhparameter(dhparam); // create certificates and private keys and set them to the context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setrsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); 37

38 Introduction servercontext.setdsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setdhcertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey( new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getpublickey(); KeyPair tempkeypair = new KeyPair(tpk, tsk); servercontext.setrsatempkeypair(tempkeypair); catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getmessage()); System.exit(0); catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); System.exit(0); catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); System.out.println("No server certs found!"); System.exit(0); So far all the required certificates, keys and parameters have been created and successfully presented to the server context object, leaving the only task to do incorporating the server context object to the corresponding server socket object: SSLServerSocket server = new SSLServerSocket(port, servercontext); After incorporating the server context object to the server socket object, we can close our discussion about the basic preconditions for implementing one (the server) side of a SSL connection. Later, when the SSLClientContext class will be introduced within chapter , you will notice, that on the client s side of a SSL connection certificates and key material are not directly obtained by the client. Rather a particular client trust decider has to implemented for fulfilling the task of certificate and key obtaining. The next chapter will introduce the several socket and context classes implementations of the isasilk SSLv3 project. 38

39 Introduction 3.4 SSL Socket And SSL Context Classes It already has been mentioned that the SSLSocket class inherits from the Socket class of the java.net package and correspondingly the SSLServerSocket class inherits from the java.net.serversocket class extending them about the SSL security features. Since objects of the SSLContext classes determine the security properties of SSLSocket respectively SSLServerSocket objects, it would be preferable to first introduce the SSLContext classes implementations, serving as a basis for the subsequent discussion of the SSLSocket classes. The main interaction process between SSL contexts and SSL sockets already has been mentioned: First it has to be created a SSLClientContext (or SSLServerContext) object: SSLClientContext clientcontext = new SSLClientContext(); or SSLServerContext servercontext = new SSLServerContext(); Following this, a new SSLSocket (respectively SSLServerSocket) object is created and initialized with the particular context object generated above: SSLSocket clientsocket = new SSLSocket(serverName, serverport, clientcontext); respectively SSLServerSocket = New SSLServerSocket(port, servercontext); Between these two tasks of creating a SSL context object and later using it as parameter value for instantiating a SSL socket object, the user optionally may supply the context object with particular properties. Otherwise the context objects will use default settings for defining the security features of the corresponding SSL socket objects. Goal of the following description of the SSLContext classes is the presentation of the several context properties that can be set by the user The SSLContext Class Instances of the SSLClientContext and SSLServerContext classes are used to define the security properties of corresponding SSLSocket respectively 39

40 SSLContext SSLServerSocket objects for implementing the client respectively server side of a SSL connection. Both, SSLClientContext and SSLServerContext classes are members of the iaik.security.ssl package making it necessary to import this package when intending to implement client or/and server side of a SSL connection: import iaik.security.ssl.* The SSLServerContext class is implemented as a subclass of the SSLClientContext class extending it about the member classes and methods that are necessary to fulfill the several certificate, key and parameter conditions for supporting any desired cipher suite (remember: on the server side, certificates and keys for authentication and key exchange are immediately supplied to the actual SSLServerContext object, whereas on the client side certificates and keys are obtained by a special client trust decider; see ): public class SSLServerContext extends SSLClientContext implements Cloneable Instances of the SSLServerContext class will be cloneable since it may be necessary for cryptography parameter renegotiation to create field-to-field copies of an existing context object (see section ). The SSLClientContext class itself implements the abstract class SSLContext defining a set of abstract methods for managing all the properties that are basically necessary for realizing any kind of SSL socket: public class SSLClientContext extends SSLContext implements Cloneable All the abstract methods of the public public abstract class SSLContext provide templates for setting respectively getting the several properties of a particular SSL Socket implementation: public abstract CipherSuite[] getenabledciphersuites(); public abstract void setenabledciphersuites(ciphersuite[] enabledciphersuites); for obtaining respectively setting the particular Cipher Suites supported by the actual SSL context implementation. public abstract CompressionMethod[] getenabledcompressionmethods(); public abstract void setenabledcompressionmethods(compressionmethod[] enabledcompressionmethods); for obtaining respectively setting the particular compression methods supported by the actual SSL context implementation. 40

41 SSLContext public abstract Random getrandomgenerator(); public abstract void setrandomgenerator(random randomgenerator); for obtaining respectively setting a specific random generator implementation responsible for generating all the random numbers that are required throughout the handshake procedure. public abstract SessionManager getsessionmanager(); public abstract void setsessionmanager(sessionmanager sessionmanager); for obtaining respectively setting a specific session manager implementation that is responsible for the actual session caching strategy. public abstract TrustDecider gettrustdecider(); public abstract void settrustdecider(trustdecider trustdecider); for obtaining respectively setting the particular trust decider implementation that is responsible for the actual certificate trusting strategy. If you think back to section you will remember that isasilk offers a high degree of provider independence: an application that wishes to use another than the default IAIK Security Provider only has to implement the SecurityProvider interface of the iaik.security.ssl.provider package. For enabling a specific SecurityProvider implementation, it has to be set by calling the setsecurityprovider method of the SSLContext class. The currently installed security provider can be obtained from the context by using the setsecurityprovider method: public static void getsecurityprovider(); public static void setsecurityprovider(securityprovider provider); Note, that in contrast to all the methods listed above, the two methods for obtaining respectively setting some particular SecurityProvider implementation, are not declared as being abstract. They are already implemented by the SSLContext class itself, namely as static methods, since only one unique system-wide security provider will be necessary. All the listed properties (cipher suites, compression methods, session manager,...) have to be incorporated by both, SSLClientContext objects as well as SSLServerContext objects. SSLServerContext objects additionally come up with the several certificate, key and cryptographic parameter features. Hence, the following SSLClientContext class discussion introduces the basic main properties of any SSL context object, followed by a description of the SSLServerContext extensions. 41

42 SSLContext The SSLClientContext Class The SSLClientContext class implements the SSLContext interface and provides all the basic properties that are necessary for managing the security features of the client socket of a SSL connection: supported cipher suites, supported compression methods, random number generator, session manager and trust decider. All these entities either can be set by means of particular user directives or might be established by agreeing with some predefined default settings. During the following discussion, keep in mind that all the basic properties also must be supported by any specific SSLServerContext implementation Random Number Generator It already has been introduced several times how to create an SSLClientContext object by instantiating the SSLClientContext class: SSLClientContext clientcontext = new SSLClientContext(); If we agree with this line of program code, we make use of the SSLClientContext default empty constructor that first has to create a default random number generator based on the current time, which may last a few seconds 1. The task of the random number generator is the generation of all random numbers that are required throughout the SSL handshake procedure: import java.util.random; Random random_generator; 1 Depending on the platform your application is running, the initialization of the random number generator may last less or more time. For increasing speed, immediately after starting your application you may create a new thread which initializes the SecureRandom generator. In this way, the seed already has been generated the first time random numbers are requested, e.g.: (new Thread() { public void run() { try { setpriority(thread.min_priority); random.nextint(); System.out.println("random number generator initialized..."); catch (Exception ex) { ex.printstacktrace(); ).start(); Alternatively you may implement your own seed generator for providing a faster way of random number generation. 42

43 SSLContext If we intend to implement our own random generator - for instance by creating a SecureRandom object of the java.security package providing a crytpographically strong pseudo-random number generator that is based on the SHA-1 hash algorithm, we directly have to supply it when creating the context object. The SSLClientContext class therefore is equipped with a proper constructor: public SSLClientContext(SecureRandom random) Suppose, we have created a new Random (or SecureRandom) object serving as our specific random number generator. Instead of using the SecureRandom default empty constructor, we assume that we have implemented our own seed generation algorithm for seeding the SecureRandom object: import java.security.*; import java.util.random;... byte[] seed = derived from some particular seed generation algorithm; SecureRandom randomgenerator = new SecureRandom(seed); Following this, we directly supply the self-designed random number generator when creating the SSLClientContext object: SSLClientContext context = new SSLClientContext(randomGenerator); Note, that we could use the setrandomgenerator(...) method for defining a specific random generator. However, we will prefer to set a self-designed random number generator directly when creating the context object, since first time-consuming creating the default generator by using the default SSLClientContext constructor and subsequently overwriting the just created generator by the new one, will cost a superfluous amount of time. For later obtaining actual - default or user defined - random number generator from the context, we may use the getrandomgenerator method: Random randomnumbergenerator; RandomNumberGenerator = context.getrandomgenerator(); Keep in mind that the same proceeding has to be used when supplying a self-designed random number generator for a SSLServerContext object:... SSLServerContext servercontext = new SSLServerContext(randomGenerator); 43

44 SSLContext... Random randomnumbergenerator; RandomNumberGenerator = servercontext.getrandomgenerator(); When first invoking the - default or supplied by a self-designed random number generator - SSLClientContext constructor, all the other properties (enabled cipher suites and compression methods, session manager and trust decider) of the new created SSLClientContext object are initialized with default settings that later may - or may not - be actualized by particular user settings Enabled Cipher Suites At the beginning of the lifetime of a SSLClientContext object, the constructor enables all the cipher suites implemented by isasilk. Remember, that isasilk implements all the SSLv3 cipher suites except for Fortezza (see 1.1.1). Every single cipher suite defines a specific key exchange algorithm, symmetric encryption algorithm and a secure hash function (see 1.1.1). Client and server have to agree on one particular cipher suite that is supported by both of them. This negotiated cipher suite is called active cipher suite and decisively determines the handshake process. An active cipher suite is selected among the enabled cipher suites that are common for both, SSL client context and SSL server context. An enabled cipher suite is a cipher suite that is supported by the actual SSLContext object (respectively SSLSocket object supplied by the context object). If an application doesn t want - or is not able - to support all the possible cipher suites, it has the ability to rearrange the default settings after it has created the particular SSLContext object. Since the enabled cipher suites are defined as an array of cipher suites within the SSLClientContext class implementation, we also have to define an array of cipher suites every time we want to actualize the enabled cipher suites of a context object - even if we only want to enable one single cipher suite: //enabled_cipher_suites as an array of cipher suites in SSLClientContext class: CipherSuite[] enabled_cipher_suites; Unlike defining a specific random number generator as described in the previous section, we cannot directly enable particular cipher suite(s) by means of one of the two SSLClientContext constructors. Rather we have to make use of the SSLClientContext s setenabledciphersuites(ciphersuite[] enabledciphersuites) method. Supposing we intend to only enable the two cipher suites SSL_RSA_WITH_IDEA_CBC_SHA and SSL_DH_DSS_WITH_DES_CBC_SHA, we first have to declare an array for being able to hold two cipher suites: 44

45 SSLContext CipherSuite[] cs = new CipherSuite[2]; Following this, we will fill the array with our two particular cipher suites and then supply it to the actual context object: cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DHE_DSS_WITH_DES_CBC_SHA; //enable the cipher suites context.setenabledciphersuites(cs); Automatically two CipherSuite objects are created and supplied with the particular parameter values for implementing the SSL_RSA_WITH_IDEA_CBC_SHA respectively SSL_DHE_DSS_WITH_DES_CBC_SHA cipher suites. The two cipher suites are assigned to the cs array. For obtaining all the actually enabled cipher suites of a particular context object, we may utilize the context s getenabledciphersuites() method. If we, for instance, are interested in the names of the enabled cipher suites, we may query them by the following lines of program code: CipherSuite[] encs = context.getenabledciphersuites(); System.out.println("Enabled cipher suites:"); for (int i = 0; i < encs.length; i++) { System.out.println("cipher suite no. "+ i +": " + encs[i].getname()); First we have defined a cipher suite array of an unspecified length and filled it with all the enabled cipher suites by calling the getenabledciphersuites()method of the actual context object. Then we have stepped through the array thereby printing the name of each cipher suite we have been passing by. The name of a specific cipher suite object is obtained by using the getname() method of the CipherSuite class. So far we have learned enough for enabling particular cipher suites, or making use of all the implemented cipher suites by only creating a default SSLClientContext object. Furthermore, we are able to obtain the enabled cipher suites of a context object. Now we want look somewhat behind the isasilk cipher suite implementation. Perhaps you will skip this section and directly go to the discussion of compression methods ( ) or session manager ( ). The basic class throughout isasilk s cipher suite environment is the CipherSuite class: public class CipherSuite A particular CipherSuite object cannot be created by directly calling a constructor. Rather the name of the specific cipher suite has to be used: 45

46 SSLContext CipherSuite cipher_suite = CipherSuite.name_of_CipherSuite Since isasilk implements all the SSLv3 cipher suites (except for Fortezza) any known cipher suite name may be set for name_of_ciphersuite. Automatically a new CipherSuite object is instantiated and supplied with all the parameter values that are necessary to implement the particular cipher suite. The constructor of the CipherSuite class itself is declared as private forbidding to call it from outside the CipherSuite class: private CipherSuite(String ciphersuitename, String cipheralgorithm, int id1, int id2, int keymaterial, int expandedkeymaterial, int IVSize, boolean isexportable, boolean implemented) where: ciphersuitename... the name of the particular cipher suite cipheralgorithm... the name of the symmetric cipher of this suite id1, id2... a two byte identifier of this cipher suite keymaterial... the number of bytes from the key block that are used for generating the write keys expandedkeymaterial... the number of bytes actually fed into the encryption algorithm IVSize... the number of bytes of the initialization vector for running the symmetric cipher in CBC mode isexportable... is this cipher suite exportable? implemented... is this cipher suite already implemented by isasilk? (false for Fortezza, true for all others) Now, what really happens when we wish to create a SSL_RSA_WITH_IDEA_CBC_SHA cipher suite object by writing CipherSuite cipher_suite = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA within our SSLClient (or SSLServer) implementation? Let s take a look inside isasilk s CipherSuite class where the desired cipher suite object is instantiated by calling the private CipherSuite constructor and providing it with the particular parameter values: public static final CipherSuite SSL_RSA_WITH_IDEA_CBC_SHA = new CipherSuite("SSL_RSA_WITH_IDEA_CBC_SHA", "IDEA.CBC.SSL", 0x00, 0x07, 16, 16, 8, false, true); 46

47 SSLContext By means of this lines of program code actually a CipherSuite object is created that is ready for supporting the SSL_RSA_WITH_IDEA_CBC_SHA cipher suite using RSA for key exchanging, SHA for MAC computation, and a 128 bit key for data encrypting with IDEA in CBC mode. The CipherSuite class is equipped with a variety of methods for querying for specific information about a cipher suite object. So, for instance, you may be interested in the cipher suite object s name, it s ID, cipher algorithm and key exchange algorithm. Maybe, for some purpose you only wish to know whether the symmetric cipher is a block or stream cipher making it necessary to ask for the corresponding information. All this is done by using the several get* methods of the CipherSuite class. Presuming the existence of some cipher suite object with name c_s, we may get particular information by typing: // get the cipher type (STREAM = 1, BLOCK = 2) int ciphertype = c_s.getciphertype(); // get the name of the encryption algorithm String cipher_alg = c_s.cipheralgorithm(); // get the name of the MAC algorithm String mac_alg = c_s.macalgorithm(); // get the name of the key exchange algorithm String kex_alg = c_s.getkeyexchangealgorithm(); // ask, if cipher suite is exportable boolean export = c_s.isexportable(); // get the key size limit for certificate int limit = c_s.getkeysizelimit(); // get the hash size for message digests int hashsize = c_s.hashsize(); // get the number of bytes used for generating the write keys int keymaterial = c_s.keymaterial(); // get the number of bytes actually fed into the encryption algorithm int exp_keymaterial = c_s.expandedkeymaterial(); // get the the number of bytes used for the initialization vector int ivsize = c_s.ivsize(); For obtaining all the cipher suites implemented by isasilk, the CipherSuite class provides the getdefault() method returning an array of all the cipher suites that actually are implemented. This method is used by the constructor of the SSLClientContext object for initially enabling all the implemented cipher suites when a new SSLClientContext object is created: CipherSuite[] enabled_cipher_suites; enabled_cipher_suites = CipherSuite.getDefault(); Since getdefault() is a static method, no extra CipherSuite object must be created for accessing all the implemented cipher suites. Remember that you have to take care for providing several certificate types and cryptographic keys/parameters if your SSLClient (respectively server) implementation 47

48 SSLContext shall be able to correctly support any desired cipher suite type (consult chapter 1.1.1, table 1.2 in particular). On the server side of the connection, certificates and keys/parameters are managed by directly binding them to the specific context object (see chapter 3.3.2), on the client side a trust decider has to be implemented for managing certificate requests coming from the server (see section ). A server also may force a cipher suite renegotiation any time during the actual clientserver communication to determine a new cipher suite for the current session (see section ). Similarly to the negotiation of a specific cipher suite, client and server also have to agree upon a particular compression method defining the algorithm for compressing the data records of the current session. Since data compression is an optional task and generally yet not done by SSLv3, the next chapter only gives a short description about setting and getting the actual compression method of a context object Enabled Compression Methods The basic concept for managing the compression methods within the isasilk SSLv3 environment resembles the cipher suite management system. Again, when a SSLClientContext object is created the first time, per default all implemented compression methods are enabled by the SSLClientContext constructor in calling the getdefault() method of the CompressionMethod class of the iaik.security.ssl package. CompressionMethod[] enabled_compression_methods; enabled_compression_methods = CompressionMethod.getDefault(); Since currently the only defined compression method of SSLv3 is the NULL method, meaning that none compression is performed on the data records, the only compression method that can be returned by the CompressionMethod.getDefault() method also is the NULL method. However, each application may add compression methods as needed. New compression methods have to be registered within the compression methods repository which is maintained by the abstract CompressionMethod class of the iaik.security.ssl package. Each particular compression method wishing to be registered must extend the CompressionMethod class by implementing the following abstract methods: /** * Returns the name of the compression method. * the name of thise compression method */ public abstract String getname(); 48

49 SSLContext /** * Returns the identifier of the compression method. * the identifier of the compression method */ public abstract int getid(); /** * Performs the compress operation. Implemented by a subclass. * in the byte array holding the data to be processed inoff the offset indicating the start position within the * in byte array inlen the number of bytes to be processed out the byte array for holding the result outoff the offset indicating the start position within the * out byte array the number of bytes that are stored in the out byte array */ public abstract int compress(byte[] in, int inoff, int inlen, byte[] out, int outoff) throws DataFormatException; /** * Performs the decompress operation. Implemented by a subclass. * in the byte array holding the data to be processed inoff the offset indicating the start position within the * in byte array inlen the number of bytes to be processed out the byte array for holding the result outoff the offset indicating the start position within the * out byte array the number of bytes that are stored in the out byte array */ public abstract int decompress(byte[] in, int inoff, int inlen, byte[] out, int outoff) throws DataFormatException; The getname() and getid() methods provide information about the particular compression method, compress(...) and decompress(...) actually implement the specific compression/decompression algorithmus. For registration purposes it is important that each particular compression method implementation includes the empty default constructor! For providing an example on how to implement a compression method, the demo.compression package of the isasilk demo library contains a sample class - called XorCompression - which actually does not perform any compression at all, but only - for the purpose of demonstration - performs a simple XOR operation with a predefined value (0xAA) 1 : 1 Note that each compression method is assigned a specific ID (0 in the case of the NULL method). So, choose arbitrary compression method IDs only for the purpose of testing. In the future - when other compression methods will be defined beside the NULL method - consult the corrresponding documentation for assigning the right predefined ID. 49

50 SSLContext package demo.compression; import iaik.security.ssl.*; /** * This class shows an example of how to implement a compression * method. This demo does not really compress the content; it just * performs a XOR operation with a defined value (0xAA). */ public class XorCompression extends CompressionMethod { // the name of this compression method private final static String name = "XOR Compression Demo"; // the id of this compression method private final static int id = 0x80; // the byte to xor the data with private final static byte xor = (byte)0xaa; /** * Default Constructor. Needed for registration. */ public XorCompression() { /** * Returns the name of this compression method. */ public String getname() { return name; /** * Returns the identifier of this compression method. */ public int getid() { return id; /** * Performs a simple XOR operation. * in the byte array holding the data to be processed inoff the offset indicating the start position within the * in byte array inlen the number of bytes to be processed out the byte array for holding the result outoff the offset indicating the start position within the * out byte array the number of bytes that are stored in the out byte array */ public int compress(byte in[], int inoff, int inlen, byte out[], int outoff) { for (int i=0; i<inlen; i++) out[outoff+i] = (byte)(in[inoff+i] ^ xor); 50

51 SSLContext return inlen; /** * Performs a simple XOR operation. * in the byte array holding the data to be processed inoff the offset indicating the start position within the * in byte array inlen the number of bytes to be processed out the byte array for holding the result outoff the offset indicating the start position within the * out byte array the number of bytes that are stored in the out byte array */ public int decompress(byte in[], int inoff, int inlen, byte out[], int outoff) { for (int i=0; i<inlen; i++) out[outoff+i] = (byte)(in[inoff+i] ^ xor); return inlen; For actually registering the new compression method, just call the default constructor: new demo.compression.xorcompression(); After registering a new compression method, it has to be added to the set of enabled compression methods. An enabled compression method is a compression method that is supported by the actual SSLContext object (respectively SSLSocket object supplied by the context object). Both, client and server have to agree upon one of the enabled compression methods to define the active compression algorithm that is used for data record compression during the current session. As already accustomed from the cipher suite management system, a particular compression method may be supplied to the actual context object by using the setenabledcompressionmethods(compressionmethod[] enabledcompmeths) method. So, for instance, for enabling the NULL and XOR compression methods, we only have to call getdefault() on the CompressionMethod class. Since both methods are already registered - the one per default and the other by explicitly calling its constructor above - getdefault() will return both methods: //get the registered compression methods CompressionMethod[] cm = CompressionMethod.getDefault(); //enable the compression methods by supplying it to the //context context.setenabledcompressionmethods(cm); 51

52 SSLContext Note the kind of redundancy in the code sample from above: when creating a new SSLClient(Server)Context object, the corresponding constructor automatically will enable all registered compression methods by implicitly calling the getdefault() method of the CompressionMethod class. However, an application may use the setenabledcompressionmethods method for changing the default setting after creating a SSLContext! To obtain the enabled compression methods of a context object, we may use the getenabledcompressionmethods() method: CompressionMethod[] enabled_compressionmethods = context.getenabledcompressionmethods(); Every single CompressionMethod object is identified by a specific name and a particular ID that may be queried by the getname() respectively getid() methods. Supposing that cm denotes a CompressionMethod object, we may write: String name = cm.getname(); int id = cm.getid(); The cipher suite and compression method actually used for a particular session are defined by the active cipher suite respectively active compression method. Active cipher suites and compression methods are kept in mind for a particular time interval, making it possible to be reused within a later session. It is the responsibility of the implemented session manager to determine the session caching strategy. The session manager will be introduced within the following chapter The Session Manager When client and server start a new communication, they may negotiate completely new cryptographic parameters or they may agree on specifications they already have used throughout a previous session or throughout another session that temporary is active. If the client - that usually initiates a handshake dialogue - intends to rely on the security specifications of some former or existing session, it may suggest this the server by sending the SessionID of the particular session in mind. If the server accepts the client s proposal, it answers by resending the same SessionID. Following this, client and server perform a shortened handshake process for generating keys for data encryption and MAC calculation based on the same cipher suite and master secret that already have been used during the session identified by the specific SessionID. However, if the server for some reason is not willing to reestablish a connection suggested by the client, it refuses the client s proposal by creating and resending an entire 52

53 SSLContext new session identifier. In this case client and server have to go through a complete handshake dialogue for negotiating the cryptographic specifications of the new session. For being able to support the reuse of former security negotiations, both communication partners have to implement some kind of session caching management. Within the isasilk environment the session caching management is done by means of four classes leaving some scope for the user to implement her/his own session caching strategy: public class SessionID public class Session class for implementing a session identifier as an arbitrary byte sequence generated by the server for identifying some active session or some session to be resumed class for implementing a session object responsible for holding all the information that is necessary for resuming an old session public interface SessionManager interface of abstract methods for providing the user a template for implementing his own session caching strategy public class DefaultSessionManager implements SessionManager class for providing a simple example of an actual session manager implementation; an application may rely on this default session manager or it may implement its own session manager; During the SSLClient introduction within chapter 3.2 it has been described how to open a SSLClientSocket object and subsequently open an output respectively input stream for enabling the writing/reading to/from the SSL socket: SSLSocket s = null; // create a SSLClientContext object SSLClientContext context = new SSLClientContext(); // create a SSLSocket object for connecting to the specified // server on the specified port number s = new SSLSocket(serverName, serverport, context); // open output/input streams to write/read to/from the socket PrintWriter os = new PrintWriter(s.getOutputStream()); DataInputStream is = newdatainputstream(s.getinputstream()); When opening an stream on the socket object, the socket class getoutputstream(), respectively getinputstream() method starts the handshake dialogue by calling the socket s starthandshake() method which itself invokes the handshaker by means of the dohandshake() message. The Handshaker class is an abstract isasilk class that is extended by the Client- respectively ServerHandshaker for directing the initial handshake dialogue. Client and ServerHandshaker are instantiated by the appropriate constructor when creating a SSLClientSocket respectively SSLServerSocket object. 53

54 SSLContext Since we are located at the client s side of a SSL connection to be established, the (client)handshaker first has to query if there already has been any communication session with the server identified by its Inet address. Therefore the handshaker makes a call to the proper session manager: Session session; session = context.getsessionmanager().getsession(socket, null); The session manager itself makes use of its getsession(sslsocket socket, SessionID sessionid) method to search the session cache for any session that matches to the inet address of the server. It is the responsibility of the actually implemented session manager to determine the searching strategy for cached sessions. Since the default session manager stores sessions within a hashtable using the peer s address as key, the default session manager s getsession method is implemented to extract the inet address of the peer from the socket object that looks for a session: Session s = (Session)activeSessions.get(socket.getInetAddress()); Note, that since activesessions is an instance of the java.util.hashtable class, an explicit cast is necessary to obtain a Session object. If a corresponding session is detected, the session manager reports it to the handshaker that uses the session s inherent sessionid for suggesting the server to resume the particular session (see illustration of figure 3.1). 54

55 SSLContext Client 1 connect to server 4 has there already been any session with this server? 2 Client Handshaker suggest server to resume a session identified by SessionID 3 have detected a former session with this server and report you corresponding SessionID Session Manager The Client orders its client handshaker to connect to a particular server. Before doing so, the handshaker asks the session manager to query the session cache if there already has been a session with this server. If the session manager detects a match in the cache, it reports the corresponding ID to the handshaker which suggets the server to resume this particular session. Figure 3.1: The Client Session Manager On the other side of the connection, when the server handshaker - responsible for directing the handshake on the server side - receives a client s Hello message including a particular sessionid, it also asks its session manager for searching the cache for containing any appropriate session (see figure 3.2). In contrast to the client session manager, the server session manager not only specifies the client s inet address - by extracting it from the supplied SLL socket object - when calling its getsession method. Since the server is interested in the one particular session the client has indicated by sending the appertaining sessionid, also this sessionid has to be specified: Session session; session = context.getsessionmanager().getsession(socket, ch.getsessionid()); Thereby ch denotes the received ClientHello message containing the particular sessionid. 55

56 SSLContext Server 2 Client wishes to resume a particular session 1 perform handshake with requesting client 5 tell client that session with Server Handshaker SessionID will be resumed have detected a former session with this client and this SessionID in the cache! 4 3 client has sent a particular SessionID for resuming a former session Session Manager The server session manager searches the cache for any session that has been held with the requesting client during the last resume period. If a match is found, a second comparison is necessary to ensure that the ID of the detected session actually matches to the SessionID received from the client. Figure 3.2: The Server Session Manager If the client has sent a Hello message without specifying any session identifier, the server has to create a entirely new session object with a new sessionid for identifying the new session. A whole handshake dialogue will be necessary to negotiate the security parameters. Now, after we have seen the general proceeding of session caching and searching, it s time to provide some guidelines for implementing one s own session manager. For that reason it would be advantageously to gain some basic understanding of isasilk s several session class implementations. The following sections first briefly introduce the isasilk classes SessionID, Session and SessionManager as fundamental preconditions for subsequently discussing a particular session manager implementation by means of the DefaultSessionManager class. 56

57 SSLContext public class SessionID The session identifier is used to identify a particular SSL session. ISaSiLk implements a session identifier as an arbitrary byte sequence, generally generated by the server for identifying some active session or some session to be resumed. However, a SessionID object also may represent an empty byte array as needed by the client when indicating the server to negotiate new security parameters. Since the client s Hello message has to include a session identifier, an empty SessionID object is transmitted if no particular session ID is available or the client intends to negotiate new security parameters. An object of the isasilk SessionID class may be created by means of the empty standard constructor or by providing some random seed. If the client, that searches the cache, doesn t find some appropriate session to be resumed, it creates a new session with an empty session identifier by using the standard sessionid constructor: //constructor for creating an empty session id: SessionID() If the server is motivated by the client to create a new session, or if the server refuses the client s proposal for agreeing on the security specifications of some former session, it creates a new session with a random seeded session identifier by using the second constructor of the SessionID class: //constructor for creating a random session id: SessionID(Random random) Once a SessionID object is created, it mainly will be used to identify some particular session within the session cache. Suppose, the server has received the client s Hello message containing the session ID of a specific session the client wishes to resume. Now the server charges the session manager to search the cache for this particular session. The default session manager uses the IP address of the peer (i.e. requesting client) as key for searching the session hashtable. If a match is found, the session identifier of the detected cached session has to be compared with the sessionid derived from the client. Note, that the default session manager only caches one session it has held with any particular peer. If there have been more than one sessions with the same peer during the last resume period, only the most recent session is kept in the cache. Notice the difference: the IP address of the peer is used to search the session cache. Only if a match is found, the sessionid is used to unmistakable identify the detected session as being the one the client wishes to resume. If an application intends to implement its own session manager, perhaps it may wish to cache all the sessions held with some specific peer during the last resume period. It also may use another hashing key than the IP address of the peer (for instance extended by a 57

58 SSLContext particular port number). The session manager (see ) provides a template giving the freedom to realize one s own session caching strategy; the default session manager (see ) only is one basic example of a simple session caching policy. In either case, there will be need for some utility to compare sessions for having the same or different session identifiers. The SessionID class provides a equals(..) method for comparing a SessionID object with another SessionID object: //method for comparing with another session identifier: public boolean equals(object object) The SessionID class equals method is used by the default session manager s getsession method for uniquely identifying a particular session derived from the session cache (see ). For providing the possibility to use SessionID objects as keys for storing session objects within a hashtable object of the java.util package, additionally the SessionID class has to support an implementation of the hashcode method of the java.lang.object class: //Creates an integer suitable for hash table indexing public int hashcode() You may ask yourself, why not using the SessionID immediately as key for caching respectively searching for sessions? The answer is, that the client - when initiating a connection to a particular server - first looks into the session cache if there has been any session with this server during the last resume period. If a match is found, the client gets the corresponding sessionid from the cache for reporting it the server. When starting the search, the client doesn t know any sessionid, and it cannot use something as search key that it doesn t know of! Since it knows the peer s IP address, this address can be serve as search key. Since per default client and server implementations use the same default session manager, sessions are also cached on the server s side by using the peer s IP address as key. Maybe an application wishes to implement different session caching strategies for server respectively client and directly use the sessionid as caching and searching key on the server s side. The following section introduces the Session class providing the data structures and methods for holding and obtaining all the information that is required to keep in mind for being able to resume a previous session public class Session In order to enable the resuming of some former session without performing a complete handshake dialogue again, all the security specifications that are typically associated with a session have to be kept in mind: negotiated cipher suite and compression method, peer certificate chain and generated master secret. 58

59 SSLContext All the information is collected within a special container. For every single session another container has to be used to keep the parameters of this session. In order to distinguish the several containers, each container is labeled with an etiquette uniquely identifying the particular container. Additionally, each container is provided with a time stamp indicating the moment it has been put into the container depot. Within the isasilk SSLv3 implementation, containers are created as instances of the Session class and the etiquette of a particular container corresponds to the SessionID of the particular session object (see ). As containers are kept within the container depot sessions are stored within the session cache. The time stamp indicates the creation time of a session object and is used to remove sessions that are longer in the cache than allowed by the actual resume period. The management of the session cache is devolved on the implemented session manager (see ) which per default is the default session manager (see ). The Session class provides two constructors for creating a new session object. The standard empty constructor creates a session object with an empty session identifier and may preferably be used by the client leaving the server the task to create a new random session id: //constructor for creating a new session with an empty session id: Session() On the other side of the connection, the server has to use a random number generator for seeding the second session class constructor to create a session with a new random session identifier: //constructor for creating a session with a new random session id: Session(Random random) For implementing your own session manager, you may take use of the Session class several service methods for accessing the entities of a particular session object: //Get the ID of this session public SessionID getid() //Get the creation time of this session public long getcreationtime() //Get the peer s certificate protected SSLCertificate getpeercertificate () //Get the master secret protected byte[] getmastersecret() //Get the negotiated cipher suite of this session protected CipherSuite getciphersuite() //Get the compression method of this session CompressionMethod getcompressionmethod() 59

60 SSLContext Furthermore, the Session class provides a special method for obtaining a string representation of all the entities collected within a particular session object: //Get a string representation of this session public String tostring() A call to this method may, for instance, print out the following information held by a specific session object: Peer Certificate: C=AT, O=IAIK, CN=atlas, OU=DH Server Certificate Resumeable: no Creation time: Cipher suite: SSL_DH_RSA_WITH_DES_CBC_SHA Compression method: NULL SessionID: fffffeee Several sessions may be created during multiple client-server connections. It is the responsibility of the implemented session manager to decide how to cache and manage the corresponding session objects holding the security parameters that are required to resume some session. The following section describes the session manager interface providing a template for the user to implement her/his own session caching policy. Subsequently, the default session manager introduction gives an example for a simple session manager implementation public interface SessionManager To continue the example comparing a session object with a container for holding all the security parameters that are required for resuming a session, we have to decide how to manage all the containers respectively session objects that may appear during a client/server communication. The particular caching strategy is left to the user; the SessionManager interface only predicts two abstract methods, one for caching sessions and one for obtaining sessions from the cache. Each class that implements the session manager interface at least has to support implementations for these two methods: /** * Add this session to the session cache. * socket the ssl socket which wants to cache this session session the session to cache */ public void cachesession(sslsocket socket, Session session); 60

61 SSLContext /** * Get a session from the session cache. * socket the SSL socket which wants to look for a session sessionid a SessionID or <code>null</code> * null if the session is not in the cache or the SessionManager wont resume this * session; the cached session otherwise */ public Session getsession(sslsocket socket, SessionID sessionid); Notice that both methods are parameterized with the SSLSocket object that wants to look for a session. From the supplied socket object the implemented session manager may get the information serving as key for putting a session object to the cache or searching for a specific session in the cache. The default manager, who manages the session caching for the server as well as for the client, depicts the peer s IP address from the socket object and stores sessions in a hashtable by using this IP address as key index. You may rely on the default session manager or you may implement your own session caching strategy, perhaps using some other keying system. You also may implement two separate session managers, one for the client and one for the server, that use different policies. The following section discusses the default session manager that may be used as an example for implementing a session manager. Before doing so, we should introduce the two methods of a SSLClientContext (respectively SSLServerContext) class that are necessary to bind (set) a specific session manager implementation to a context object, and to obtain (get) the actual session manager from a context object: //get the actual session manager of this context object public abstract SessionManager getsessionmanager(); //set the session manager for this context object public abstract void setsessionmanager(sessionmanager sessionmanager); public class DefaultSessionManager implements SessionManager Per default, the isasilk SSLv3 implementation uses one single default session manager to manage both, the client s session caching as well as the server s session caching. This section describes the default session manager by a step-by-step walk through the corresponding program code. Before going into details, we will think of the tasks the default session manager shall be able to handle: 61

62 SSLContext Putting some session to the session cache Getting some session from the session cache Removing some session from the session cache if already too long in the cache If we assume to provide one method for each specific task, our default session manager at least will contain three methods. For their specific implementations we first have to agree about the storage medium we will use to cache the session objects. The default session manager uses the Hashtable class of the java.util package as session cache. A hashtable can be imagined as an storage medium that uses some kind of key for locating a particular object within the storage. The key serves as index to the hashtable. Any object that is not the null object may be used as key for a hashtable, presuming that the corresponding key class supports implementations of the hashcode and equals methods of the java.lang.object class for generating and comparing hashtable indices. Each Hashtable object is characterized by a specific capacity and a specific load factor that can be set when creating a new instance of the Hashtable class. The load factor value should be chosen to lie between 0.0 and 1.0. However, one may rely on the default settings by using the standard constructor which sets the capacity to 101 and the load factor to At every stadium of the lifetime of an hashtable object the actual capacity of the hashtable is controlled to not exceed the product of load factor and current capacity, causing an automatically resizing of the hashtable s total capacity. Since this controlling and increasing process will claim for some time, it may be preferable to specify some larger load capacity and load factor already at the beginning when creating the hashtable object to reduce the number of times the hashtable has to be resized. Since for our demonstration purposes we don t expect too much net traffic, we will implement the session cache as hashtable with default load capacity and load factor: Hashtable activesessions; //repository for the cached sessions activesessions = new Hashtable(); Since sessions should be kept in the cache only for a certain time period, we have to determine a particular resume period value. Every time an access is made to the cache, the cache has to be checked for sessions to be removed because already exceeding the defined resume period. We voluntary decide to set the resume period to 2 hours meaning that a session has to be removed from the cache when its creation time dates back more than two hours: long resumeperiod; //after this time a session is removed from the cache resumeperiod = 1000*60*60*2; //resume period in milliseconds For statistical purposes we also introduce a counter indicating the number of sessions that have been removed from the cache since the cache hashtable has been created: 62

63 SSLContext int removed; //number of removed cache entries removed = 0; Now we are ready to implement the constructor of our default session manager. Since the isasilk SSLContext object only supports a SessionManager object, but the default session manager is an specific implementation of the session manager interface, we will use a private constructor that only may be called inside the DefaultSessionManager class. For enabling access to the new created default session manager object from outside the class, we provide a special factory method that returns the new created default session manager object as session manager implementation: static SessionManager session_manager; //the session manager static { session_manager = new DefaultSessionManager(); //Return one session manager for all SSLSockets. public synchronized static SessionManager getmanager() { return session_manager; Hashtable activesessions; // repository for the cached sessions long resumeperiod; // after this time a session is removed // from the cache int removed; // number of removed cache entries //Create only one session manager for all SSLSockets. private DefaultSessionManager() { activesessions = new Hashtable(); resumeperiod = 1000*60*60*2; // 2 hours removed = 0; off = false; Note that we have defined the session manager to be a static instance since we only will need one single session manager throughout the client s (respectively server s) lifetime. The first time the getmanager() method is called from outside the DefaultSessionManager class by writing SessionManager session_manager; session_manager = DefaultSessionManager.getManager(); an instance of the DefaultSessionManager class is created. Every further call of the getmanager() method will access this one particular instance and not create a new session manager object. The getmanager() method additionally is defined to be synchronized forbidding more than one access at a time. The next task is to implement a method for putting a session into the session cache. Since the session cache is implemented as a hashtable, we make use of the Hashtable 63

64 SSLContext class put method for adding the new session. As index key for the hashtable serves the Inet address of the peer which is extracted from the socket object that wants to cache the session: /** * Put a session into the session cache. * socket the SSL socket which wants to cache this session session the session to cache */ public void cachesession(sslsocket socket, Session session) { deleteoldsessions(); activesessions.put(socket.getinetaddress(), session); Since we decided to remove all sessions that exceed the resume period every time when accessing the cache, we also have to check the cache for sessions to be deleted when we want to add a new session. Old sessions are removed by means of the deleteoldsessions() method: //Delete sessions which are longer in cache than resume period private void deleteoldsessions() { long time = System.currentTimeMillis(); for (Enumeration e = activesessions.keys(); e.hasmoreelements();) { Object key = e.nextelement(); Session s = (Session)activeSessions.get(key); if (time - s.getcreationtime() > resumeperiod) { activesessions.remove(key); removed++; First the current time (in milliseconds) is evaluated. Then the session cache hashtable is searched key by key. For every key the corresponding session object is obtained from the hashtable. Note that an explicit cast is necessary to derive a session object from the Hashtable get(key) method which per default returns an generalized Object instance. For each session the getcreationtime() method returns the time (in milliseconds) the particular session object has been created. If the session s creation time dates back more than the resumeperiod value, the corresponding session is removed from the cache. After providing methods for putting sessions into the cache and deleting old sessions from the cache, the remaining task is to implement a method for getting sessions from the cache. Since both, client and server shall be able to use the default session manager, we must consider client accesses as well as server accesses. The template for the getsession(..) method is already predicted by the SessionManager interface: 64

65 SSLContext public Session getsession(sslsocket socket, SessionID sessionid); The default manager uses the Inet address of the peer as key for searching the session cache hashtable. This address is extracted from the socket that wants to search the cache and that is supplied the getsession() method as first parameter object : Session s = (Session)activeSessions.get(socket.getInetAddress()); After a particular session is derived from the cache, the further proceeding has to incorporate client as well as server requests. A client may call the getsession(..) method to ask if there is any session in the cache that has been held with the particular server identified by the server s Inet address. Therefore the client may not specify any session identifier when calling the getsession(..) method: Session session; session = context.getsessionmanager().getsession(socket, null); On the other side, the server when receiving a particular session identifier from the client indicating some session to be resumed, searches the cache for any session that exactly matches to the specified session id. The server therefore has to supply the session identifier when calling the getsession(..) method. Session session; session = context.getsessionmanager().getsession(socket, session_id); When an appropriate session - matching the server s Inet address - has been found in the cache after a client s inquiry, the getsession(..) method immediately can return the session. Note that a client s call to the getsession method is marked by a null SessionID: Session s = (Session)activeSessions.get(socket.getInetAddress()); if (sessionid == null) return s; When an appropriate session - matching the client s Inet address - has been found in the cache after a server s inquiry, this session first has to be compared with the SessionID the client has sent. If the two session identifiers are identical, the session derived from the cache may be resumed and can be returned by the getsession method. Before comparing the two session identifiers, we first have to ensure, that there has been detected any session in the cache that matches to the client s Inet address. Otherwise an error may occur: 65

66 SSLContext Session s = (Session)activeSessions.get(socket.getInetAddress()); if (s!= null) { if (sessionid.equals(s.getid())) return s; And finally, the getsession method may get a session from the cache that matches to the client s Inet address, but not to the session identifier the client has sent. Since this session is not of interest, the getsession method removes it from the cache and returns the null object indicating the server to create a complete new session object: activesessions.remove(socket.getinetaddress()); return null; Remember, that before searching the cache, all sessions have to be removed which are longer in the cache than allowed by the resume period. This may lead to the following getsession implementation within the default session manager class: /** * Returns a session form the cache. socket the SSL socket which wants to look for a session sessionid the ID of the session which should be resumed * or null if this method is called by a SSL client. * the session from the cache or null */ public Session getsession(sslsocket socket, SessionID sessionid) { deleteoldsessions(); //search the cache for a session that matches the peer s //InetAddress Session s = (Session)activeSessions.get(socket.getInetAddress()); //if client request or no proper session in cache if (sessionid == null s == null) return s; //if server request check, for ID match if (sessionid.equals(s.getid())) return s; //if InetAddress match, but no ID match activesessions.remove(socket.getinetaddress()); return null; After successfully implemented our three basic methods for putting sessions to the cache, and deleting or getting sessions from the cache, additionally we will provide a possibility for querying and changing the resume period from outside the default session manager class: 66

67 SSLContext /** * Set the resume period of cached sessions. * period the resume period in seconds */ public void setresumeperiod(long period) { resumeperiod = period*1000; /** * Return the resume period of this session manager. * the resume period in seconds */ public long getresumeperiod() { return resumeperiod/1000; Now we are ready to put all together for realizing our default session manager implementation. Perhaps it would be advantageously to include some kind of switch making it possible to enable respectively disable the session manager for some reason. Suppose you wish to test the correct working of all the implemented cipher suites. For continuously testing one cipher suite after the another throughout one single program execution (take a look at the demo CipherSuiteTest source code), it may be useful to switch of the session manager for disabling any kind of session caching. import java.util.*; import java.net.inetaddress; public class DefaultSessionManager implements SessionManager { static SessionManager session_manager; // the session manager static { session_manager = new DefaultSessionManager(); /** * Return one session manager for all SSLSockets. * the session manager */ public synchronized static SessionManager getmanager() { return session_manager; Hashtable activesessions; // repository for the cached sessions long resumeperiod; // after this time a session is removed // from the cache 67

68 SSLContext int removed; boolean off; // number of removed cache entries // useful when testing different cipher suites // Create only one session manager for all SSLSockets. private DefaultSessionManager() { activesessions = new Hashtable(); resumeperiod = 1000*60*60*2; // 2 hours removed = 0; off = false; /** * Disables or enables the DefaultSessionManager. * on true to enable the DefaultSessionManager * false to disable the DefaultSessionManager */ public void enable(boolean on) { off =!on; // Set the resume period of cached sessions. public void setresumeperiod(long period) { resumeperiod = period*1000; // Get the resume period of this session manager. public long getresumeperiod() { return resumeperiod/1000; // Put a session into the session cache. public void cachesession(sslsocket socket, Session session) { if (off) return; deleteoldsessions(); activesessions.put(socket.getinetaddress(), session); // Get a session form the cache. public Session getsession(sslsocket socket, SessionID sessionid) { if (off) return null; deleteoldsessions(); //search the cache for a session that matches the peer s //InetAddress Session s = (Session)activeSessions.get(socket.getInetAddress()); // if client request or no proper session in cache if (sessionid == null s == null) return s; 68

69 SSLContext // if server request, check for ID match if (sessionid.equals(s.getid())) return s; // if InetAddress match, but no ID match activesessions.remove(socket.getinetaddress()); return null; // Deletes sessions which are longer in cache than resume period. private void deleteoldsessions() { long time = System.currentTimeMillis(); for (Enumeration e = activesessions.keys(); e.hasmoreelements();) { Object key = e.nextelement(); Session s = (Session)activeSessions.get(key); if (time - s.getcreationtime() > resumeperiod) { activesessions.remove(key); removed++; /** * Get some statistics about the sessions cache. * a string representation of some statistics */ public String tostring() { StringBuffer buf = new StringBuffer(); if (off) buf.append("defaultsessionmanager disabled.\n"); else { buf.append("defaultsessionmanager ensabled:\n"); buf.append("sessions in cache: "+activesessions.size()+"\n"); buf.append("removed sessions: "+removed+"\n"); return buf.tostring(); You also may get a demo version of this default session manager - called DemoSessionManager - in your isasilk demo directory. If you have implemented your own session manager - let s call it MySessionManager - you have to incorporate it into the actual context object by using the setsessionmanager(..) method of the SSLContext class: SessionManager manager = MySessionManager.getManager(); context.setsessionmanager(manager); 69

70 SSLContext To obtain the actually installed session manager from the context object, use the getsessionmanager() method. Suppose, the default session manager is the active session manager of the current context object and you intend to change the resume period to one hour. Remember that the setresumperiod(..) method expects to specify the time value in seconds: DefaultSessionManager session_manager; session_manager = (DefaultSessionManager)context.getSessionManager(); session_manager.setresumeperiod(60*60); Note that an explicit cast to DefaultSessionManager is necessary since getsessionmanager() returns a SessionManager object that doesn t support the setresumeperoiod method. After this expensive discussion of the session caching management, we can proceed to the next - an already last - part of the SSLCLientContext introduction - the trust decider class The Trust Decider The TrustDecider interface provides the user a template of abstract methods for implementing her/his own policy for trusting or rejecting a certificate that has been sent from the peer. On the client s side, additionally the trust decider has to supply the client handshaker with certificates and keys the client handshaker will need to satisfy a certificate request possibly coming from the server. If no trust decider is implemented, every certificate derived from the peer will be trusted. On the client s side the absence of a trust decider implementation additionally will lead to a No certificate warning indicating the server that the client is not able to suffer the server s certificate request. Simplified, the general proceeding during a handshake dialogue can be described as follows: The server handshaker, when receiving the certificate of the client, first checks if there is any trust decider implemented and incorporated into the server context. It therefore tries to extract the proper trust decider from the server context by calling the context s gettrustdecider() method: TrustDecider trust_decider = servercontext.gettrustdecider(); If no trust decider is returned by the gettrustdecider() method, either no trust decider is implemented at all, or no trust decider has been incorporated into the server 70

71 SSLContext context. In both cases, the gettrustdecider()method returns null and the client certificate is trusted per default. Otherwise, if the gettrustdecider() method actually returns a trust decider object, the server handshaker consults this trust decider to inquire whether the received client certificate should be trusted or not. If the trust decider accepts the client certificate, the handshake dialogue continues to the next stage. If the trust decider refuses the client certificate, a fatal bad certificate alert is triggered and the connection is closed with an untrusted certificate SSL exception. Somewhat different is the situation for the client handshaker. Of course, the client handshaker performs the same steps as described above for asking the client trust decider whether trusting a server certificate or not. However, it may be necessary for the client handshaker to consult the trust decider a second time if the server claims for a client authentication. In this case, the client handshaker first ensures that the trust decider responsible for dealing with certificate requests of the server, is implemented as instance of the ClientTrustDecider class (see ). If not, the connection is closed by an TrustDecider for client SSLSocket must be a ClientTrustDecider SSLException message. If the trust decider actually is a client trust decider, the client handshaker asks the trust decider to look for a proper certificate for suffering the server s certificate request. If the client trust decider cannot supply the required certificate, a No client certificate warning is sent to the server that thereupon has to decide whether closing the connection or accepting the anonymity of the client. Since the task of deciding whether the peer certificate has to be trusted or not, may be fulfilled by a particular server as well as client trust decider implementation, whereas the providing of certificates only has to be done by a client trust decider, we first will discuss a simple server trust decider implementation, followed by the introduction of the client trust decider. Basically, isasilk provides three interface classes leaving the user some scope for implementing her/his own certificate trusting policy: //interface of abstract methods to let the user implement her/his own certificate trusting policy public interface TrustDecider //interface for implementing a server trust decider public interface ServerTrustDecider extends TrustDecider //interface for implementing a client trust decider public interface ClientTrustDecider extends TrustDecider Unlike the session manager arrangement, where one single session manager implementation may be used for managing the session caching for both, client and server, isasilk demands on distinguishing between client trust decider and server trust decider implementation. Both interfaces, ClientTrustDecider and ServerTrustDecider extend the basic interface TrustDecider, but ClientTrustDecider is not a subclass of ServerTrustDecider, although in principle one may think that the ClientTrustDecider class extends the ServerTrustDecider class about the features necessary to get certificates enabling for client authentication. 71

72 SSLContext public interface TrustDecider The TrustDecider interface is the basic interface class of isasilk s trust decider architecture. It is already extended within the isasilk standard environment by the ServerTrustDecider respectively ClientTrustDecider interfaces which on their turn may be implemented by the user to realize her/his own certificate trusting policy. The TrustDecider interface only provides one single abstract method for deciding if the certificate sent from the peer is to be trusted or not. If the corresponding server (respectively) client handshaker successfully has ensured that a proper trust decider has been implemented and incorporated into the actual context object, it calls this method to check if the peer certificate is trustworthy: /** * Decides if the peer certificate is trustworthy or not. * certificate the SSLCertificate message containing the peer s certificate (list) true if the peer is trusted or false otherwise */ public abstract boolean istrustedpeer(sslcertificate certificate); If this method returns false, the handshaker terminates the connection with a fatal bad certificate error. Otherwise - if istrustedpeer returns true, the handshake dialogue proceeds to the next stage. Note that SSLCertificate represents a handshake message for transfering a certificate chain. Since istrustedpeer has to check the trustworthiness of the peer s X.509 certificate chain received with this SSLCertificate message, the certificate chain has to be "extracted" from the handshake message using the getcertificatechain() method of the SSLCertificate class: public X509Certificate[] getcertificatechain(); It should be emphasized that an application don t has to confirm with the conventional way of checking the trustworthiness of the peer certificate already during the handshake phase by calling the proper trust decider. Also the certificate may be checked at any later time during the client-server conversation. For obtaining the peer s certificate chain, the SSLSocket class provides the method getpeercertificatechain(): /** * Returns the certificate chain sent by the peer or null if the * peer has no certificate. * * X509Certificate[0] contains the peer certificate. * X509Certificate[len-1] contains the top CA certificate. * 72

73 SSLContext the certificate chain sent by the peer */ public X509Certificate[] getpeercertificatechain(); public interface ServerTrustDecider extends TrustDecider Since the only task of the server trust decider is to decide about the trustworthiness of the certificate derived from the client, the ServerTrustDecider interface is equipped with nothing but an empty body that may be filled by a specific server trust decider implementation of the user: public interface ServerTrustDecider extends TrustDecider { An implementation of the ServerTrustDecider at least has to contain an implementation of the basic istrustedpeer(sslcertificate certificate) method for deciding about the trustworthiness of the certificate sent by the client. For the purpose of illustration, we may implement a SampleServerTrustDecider class for checking the consistency of the X.509 certificate chain derived from the client. Therefore the istrustedpeer(..) method first shall print out the certificate chain and then call a separate verifycertificatechain(..) method for checking if the certificate is to be trusted (return true) or not (return false). Remember, that before calling the verifycertificatechain(..) method, we have to extract the X.509 certificate chain from the SSLCertificate message received from the client. If the client has not sent a certificate, the server handshaker calls the server trust decider s istrustedpeer(..) method without supplying a certificate chain. The server trust decider determines whether to accept the absence of a client certificate or not. In our example we will continue the handshake dialogue if the client doesn t fullfill a certificate request: /** * Shows the certificate chain sent by the client and * checks its consistency. * certificate the certificate message with the client * certificate list true, if the client certificate is trusted; false * otherwise */ public boolean istrustedpeer(sslcertificate[] certificate) { 73

74 SSLContext if (certificate == null) return true; // no certificate is o.k. // get the X.509 certifcate chain from the SSLCertifcate message X509Certificate[] CertChain = certificate.getcertificatechain(); debug("\nclient certificate chain:"); for (int i=0; i<certchain.length; i++) debug(certchain[i].getsubjectdn().tostring()); return verifycertificatechain(certchain); The verifycertificatechain(..) method checks the supplied X.509 certificate chain certchain (i.e. the certificate chain derived from the client), starting with the selfsigned top level CA certificate certchain[certchain.length-1] and leading to the actual client user certificate certchain[0]. For actually verifying each single certificate of the certificate chain to be checked, the verifycertificatechain(..) method makes calls to the verify(..) methods of the X509Certificate class of the iaik.x509 package. Thereby, the top level certificate is checked by using its inherent public key, and all the other certificates are verified by means of the public key belonging to the certificate located just one position higher in the certificate hierarchy. If an error is detected during the checking procedure, the client s certificate will be refused by an fatal bad certificate alert: /** * Verifies a certificate chain. the certificate chain to verify true if the certificate chain is o.k., false otherwise */ public boolean verifycertificatechain(x509certificate[] chain) { int len = chain.length; try { chain[len-1].verify(chain[len-1].getpublickey()); //TOP LEVEL for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getpublickey()); catch (Exception ex) { return false; return true; The whole SampleServerTrustDecider class implementation also includes a debug method for printing information onto the screen if the constructor is supplied with the boolean true value: import java.security.cert.x509certificate; import iaik.security.ssl.*; public class SampleServerTrustDecider implements ServerTrustDecider { boolean debug; 74

75 SSLContext /** * Create a SampleServerTrustDecider. * printdebuginfo if true debug information is printed to * System.out */ public SampleServerTrustDecider(boolean printdebuginfo) { debug = printdebuginfo; /** * Verifies a certificate chain. * * The certificate of the peer is the first one in the list * (chain[0]), and the top level certificate is the last one. * the certificate chain to verify true if the certificate chain is o.k., false otherwise */ public boolean verifycertificatechain(x509certificate[] chain) { int len = chain.length; try { chain[len-1].verify(chain[len-1].getpublickey(); //TOP LEVEL for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getpublickey()); catch (Exception ex) { return false; return true; /** * This method is called during the SSL handshake procedure to let * an application decide if the certificate sent by the client is * trustworthy. If this method returns false the SSL connection is * terminated with a fatal bad certificate error. * * This demo implementation just shows the certificate chain sent by * the client and checks its consistency. * certificate the SSLCertificate message containing the * certificate chain sent from the client true, if the client certificate is trusted, * false otherwise */ public boolean istrustedpeer(sslcertificate certificate) { if (certificate == null) { debug("no client certificate!"); return true; // no certificate is o.k. X509Certificate[] certchain = certificate.getcertificatechain(); debug("\nclient certificate chain:"); 75

76 SSLContext for (int i=0; i<certchain.length; i++) debug(certchain[i].getsubjectdn().tostring()); return verifycertificatechain(certchain); /** * If enabled print some debug information. * s the string to print */ private void debug(string s) { if (debug) System.out.println(s); To enable the SampleServerTrustDecider implementation, it has to be incorporated into the actual server context object. Note, that when creating a SampleServerTrustDecider object, we have to specify if debug information has to be reported: SSLServerContext servercontext = new SSLServerContext(); SampleServerTrustDecider trustdecider = new SampleServerTrustDecider(true); ServerContext.setTrustDecider(trustDecider); The active server trust decider may be obtained from the server context by means of the gettrustdecider() method. If the active server trust decider is an instance of the ServerTrustDecider class, an explicit cast will be necessary since per the default a TrustDecider object is returned: //without cast a TrustDecider object is returned TrustDecider trustdecider = servercontext.gettrustdecider(); //cast to SampleServerTrustDecider SampleServerTrustDecider servertd = (SampleServerTrustDecider)serverContext.getTrustDecider(); 76

77 SSLContext Server Trust Decider received client certificate Server Handshaker The server trust decider checks the trustworthiness of the certificate received from the client. Figure 3.3: The Server Trust Decider Any application may realize its own server trust decider policy, which - of course - may be more comprehensive than the example above. For a demonstration look at the DemoServerTrustDecider class of isasilk s Demo package public interface ClientTrustDecider extends TrustDecider Additionally to the task of checking the trustworthiness of the certificate sent by the server, the client trust decider has to take care for providing appropriate certificates and keys for suffering a client authentication request coming from the server. If the server is a non anonymous server, it may claim for a client authentication by sending a certificate request message. If an anonymous server tries to request a certificate from the client, the connection is closed immediately by triggering a fatal handshake failure. In sending a certificate request message to the client, the server specifies the certification authorities and certificate types it is willing to accept. The client, when receiving the servers certificate request message, asks its client trust decider whether it is able to fulfill the server s specific certificate requirements. If no client trust decider is installed or no client trust decider is bound to the actual client context, the client has to answer the server s certificate request with a No certificate warning. The same warning has to be sent back to the server if the actual context object supports a client trust decider, but the client trust decider is not able to supply an appropriate certificate. If the server receives a No certificate message from the client answering its certificate request message, it is left to the server to decide if the connection should be closed with a fatal handshake failure or if the handshake dialogue should be continued. 77

78 SSLContext Client Trust Decider received server certificate Client Handshaker The client trust decider checks the trustworthiness of the certificate received from the server. Additionally, the client trust decider has to take care for certificates and keys if the server requets a client authentication. Figure 3.4: The Client Trust Decider There are several types of certificates the server may request from the client when sending its certificate request message: rsa_sign: denotes a RSA certificate including the client s public RSA key; can be used for signing dss_sign: denotes a DSS certificate including the client s public DSA key; can be used for signing rsa_fixed_dh: denotes a RSA certificate including fixed Diffie Hellman parameters that have to match to the DH parameters the client has received within the server certificate; cannot be used for signing dss_fixed_dh: denotes a DSS certificate including fixed Diffie Hellman parameters that have to match to the DH parameters the client has received within the server certificate; cannot be used for signing rsa_ephemeral_dh: denotes a RSA certificate including the RSA public key; the ephemeral Diffie Hellman parameters are sent with the Client Key Exchange message and have to match to the DH parameters the client has received within the server key exchange message; can be used for signing dss_ephemeral_dh: denotes a DSS certificate including the DSA public key; the ephemeral Diffie Hellman parameters are sent with the Client Key Exchange message and have to match to the DH parameters the client has received within the server key exchange message; can be used for signing fortezza_dms: denotes a fortezza certificate; can be used for signing 78

79 SSLContext It is the responsibility of the implemented client trust decide whether a particular certificate shall be supported or not. The client handshaker that receives the certificate request message from the server, expects from the client trust decider an easy mechanism for obtaining appropriate certificates and keys to satisfy the server s certificate request. The isasilk s inherent ClientTrustDecider interface first defines some fixed key values making it possible to uniquely identify a particular certificate type that may be requested from the server: public static final byte rsa_sign = 1; public static final byte dss_sign = 2; public static final byte rsa_fixed_dh = 3; public static final byte dss_fixed_dh = 4; public static final byte rsa_ephemeral_dh = 5; public static final byte dss_ephemeral_dh = 6; public static final byte fortezza_dms = 20; A SSL server may use these agreements to define the certificate types it wants to specify within its certificate request message. If the server, for instance, wishes to get a certificate of either rsa_sign, dss_sign, rsa_ephemeral_dh or dss_ephemeral_dh type, it sets the appropriate values and packs them into a byte array: byte[] types = new byte[4]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; types[2] = ClientTrustDecider.rsa_ephemeral_dh; types[3] = ClientTrustDecider.dss_ephemeral_dh; Beside the definition of the certificate types, the ClientTrustDecider interface includes two abstract methods that have to be implemented for enabling the client handshaker to easily access a particular certificate and private key for satisfying the server s certificate request: /** * Returns a SSLCertificate handshake message containing the client certificate. * By implementing this interface someone can use his own procedure * to access the client certificates. * certificatetypes the certificate types the server expects certificateauthorities the certification authorities the server accepts keyexchangealgorithm the currently active key exchange * algorithm (from cipher suite) a SSLCertificate handshake message containing the client certificate list (list[0] = client certificate) or null if no appropriate certificate is found. */ public abstract SSLCertificate[ ] getcertificate(byte[ ] certificatetypes, Principal[ ] certificateauthorities, String keyexchangealgorithm); 79

80 SSLContext /** * Returns the private key belonging to the certificate returned by * getcertificate(). * the private key */ public abstract PrivateKey getprivatekey(); Note that the getcertificate(...) method has to return a SSLCertificate handshake message object containing the client certificate chain to be sent to the server! Now, if we intend to design a particular demo client trust decider implementation, we first have to reflect about the several tasks our client trust decider shall be able to accomplish: taking care for obtaining the desired certificates and corresponding keys from some source providing some methods making it possible for the client handshaker to have access to the supplied certificates respectively private keys implementing the istrustedpeer(..) method of the basic TrustDecider interface for deciding if the certificate derived from the server is trustworthy If you think back to chapter you may remember the discussion about the way a SSL server may follow to get certificates respectively keys for being able to support all the cipher suites implemented by isasilk: first all certificates and keys - except for temporary Diffie Hellman parameters which have to be generated separately - have been created from.der files containing DER encoded certifcate chains and key material. Following this, the derived certificate chains and keys have been incorporated into the actual server context object. Of course, each particular application may use its own strategy to obtain certificates and keys from some available source. However, for the purpose of demonstration we again will read in certificates and key material from the.der files of our certs subfolder holding IAIK KeyAndCertificates structures. It is important to be aware about the difference between the server and client side when providing certificates and key material for authentication and key exchanging: The server - after obtaining the certificates and keys from some source - makes them available for the corresponding server handshaker by immediately supplying them to the actual server context object. Later, during the handshake dialogue, when the server handshaker requires certificate/keys for authentication and key exchanging, it will get them from the server context. The client passes the certificate and key obtaining task to the client trust decider, and the client handshaker - responsible for managing the handshake dialogue - gets certificates and keys from the client trust decider. 80

81 SSLContext Since the client trust decider at first has to take care for certificates and key material, this duty already may be included into the SampleClientTrustDecider constructor implementation: private X509Certificate[] rsa_cert; private PrivateKey rsa_private_key; private X509Certificate[] dsa_cert; private PrivateKey dsa_private_key; private X509Certificate[] dh_cert; private PrivateKey dh_private_key; private PrivateKey private_key; //Constructor for creating a SampleClientTrustDecider object public SampleClientTrustDecider() { try { KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/clientRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); rsa_cert = kac.getcertificatechain(); rsa_private_key = epki.getprivatekey(); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/clientDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); dsa_cert = kac.getcertificatechain(); dsa_private_key = epki.getprivatekey(); // set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/clientDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); dh_cert = kac.getcertificatechain(); dh_private_key = epki.getprivatekey(); catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); Each specific kac object is created as instance of the iaik.utils.keyandcertificate class for generating the desired private key and belonging certificate chain from DER encoded files. Since the inherent private key has been protected by password based encryption, it has to be decrypted by instantiating the 81

82 SSLContext iaik.pkcs.pkcs8.encryptedprivatekeyinfo class when creating a "key holding" epki object (see 3.3.2). Remember, that SSLv3 demands certificates according to the X.509 syntax, as returned by the getcertificatechain() method of the iaik.utils.keyandcertificate class. Now, when a SampleClientTrustDecider object is created, it first looks for appropriate files in the certs directory and creates the required certificates and keys: SampleClientTrustDecider clienttd = new SampleClientTrustDecider(); Remember that this is a demo client trust decider implementation that reads in certificates from files. You may follow your own strategy for obtaining certificates and keys. However, be sure to provide certificates according to the X.509 syntax! After creating certificates and keys - regardless the way it is done - we have to implement proper methods for supplying certificates to the client handhaker asking for them. When the client handshaker has received the certificate request message from the server, it makes a call to the getcertificate(..) method of the client trust decider thereby specifying the certification authorities and certificate types the server is willing to accept. The client trust decider now searches the certificates created by its constructor to query if it is able to fulfill the server requirements. Since the server may accept certificates of more than only one type, the client handshaker additionally has to specify the actual key exchange algorithm when calling the client trust decider s getcertificate(..) method. Since client certificate and keys have to be in accordance with the negotiated cipher suite, the client handshaker gets the key exchange algorithm from the active cipher suite before calling the getcertificate(..) method of the client trust decider: key_exchange_algorithm = cipher_suite.getkeyexchangealgorithm(); SSLCertificate certificate = ((ClientTrustDecider)trust_decider).getCertificate( certificate_request.getcertificatetypes(), certificate_request.getcertificateauthorities(), key_exchange_algorithm); Note that certificate_request denotes the certificate request message the client handshaker has derived from the server. The following implementation of the getcertificate(..) method of the SampleClientTrustDecider class first reports all the certification authorities and certificate types the server is willing to accept. Therefore a separate debug(..) method is implemented doing nothing else than printing the supplied input String to the standard output stream: 82

83 SSLContext private void debug(string s) { System.out.println(s); After printing information onto the screen, the supplied key exchange algorithm is used to determine the type of the certificate to be returned. Since a Java method only can return one single entity, we have to use a extra method getprivatekey() the client handshaker may call to get the private key matching to the certificate first derived by the getcertificate(..) method: public PrivateKey getprivatekey() { return private_key; The private key returned by getprivatekey() has been created by the SampleClientTrustDecider constructor and assigned to the global private_key variable within the getcertificate() method when determining the certificate type and private key type that matches the active cipher suite s key exchange algorithm. The whole getcertificate(..) method may look like (remember that we have to return a SSLCertificate handshake message containg the client certificate chain to be sent to the server; we therefore construct a SSLCertificate object by supplying the SSLCertificate constructor with the proper certificate chain previously generated when creating the actual SampleClientTrustDecider object): /** * Returns a SSLCertificate handshake message containing the * client certificate. * certificatetypes the certificate types the server requests certificateauthorities the certification authorities the * server accepts keyexchangealgorithm the currently active key exchange * algorithm (from cipher suite) the SSLCertificate message containing the * client certificate list */ public SSLCertificate getcertificate(byte[] certificatetypes, Principal[] certificateauthorities, String keyexchangealgorithm) { //print actual key exchange algorithm debug("key exchange algorithm: "+keyexchangealgorithm); //print certification authorities accepted by the server debug("server accepts the following CAs:"); for (int i=0; i<certificateauthorities.length; i++) debug(certificateauthorities[i].tostring()); //print certificate types requested by the server debug("server requests the following certificate types:"); for (int i=0; i<certificatetypes.length; i++) { switch (certificatetypes[i]) { case ClientTrustDecider.rsa_sign: 83

84 SSLContext debug("rsa_sign"); break; case ClientTrustDecider.dss_sign: debug("dss_sign"); break; case ClientTrustDecider.rsa_fixed_dh: debug("rsa_fixed_dh"); break; case ClientTrustDecider.dss_fixed_dh: debug("dss_fixed_dh"); break; case ClientTrustDecider.rsa_ephemeral_dh: debug("rsa_ephemeral_dh"); break; case ClientTrustDecider.dss_ephemeral_dh: debug("dss_ephemeral_dh"); break; case ClientTrustDecider.fortezza_dms: debug("fortezza_dms"); break; //select proper certificate and private key according the active //cipher suite s key exchange algorithm if (keyexchangealgorithm.startswith("rsa") keyexchangealgorithm.startswith("dhe_rsa")) { debug("return RSA certificate..."); private_key = rsa_private_key; return new SSLCertificate(rsa_cert); else if (keyexchangealgorithm.startswith("dhe_dss")) { debug("return DSA certificate..."); private_key = dsa_private_key; return new SSLCertificate(dsa_cert); else if (keyexchangealgorithm.startswith("dh_")) { debug("return DH certificate..."); private_key = dh_private_key; return new SSLCertificate(dh_cert); return null; After having done all the work for obtaining certificates and keys and returning them, we shall not forget on the very own s task of the client trust decider: checking if the certificate derived from the server is trustworthy or not. As already introduced when discussing the demo server trust decider, we again will implement the istrustedpeer(..) method of the basic TrustDecider interface to report the received server certificate chain and check its consistency by using the verifycertificatechain(certchain) method. Since, on the client side, a 84

85 SSLContext certificate chain coming from the server is always supplied when calling the istrustedpeer() method, we don t have to decide about a null argument: //returns true if the certificate derived from the server is trusted //this demo version shows the received certificate chain and checks //its consistency public boolean istrustedpeer(sslcertificate certificate) { // get the X.509 certificate chain from the SSLCertificate message X509Certificate[] certchain = certificate.getcertificatechain(); debug("server certificate chain"); for (int i=0; i<certlist.length; i++) debug(certchain[i].getsubjectdn().tostring()); return verifycertificatechain(certchain); As already seen when implementing the SampleServerTrustDecider ( ), again we have to be aware to extract the inherent X509Certificate chain from the supplied SSLCertificate message for passing it to the verifycertificatechain method. Now we are ready to put all together for implementing the whole DemoCleintTrustDecider class. To let the user decide if debug information should be reported or not, we include a special boolean debug variable that has to be initialized when calling the constructor: import java.security.*; import java.io.*; import java.security.cert.x509certificate; import iaik.security.ssl.*; import iaik.asn1.*; import iaik.asn1.structures.name; import iaik.security.rsa.*; import iaik.security.dsa.*; import iaik.security.dh.*; import iaik.pkcs.*; import iaik.utils.keyandcertificate; import iaik.pkcs.pkcs8.encryptedprivatekeyinfo; public class SampleClientTrustDecider implements ClientTrustDecider { private X509Certificate[] rsa_cert; private PrivateKey rsa_private_key; private X509Certificate[] dsa_cert; private PrivateKey dsa_private_key; private X509Certificate[] dh_cert; private PrivateKey dh_private_key; private PrivateKey private_key; boolean debug; 85

86 SSLContext /** * Creates a SampleClientTrustDecider * printdebuginfo if true debug information is printed to * System.out */ public SampleClientTrustDecider(boolean printdebuginfo) { debug = printdebuginfo; try { KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/clientRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); rsa_cert = kac.getcertificatechain(); rsa_private_key = epki.getprivatekey(); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/clientDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); dsa_cert = kac.getcertificatechain(); dsa_private_key = epki.getprivatekey(); // set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/clientDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); dh_cert = kac.getcertificatechain(); dh_private_key = epki.getprivatekey(); catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); /** * Verifies a certificate chain. * * The certificate of the peer is the first one in the list * (chain[0]), and the top level certificate is the last one. * the certificate chain to verify true if the certificate chain is o.k., false otherwise */ public boolean verifycertificatechain(x509certificate[] chain) { int len = chain.length; 86

87 SSLContext try { chain[len-1].verify(chain[len-1].getpublickey()); //TOP LEVEL for (int i = len-1; i>0; i--) chain[i-1].verify(chain[i].getpublickey())) return false; catch (Exception ex) { return false; return true; /** * This method is called during the SSL handshake procedure to let * an application decide if the certificate sent by the server is * trusted. If this method returns false the SSL connection is * terminated with a fatal bad certificate error. * * This demo implementation shows the certificate chain sent by * the server and checks its consistency. * certificate the SSLCertificate maessage containing the * certificate chain sent by the server true, if the server certificate is trusted; false otherwise */ public boolean istrustedpeer(sslcertificate certificate) { X509Certificate[] certchain = certificate.getcertificatechain(); debug("server certificate chain"); for (int i=0; i<certchain.length; i++) debug(certchain[i].getsubjectdn().tostring()); return verifycertificatechain(certchain);; /** * Returns a SSLCertificate handshake message conatining the * client certificate. * If there is no TrustDecider set in a SSLClientContext a * NoCertificate warning is sent to the server. * * This demo implementation shows the certificate types and CAs the * server requests. It returns a SSLCertificate object containing * the client certificate specified in the constructor of this * class. * certificatetypes the certificate types the server requests certificateauthorities the certification authorities the * server accepts keyexchangealgorithm the currently active key exchange * algorithm (from cipher suite) the SSLCertificate object containing the client * certificate list */ 87

88 SSLContext public SSLCertificate getcertificate(byte[] certificatetypes, Principal[] certificateauthorities, String keyexchangealgorithm) { //Print actual key exchange algorithm debug("key exchange algorithm: "+keyexchangealgorithm); //Print certification authorites accepted by the server debug("server accepts the following CAs:"); for (int i=0; i<certificateauthorities.length; i++) debug(certificateauthorities[i].tostring()); //Print certificate types requested by the server debug("server requests the following certificate types:"); for (int i=0; i<certificatetypes.length; i++) { switch (certificatetypes[i]) { case ClientTrustDecider.rsa_sign: debug("rsa_sign"); break; case ClientTrustDecider.dss_sign: debug("dss_sign"); break; case ClientTrustDecider.rsa_fixed_dh: debug("rsa_fixed_dh"); break; case ClientTrustDecider.dss_fixed_dh: debug("dss_fixed_dh"); break; case ClientTrustDecider.rsa_ephemeral_dh: debug("rsa_ephemeral_dh"); break; case ClientTrustDecider.dss_ephemeral_dh: debug("dss_ephemeral_dh"); break; case ClientTrustDecider.fortezza_dms: debug("fortezza_dms"); break; //select proper certificate and private key according the active //cipher suite s key exchange algorithm if (keyexchangealgorithm.startswith("rsa") keyexchangealgorithm.startswith("dhe_rsa")) { debug("return RSA certificate..."); private_key = rsa_private_key; return new SSLCertificate(rsa_cert); else if (keyexchangealgorithm.startswith("dhe_dss")) { debug("return DSA certificate..."); private_key = dsa_private_key; return new SSLCertificate(dsa_cert); else if (keyexchangealgorithm.startswith("dh_")) { debug("return DH certificate..."); 88

89 SSLContext private_key = dh_private_key; return new SSLCertificate(dh_cert); return null; /** * Returns the private key belonging to the certificate returned by * getcertificate(). * the private key specified in the constructor */ public PrivateKey getprivatekey() { return private_key; /** * If enabled print some debug information. * s the string to print */ private void debug(string s) { if (debug) System.out.println(s); After creating the SampleClientTrustDecider object, it has to be enabled by incorporating it into the actual client context. Note, that when creating a SampleClientTrustDecider object, we have to specify if debug information has to be reported: SSLClientContext context = new SSLclientContext(); SampleClientTrustDecider trustdecider = new SampleClientTrustDecider(true); context.settrustdecider(trustdecider); The active client trust decider may be obtained from the client context by means of the gettrustdecider() method. If the active client trust decider is an instance of the SampleClientTrustDecider class, an explicit cast will be necessary since per the default a TrustDecider object is returned: //without cast a TrustDecider object is returned TrustDecider trustdecider = context.gettrustdecider(); //cast to SampleClientTrustDecider SampleClientTrustDecider servertd = (SampleClientTrustDecider)context.getTrustDecider(); 89

90 SSLContext Any application may realize its own client trust decider policy, which may be more comprehensive than the example above. For a demonstration look at the DemoClientTrustDecider class of isasilk s Demo package. For summing up, the following two sections briefly describe what the server respectively client has to do for supporting trust deciding Trust Deciding: What the SSLServer has to do Presuming that a server trust decider, for instance our SampleServerTrustDecider, has been implemented, the only thing to do is incorporating the trust decider into the server context: SampleServerTrustDecider trustdecider = new SampleServerTrustDecider(true); servercontext.settrustdecider(trustdecider); It may be necessary for the SSLServer to perform some additional tasks for configuring the server trust decider, depending on the peculiarities of the installed server trust decider implementation. The, for example, DemoServerTrustDecider of isasilk s Demo package allows the SSLServer to specify trusted signers for deciding about the trustworthiness of the client certifcates (see DemoServerTrustDecider and SSLServer source codes of the isasilk Demo package) Trust Deciding: What the SSLClient has to do Presuming that a client trust decider, for instance our SampleClientTrustDecider, has been implemented, the only thing to do is incorporating the trust decider into the client context: SampleClientTrustDecider trustdecider = new SampleClientTrustDecider(true); context.settrustdecider(trustdecider); It may be necessary for the SSLServer to perform some additional tasks for configuring the server trust decider, depending on the peculiarities of the installed server trust decider implementation. 90

91 SSLContext Client Authentication: What the SSLServer has to do If the server claims for a client authentication, it has to send a certificate request message to the client specifying the certification authorities and certificate types it is willing to accept. Since the server handshaker, which is responsible for managing the handshake dialogue with the client, has to know whether it shall send a certificate request message or not, the server must inform the server handshaker when it intends to request a client authentication. Therefore the ServerContext class is equipped with a special method the server may call for telling the handshaker to send the certificate request message: public void setrequireclientcertificate(byte[] certificatetypes, Name[ ] certificateauthorities); When calling the context s setrequireclientcertificate method, the server has to supply the proper certification types within a byte array and the accepted certification authorities within an array of Relative Distinguished Names. For specifying the certificate types to be accepted, the server creates a proper byte array and fills it with the certificate type identifiers as defined within the ClientTrustDecider class (see ). Supposing to claim for a client certificate of either rsa_sign or dss_sign type, the server will need a two-byte array: byte[] types = new byte[2]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; Since rsa_sign and dss_siqn are static variables (see ), no extra ClientTrustDecider object must be created for setting the certificate types. The certification authorities to be accepted are defined as an array of Name objects of the IAIK-JCE iaik.asn1.structures package. The Name class of the iaik.asn1.structures package represents a X.500 Name structure consisting of OBJECT IDENTIFIER - value assertions pairs. For instantiating the Name class, the server may use the default constructor, and subsequently add some relative distinguished name by means of the Name class addrdn(..) method: /** * Adds a RelativeDistinguishedName to this Name. oid the ObjectID of the RDN value the value of the RDN */ public void addrdn(objectid oid, String value); 91

92 SSLContext We suppose that our SSL server wishes to specify only one particular certification authority: Name[] acceptedcas = new Name[1]; Name verisign = new Name(); verisign.addrdn(objectid.country, "US"); verisign.addrdn(objectid.organization, "VeriSign, Inc."); verisign.addrdn(objectid.organizationalunit, "Class 1 Public Primary Certification Authority"); acceptedcas[0] = verisign; After defining certification authorities and certificate types, the only remaining task for the server is to indicate a request for a client certificate by informing the handshaker with the setrequireclientcertificate(..) note: servercontext.setrequireclientcertificate(types, acceptedcas); The server context can be seen as some kind of intermediary instance between server and server handshaker: the server tells the context to inform the handshaker of the intended certificate request. The server handshaker gets the message from the context thereby reading the certification authorities and certificate types it has to specify when sending the certificate request message to the client. If neither types nor acceptedcas are set by the server, no client authentication will be demanded Client Authentication: What the SSLClient has to do Since all the work necessary for dealing with a certificate request of the server is done by the client trust decider and client handshaker, a SSLClient implementation only has to bind the particular client trust decider into the context (as already done in ): SampleClientTrustDecider trustdecider = new SampleClientTrustDecider(true); context.settrustdecider(trustdecider); Keep in mind, that implementing a client trust decider is an absolute necessity for supporting client authentication! Now we can close our SSLClientContext discussion with a short summary SSLClientContext: Summary The SSLClientContext class extends the abstract SSLContext class for providing all the security features a SSLSocket may need to perform a SSL communictaion. 92

93 SSLContext An object of the SSLClientContext class may be created using either the default empty constructor or by defining a random number generator ( ) to be used for generating all the random numbers required during the handshake procedure. Several methods enable the user to set/get the security features of the SSLClientContext object. Enabled cipher suites ( ) and compression methods ( ) define the key exchange, symmetric encryption and MAC, respectively compression algorithms supported by a particular SSLClientContext object. Session Manager ( ) and Trust Decider ( ) interfaces provide templates for enabling the user to implement her/his own session caching repectively peer certificate trusting policy. To activate the security properties of a particular SSLClientContext object, it has to be incorporated into the SSLSocket object for which it has been created: SSLSocket socket = null; SSLClientContext context = new SSLClientContext();... supply the context object with user implemented properties (optional)... socket = new SSLSocket(serverName, serverport, context); At the beginning of this chapter, it has been mentioned that all the basic properties of a SSLClientContext object also are supported by a SSLServerContext object. During the course of this chapter, several times when necessary it has been pointed onto differences between client and server implementation. The following introduction to the SSLServerContext class therefore only briefly describes the additional features the server context may provide in extension to the client context The SSLServerContext Class The SSLServerContext class extends the SSLClientContext class about some properties required only by the server socket of a SSL connection. Remember the two tasks, a SSL server context must add to the functionality of a SSL client context: The server delegates the task of obtaining certificates, private and temporary keys used for authentication and key exchange not to a trust decider. Rather certificates and keys are directly supplied to the actual server context object. Therfore the SSLServerContext class has to provide appropriate methods making it easy to set/get the corresponding entities from a server context object. The server context object serves as a intermediary between the server and its handshaker when sending a certificate request message to the client. Therefore the 93

94 SSLContext SSLServerContext class on the one hand includes a method for allowing the server to specify certificate types and certification authorities for the certificate request message. On the other hand, the server handshaker will ask the context whether the server has directed to sent a certificate request message or not. It already has been discussed in chapter how the server may get proper certificates and keys for authentication from files holding IAIK KeyAndCertificate structures (see also ). So it will do at this place only to repeat the binding of the several certificates/keys into the server context object: // set the RSA certificate/private key for RSA cipher suites servercontext.setrsacertificate(kac.getcertificatechain(), epki.getprivatekeyinfo()); // set the DSA certificate/private key for DSA cipher suites servercontext.setdsacertificate(kac.getcertificatechain(), epki.getprivatekeyinfo()); // set the DH certificate/private key for DH cipher suites servercontext.setdhcertificate(kac.getcertificatechain(), epki.getprivatekeyinfo()); //set the temporary RSA key pair for RSA_EXPORT cipher suites servercontext.setrsatempkeypair(tempkeypair); // set the DH parameter for ephemeral cipher suites servercontext.setdhparameter(dhparam); Remember, that each specific kac object is created as instance of the iaik.utils.keyandcertificate class for generating the desired private key and belonging certificate chain from DER encoded files. Since the inherent private key has been protected by password based encryption, it has to be decrypted by instantiating the iaik.pkcs.pkcs8.encryptedprivatekeyinfo class when creating a "key holding" epki object (see 3.3.2). The getcertificatechain() method of the KeyAndCertificate class has to be used to obtain X.509 certificates as required by the server context. Any application may implement their own strategy for obtaining certificates and key material from some available source. However, it has to be noticed that the several set*certificate(..) methods of the SSLServerContext class claim for certificates according to the X.509 syntax. The SSLServerContext class provides a particular utility method for automatically enabling all cipher suites that can be supported by the actual set of certificates and keys: public CipherSuite[] updateciphersuites() 94

95 SSLContext In this way, supposing to already have set key and certifcates as described above, only the updateciphersuites() has to be called for enabling all corresponding cipher suites: servercontext.updateciphersuites(); The second additional task of the SSLServerContext class - serving as a intermediary between the server and its handshaker when sending a certificate request message to the client - also has been described within the last sections (see ). After the server has defined certification authorities and certificate types it is willing to accept, it makes them available for the server handshaker by preparing the server context: servercontext.setrequireclientcertificate(types, acceptedcas); For providing a answer to the server handshaker s question whether a certificate request message has to be sent to the client or not, the SSLServerContext class uses a boolean method returning true if certificate request shall be sent and false otherwise: public boolean getrequireclientcertificate(); After creating a SSLServerContext object and optionally supplying it with some user-defined facilities, the server context has to be incorporated into the actual SSLServerSocket object: SSLServerSocket serversocket = null; SSLServerContext servercontext = new SSLServerContext();... supply the context object with user implemented properties (optional)... serversocket = new SSLServerSocket(port, servercontext); In general, the incorporating a SSLClientContext object into a SSLSocket object - respectively a SSLServerContext object into a SSLServerSocket object - will complete the context intitialization phase. Correspondingly, we can close our SSLContext discussion and proceed over to a short introduction of the SSLSocket classes thereby concentrating on the properties that may be of main interest when implementing the client or server side of a SSL connection. 95

96 SSLSocket The SSLSocket Class An object of the Socket class of the java.net package implements one end-point of a two-way communication link between two programs running on the network (javatut]). An object of the SSLSocket class extends a Socket object about SSL s inherent security features that mainly are determined by the corresponding SSLContext object. Introducing we shall look back to section 3.1 where briefly has been described how a SSLClient implementation may open a SSL connection by instantiating the SSLSocket class and supplying a SSLClientContext object for defining particular security features: PrintWriter writer = null; BufferedReader reader = null; SSLSocket s = null; SSLClientContext context = new SSLClientContext(); try { s = new SSLSocket(serverName, serverport, context); s.setdebugstream(system.out); reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream());... communicate with server... s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); First a new SSL stream socket is created for connecting to a server specified by its name and listening on port serverport. For the particular SSLSocket constructor used in the example above it is necessary to identify the server by its name. As already might be familiar from the conventional Socket class, the SSLSocket class provides a variety of constructors allowing to specify the communication partner by its InetAddress. Also the default constructor is included for creating a unconnected socket as may be used by the server socket. In addition to the initial example of section 3.1, now we will open not only an output and input stream for writing to and reading from the socket, but also an debug stream for printing debugging information during the handshake phase to System.out (look at the bold line in the program code fragment above). Note that for increasing efficiency we also now will buffer the strings read in from and written out to the socket. For actually communicating with the server, in our example we make use of the println() and readline() methods of the java.io.printwriter respectively java.io.bufferedreader class to write/read strings to/from the socket streams. 96

97 SSLSocket Supposing, the client wishes to get the homepage of the specified server, it prints a corresponding request onto the buffered output stream and subsequently flushes this stream forcing any buffered output bytes to be written out to the underlying output stream: String request = new String("GET / HTTP/1.0"); writer.println(request); writer.println(); writer.flush(); Following this, the data sent back from the server are read in line by line from the socket input stream and printed to System.out: String line; while ((line = reader.readline())!= null) { System.out.println("Server sends: "+line); After some communiction with the server, the connection is closed by first closing the serveral streams and subsequently closing the SSL socket. So far, we have learned enough for being able to implement the client s side of a SSL connection by creating a SSLSocket object, initializing it with the corresponding context object for defining the security features, opening input and output streams onto the socket, performing some communication with the server, and finally closing streams and socket. The remaining discussion of the SSLSocket class will introduce three properties that may be used by some application for implementing a connection over a SSL proxy obtaining the certificate chain sent by the peer directly from the SSLSocket object. renegotiating new security specifications for the current session Connecting via a Proxy If the SSL client wishes to connect to a particular server via a proxy, no SSL handshake dialogue should be performed when the client connects to the proxy asking for establishing a SSL connection to the server listening on a specified port number. Since the handshake procedure will start automatically as soon as any stream is opened onto a SSL socket, the client explicitly has to direct its handshaker not to perform a handshake dialogue when contacting the proxy. Later, when the proxy is ready to forward the connection to the desired server, the client must start the handshake process manually. Suppose, we have implemented an extra method for sending a connect-to-server request to the proxy. This message will be sent to the proxy without being encrypted. Therefore we first open a SSL socket for connecting to the proxy and explicitly switch off 97

98 SSLSocket the automatic handshake start (look at the bold line in the following program code fragment): SSLSocket s = new SSLSocket(proxyName, proxyport, context); s.setautohandshake(false); Since the automatic handshake is turned off, now we can open input and output streams onto the socket for sending the unencrypted connect-to-server message to the proxy. reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream()); //send connect to server message to proxy proxyconnect(servername, serverport); For enabling the handshake dialogue between proxy and server, now we have to start the handshake dialogue manually: s.starthandshake(); If the following handshake procedure will be successfully completed, we can start the protected communication with the server using the proxy as intermediary point Obtaining the peer s certificate For providing an application a direct access to the certificate sent by the peer, the SSLSocket class is equipped with the getpeercertificatechain() method the application may call to obtain the peer s certificate chain for some reason (for instance for explicitly checking if the peer s certificate is trustworthy when not done so by a trust decider). The following example reads in the peer s certificate chain from the socket s and prints all the included certificates to System.out: X509Certificate[] chain = s.getpeercertificatechain(); for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": "+chain[i].getsubject()); System.out.println(); In the same way we may get active cipher suite and compression method from the SSLSocket. Remember that the active cipher suite is the one specific cipher suite client and server have negotiated for defining key exchange, symmetric encryption and MAC algorithms of the current session. Correspondingly, the active compression method defines the compression algorithm for compressing the data records of the actual session. 98

99 SSLSocket CipherSuite active_cs = s.getactiveciphersuite(); CompressionMethod active_cm = s.getactivecompressionmethod(); Security Parameter Renegotiation At any time during a SSL client-server communication, the server may decide to refresh the security settings (active cipher suite, active compression method,...) of the current session by sending a Hello Request message indicating the client to start a new handshake dialogue by transmitting a new Client Hello message. The Hello Request message will be ignored by the client if it arrives actually during a handshake phase. Otherwise the client will start a complete new handshaking procedure by sending the Client Hello message. The only difference is that the handshake messages of this second handshaking procedure will already be protected by the cryptographic parameters which have been negotiated during the first handshaking procedure. So any attacker even would not be able to see the normal unencrypted Hello and Key Exchange messages. On the other hand, the client itself may initiate a parameter refreshment by sending a Client Hello message to the server. The following section decribes parameter renegotiation within the isasilk environment from the server s point of view. Renegotiation initiated from the client requires an equivalent proceeding. isasilk provides a quite simple mechanism for enabling a SSLServer implementation to initiate a new handshake dialogue by sending a Hello Request message. Imaging the server side somewhere during a SSL client-server conversation. The server communicates with the client by means of streams that are opened on a SSLSocket object generated when accepting a client s request at the beginning of the actual session: SSLSocket s; s = (SSLSocket)serverSocket.accept(); OutputStream os = s.getoutputstream(); InputStream is = s.getinputstream();... Now the server decides for some reason - for instance, it wants to use a 128Bit key RC4 cipher for data encryption instead of the originally negotiated 40Bit key RC4 - to renegotiate the security specifications of the current session. It can do so by simply calling the SSLSocket class renegotiate() method ordering the server handshaker to send a Hello Request message. Since this method may throw an IOException, the server must take care for catch it: 99

100 SSLSocket try { s.renegotiate(); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); A call to the SSLSocket s renegotiate() method automatically will cause the server handshaker to send the Hello Request message for initiating the client handshaker to respond with its Client Hello message. However, before ordering the server handshaker to send the Hello Request message, the server should change the context of the actual client-communicating SSLSocket according to the new security parameters it wants to renegotiate for the current session. Supposing the server wishes to force the SSL_RSA_WITH_RC4_128_MD5 cipher suite for performing a 128Bit key RC4 data encryption, it first has to set the appropriate cipher suite. For that reason the actual context object has to be obtained from the SSLSocket (we alternatively may create a new context object and supply it with the new settings; but if we only want to refresh the enabled cipher suites, we can rely on all the other context settings that already have been established): SSLContext con = s.getcontext(); Following this, the obtained context object has to be refreshed according to the desired cipher suite: CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5; con.setenabledciphersuites(new_cs); Finally, after incorporating the modified context object into the SSLSocket again, the renegotiation process may be initiated: s.setcontext(con); try { s.renegotiate(); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); Summing up, all the work that have to be done by a SSLServer for renegotiating the cryptographic parameters of the current session, may lead to a program code fragment similar to (s further on denotes the SSLSocket object initially returned by the accept() method for communicating with the client): //define a new cipher suite (or any new context parameters if desired) CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5; 100

101 SSLSocket //get the actual context from the SSLSocket SSLContext con = s.getcontext(); //set the new cipher suite as enabled cipher suite con.setenabledciphersuites(new_cs); //set the modified context for the SSLSocket again s.setcontext(con); //start the renegotiation process try { s.renegotiate(); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); On the other side, just the same program fragment may be used by a SSLClient that itself wishes to initiate a security parameter regoniation. In this case, of course, the socket s from the example above will indicate the SSLSocket the client uses to communicate with the server. However, a server may want to refresh not only the security parameters of the current client session, but also set the new parameters for any further client request. Notice, that in the example above, we have changed the cipher suite settings of the context object belonging to the SSLSocket object that is used to communicate with some particular client. We have not changed the server context object! When the server - at the beginning of the current session - has called the SSLServerSocket s accept() method, a SSLSocket object has been returned for communicating with the client. Thereby, inside the accept() method and not visible for the user, the new created SSLSocket object has been initialized with the actual SSLServerContext for determining the several cryptographic settings (cipher suites, compression methods,...) the sever handshaker has used to go into the handshake dialogue with the client handshaker. In changing only the context of this SSLSocket will redefine the server s handshake conditions for renegotiating the security parameters of the current session with this one particular client. All further incoming client requests still will be handled by the old server context settings, since the accept() method initializes each new created SSLSocket object with the unchanged server context. If we want to define new server context settings not only for renegotiating the cryptographic parameters of the current session, but also for every further handshake dialogue, we directly may change the server context when starting the renegotiation process: //define a new cipher suite (or any new context parameters if desired) CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_RC4_128_MD5; //set the new cipher suite as enabled cipher suite for the actual //server context servercontext.setenabledciphersuites(new_cs); //set the modified server context for the SSLSocket s.setcontext(servercontext); //start the renegotiation process s.renegotiate(); 101

102 SSLSocket Note, that when implementing a SSLClient based on isasilk, no care has to be taken about any Hello Request message coming from some server just communicating to. All the work necessary to handle a server s Hello Request is done by the client handshaker! In addition of being able to realize all the basic tasks that are necessary for implementing the client s side of a SSL connection, now we may include a proxy and/or obtain the peer s certificate directly from the SSL socket - quite enough for building a reasonable SSLClient. For implementing a SSLServer we also have to know something about the SSLServerSocket class The SSLServerSocket Class An object of the ServerSocket class of the java.net package implements a server socket waiting on requests coming from any calling client. An object of the SSLServerSocket class extends a ServerSocket object about SSL s inherent security features that mainly are determined by the corresponding SSLServerContext object. Again, we shall look back to the example of section 3.2 introducing a simple implementation of the server side of a SSL connection: SSLServerSocket server = null; SSLSocket s = null; SSLServerContext servercontext = new SSLServerContext(); try { server = new SSLServerSocket(serverPort, servercontext); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); while (true) { try { s = (SSLSocket)server.accept(); OutputStream os = s.getoutputstream(); InputStream is = s.getinputstream();... communicate with client... s.close(); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); 102

103 SSLSocket First a SSLServerSocket object is created and supplied with a SSLServerContext object for defining particular security features. The constructor used in the example above generates a server socket on an explicitly specified port the server shall listen for incoming connection requests. There are many other constructors within the SSLServerSocket class making it possible not to specify any port number and/or limiting the number of incoming connection indications to be handled. If no particular port number is set, the server socket is created at any free port. If no particular context object is supplied, the server socket is created with a default context. When a request for connect comes in over the network, the server socket accepts this request and returns a new SSLSocket for communicating with the client. Since the SSLServerSocket s accept() method per default returns a conventional Socket object, an explicit cast is necessary for obtaining a SSLSocket object. Now output and input streams are opened onto the new created SSLSocket object for actually communicating with the requesting client. For our example, we will implement a SSLServer waiting for a SSL connection coming from some browser. If the connection is accepted, the server only will return the string "SSL Test ok.". First the client s message is read from the input stream into a byte array and subsequently printed to System.out: byte[] arr = new byte[300]; int l=-1; for (int i=0; i<10 && l<0; i++) l = is.read(arr); System.out.println("client sends: "+l); for (int j=0; j<l; j++) System.out.print((char)arr[j]); For displaying the answering "SSL Test ok." message in the requesting browser, we have to pack it into a HTML page and transfer it according to the hyper text transfer protocol (HTTP). Supposing to have implemented an extra method addline(string line) for reading strings into a buffer byte array, we may fill the buffer with our HTTP message: //write to some buffer byte array addline("http/ OK"); addline("content-type: text/html"); addline("server: IAIK-SSL Testserver"); addline(""); addline("<html><head>"); addline("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;CHARSET=iso \">"); addline("<title>ssl Test</TITLE>"); addline("</head>"); addline("<body>"); addline("<h1>ssl Test ok.</h1>"); addline("</body>"); addline("</html>"); 103

104 SSLSocket Finally we ll send the message to the browser by putting the buffer contents onto the SSLSocket s output stream and subsequently flushing the stream: os.write(buffer, 0, pos); os.flush(); The variable pos indicates the number of bytes stored within the buffer to be written onto the stream. The value of pos automatically has been updated inside the addline() method everytime a string has been read into the buffer: static byte[] buffer = new byte[10000]; //initially the buffer is empty static int pos = 0; //carriage return line feed static byte[] crlf = {13, 10; //method for reading a string into a byte array public static void addline(string line) { byte[] arr = line.getbytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2; The method arraycopy(object src, int src_pos, Object dst, int dst_pos) copies an sub array of the source array to the destination array. The sub array of the source array starts at src_pos and is copied to dst_pos within the destination array. After sending the data to the browser, the server yet close SSLSocket thereby closing any stream onto the socket. When explicitly closing streams, the output stream must be closed before closing the input stream. The server socket itself remains opened continuing to listen on incoming client requests: os.close(); is.close(); s.close(); There are no more particular features of the ServerSocketClass for being of interest when implementing a SSL server. The following concluding section will step through example SSLClient respectively SSLServer implementations thereby repeating all the features we have learned during the course of this paper. 104

105 SSLClient and SSLServer 3.5 Example: SSLClient and SSLServer During the course of this paper, several program code fragments have provided examples for tasks that may be included by some particular SSLClient respectively SSLServer implementation. Within this final chapter we will put all together for completely describing a sample SSLClient and SSLServer implementation. According the general line of this paper, we will start in discussing the SSLClient and finish with the description of the SSLServer A SSLClient Implementation Example Our concluding SSLClient implementation is based on the client example briefly introduced in chapter when presenting the SSLSocket class. Remember, that this client connects to a server asking it to send its homepage. For enabling the user to specify the server to be contacted, we extend our SSLClient example about the possibility for reading in the server s name and port number to be listening at runtime. Furthermore, optionally a proxy host and port may be supplied for connecting to the desired server via a proxy. Assuming that a specific client trust decider is implemented, we will include it into our SSLClient implementation. We won t use some particular security provider. Rather we will rely on the default IAIK provider making it superfluous to explicitly set some specific SecurityProvider implementation (see 3.3.1). We have to start with importing all the classes necessary for performing I/O, net and security operations, adding a ptovider, dealing with RSA, PKCS and X.509 structures, and supporting ssl objects: import java.io.*; import java.net.*; import java.security.*; import java.security.cert.x509certificate; import iaik.security.ssl.*; import iaik.security.provider.iaik; import iaik.security.rsa.*; import iaik.pkcs.*; For realizing proxy connections we implement a seperate proxyconnect(..) method that has to be called with the server name and port the proxy shall connect to. Since the contact to the proxy is established by operating on socket streams that are opened only later 105

106 SSLClient within the main procedure, the corresponding class variables have to be declared global for proxyconnect and main method: //stream for writing Strings to the SSLSocket static PrintWriter writer = null; //stream for reading Strings buffered from the SSLSocket static BufferedReader reader = null; The proxyconnect(..) method itself only sends a request message to the proxy for connecting to a specified server at a specified server port using the HTTP protocol. Both, proxy name and port as well as server name and port are supplied at runtime. Note that the proxyconnect(..) method don t need to know the proxy s name. The connection to the proxy is already established when the proxyconnect(..) method is called for forwarding the connection to the specified server. So the the proxyconnect(..) method will operate on streams already opened onto the socket for communicating with the proxy: /** * This method is used for connecting over a SSL proxy. * * This method just sends "CONNECT host:port HTTP/1.0\n\n" (NOT * ENCRYPTED!) to the proxy and displays the messages sent back from * the proxy. * host the host name where a SSL connection should be * established port the port number of that host * IOException if any problem with the socket occurs */ public static void proxyconnect(string host, int port) throws IOException { String request = new String("CONNECT "+host+":"+port+" HTTP/1.0"); //write request onto output stream writer.println(request); writer.println(); writer.flush(); //read and print the proxy s answers String line; do { line = reader.readline(); System.out.println("Proxy sends: "+line); while (line.length() > 0); System.out.println(); Now we are ready to implement the several tasks of the main procedure of our SSLClient class. First, we will read in server name and port just as proxy name and port. If the user will hurt the input format, a failure message shall be printed onto the screen: 106

107 SSLClient //read in server name and server port if (arg.length >= 1) servername = arg[0]; else { System.out.println("Usage: server host:port [proxy:port]\n You can try: ssl3.netscape.com:443\n"); System.exit(0); //determine server name and server port int p = servername.indexof(58); if (p > 0) { serverport = Integer.decode(serverName.substring(p+1)).intValue(); servername = servername.substring(0, p); //read in proxy name and proxy port if (arg.length >= 2) { proxyname = arg[1]; //determine proxy name and proxy port p = proxyname.indexof(58); // proxy port if (p > 0) { proxyport = Integer.decode(proxyName.substring(p+1)).intValue(); proxyname = proxyname.substring(0, p); W For supporting the IAIK-JCE cryptographic algorithm implementations, we must add the IAIK provider (see section 3.3.2): IAIK provider = new IAIK(); Security.addProvider(provider); Within the next lines of program code we first will declare a SSLSocket object. Following this, we create a SSLClientContext object for preparing the security features of the SSLSocket. Assuming our client will support only the two cipher suites SSL_RSA_WITH_IDEA_CBC_SHA and SSL_DH_DSS_WITH_DES_CBC_SHA, we first have to declare an array for being able to hold two cipher suites and subsequently set the appropriate suites. Since our SSLClient shall include a client trust decider for checking the trustworthiness of peer certificates and managing server certificate requests, we have to create a client trust decider object instantiating the SampleClientTrustDecider class as introduced in section Instead of taking the SampleClientTrustDecider, you may implement your own client trust decider. After defining cipher suites and client trust decider, we have to incorporate them into the client context. Note, that we don t have implemented a separate session manager. We agree with the default session manager ( ) for managing the session cache. 107

108 SSLClient SSLSocket s = null; SSLClientContext context = new SSLClientContext(); //define cipher suites to be supported CipherSuite[] cs = new CipherSuite[2]; cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DH_DSS_WITH_DES_CBC_SHA; //enable the two cipher suites context.setenabledciphersuites(cs); //create a client trust decider SampleClientTrustDecider trustdecider = new SampleClientTrustDecider(true); //enable the client trust decider context.settrustdecider(trustdecider); Now, we can start the actual communication with the server. If a proxy name has been specified by the user, a proxy is used as intermediary point. If no proxy is to be used, a SSLSocket is created and connected to the specified port number on the named host. The security features of the SSLSocket are defined by setting the client context. Output and input streams are opened onto the socket for writing data to and reading data from the socket. For printing debugging info to System.out, we enable the debugging stream. If the connection shall go over a proxy, a SSLSocket is created and connected to the specified port number on the named proxy. Since the connect-to-server message sent to the proxy is not to be encrypted, the automatic handshake has to be disabled before opening any streams onto the socket. After the proxy has answered to the client s request, the handshake has to be switched on manually for negotiating the security parameters with the server: if (proxyname == null) { // dont t connect over a proxy s = new SSLSocket(serverName, serverport, context); s.setdebugstream(system.out); //debugging info to System.out reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream()); else { s = new SSLSocket(proxyName, proxyport, context); s.setdebugstream(system.out); //disbale automatic handshake start s.setautohandshake(false); reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream()); //send connect-to-server request to proxy proxyconnect(servername, serverport); //start handshake dialogue manually s.starthandshake(); 108

109 SSLClient After establishing streams onto the socket, our client can send the request for the server s homepage according to the HTTP protocol. It therefore puts the appropriate message onto the output streams. The headers sent back from the server are read in from the input stream and printed to System.out. Before starting the actual data transfer, we will print active cipher suite and compression method of this session onto the screen. Additionally we also will print the certificate chain sent from the server. For obtaining the corresponding entities from the socket, we use the proper methods as described in section 3.4.3: System.out.println("Active cipher suite: " +s.getactiveciphersuite().getname()); System.out.println("Active compression method: " +s.getactivecompressionmethod().getname()); System.out.println("\nServer certificate chain:"); X509Certificate[] chain = s.getpeercertificatechain(); for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": " +chain[i].getsubject()); System.out.println(); String request = new String("GET / HTTP/1.0"); System.out.println("Send request for server homepage..."); writer.println(request); writer.println(); writer.flush(); String line; do { line = reader.readline(); System.out.println("Server sends: "+line); while (line!= null); s.close(); Now, our SSLClient implementation is ready to put all the several parts together for obtaining a view of the complete SSLClient class implementation. import java.io.*; import java.net.*; import java.security.*; import java.security.cert.x509certificate; import iaik.security.ssl.*; import iaik.security.provider.iaik; import iaik.security.rsa.*; import iaik.pkcs.*; /** * Demo SSL client implementation. */ 109

110 SSLClient public class SSLClient { //stream for writing Strings to the SSLSocket static PrintWriter writer = null; //stream for reading Strings buffered from the SSLSocket static BufferedReader reader = null; /** * This method is used for connecting over a SSL proxy. * * This method just sends "CONNECT host:port HTTP/1.0\n\n" (NOT * ENCRYPTED!) to the proxy and displays the messages sent back from * the proxy. * host the host name where a SSL connection should be * established port the port number of that host * IOException if any problem with the socket occurs */ public static void proxyconnect(string host, int port) throws IOException { String request = new String("CONNECT "+host+":"+port+" HTTP/1.0"); //write request onto output stream writer.println(request); writer.println(); writer.flush(); //read and print the proxy s answers String line; do { line = reader.readline(); System.out.println("Proxy sends: "+line); while (line.length() > 0); System.out.println(); /** * Connects to a SSL server and displays the headers sent back by * the server. * * Usage: server host:port [proxy:port] */ public static void main(string arg[]) throws IOException { // for waiting till a key is pressed BufferedReader key = new BufferedReader( new InputStreamReader(System.in)); String servername = null; int serverport = 443; String proxyname = null; int proxyport = 9999; System.out.println("add Provider IAIK...\n"); 110

111 SSLClient IAIK provider = new IAIK(); Security.addProvider(provider); //read in server name and server port if (arg.length >= 1) servername = arg[0]; else { System.out.println("Usage: server host:port [proxy:port]\n You can try: ssl3.netscape.com:443\n"); System.exit(0); //determine server name and server port int p = servername.indexof(58); if (p > 0) { serverport = Integer.decode(serverName.substring(p+1)).intValue(); servername = servername.substring(0, p); //read in proxy name and proxy port if (arg.length >= 2) { proxyname = arg[1]; //determine proxy name and proxy port p = proxyname.indexof(58); // proxy port if (p > 0) { proxyport = Integer.decode(proxyName.substring(p+1)).intValue(); proxyname = proxyname.substring(0, p); SSLSocket s = null; SSLClientContext context = new SSLClientContext(); //define cipher suites to be supported CipherSuite[] cs = new CipherSuite[2]; cs[0] = CipherSuite.SSL_RSA_WITH_IDEA_CBC_SHA; cs[1] = CipherSuite.SSL_DH_DSS_WITH_DES_CBC_SHA; //ebable the two cipher suites context.setenabledciphersuites(cs); //create a client trust decider SampleClientTrustDecider trustdecider = new SampleClientTrustDecider(true); //enable the client trust decider context.settrustdecider(trustdecider); System.out.print("Connect to "+servername+":"+serverport); if (proxyname!= null) System.out.print(" via "+proxyname+":"+proxyport); System.out.println("\n"); try { if (proxyname == null) { // dont t connect over a proxy 111

112 SSLClient s = new SSLSocket(serverName, serverport, context); s.setdebugstream(system.out); //debugging info to System.out reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream()); else { s = new SSLSocket(proxyName, proxyport, context); s.setdebugstream(system.out); //disbale automatic handshake start s.setautohandshake(false); reader = new BufferedReader( new InputStreamReader(s.getInputStream())); writer = new PrintWriter(s.getOutputStream()); //send connect-to-server request to proxy proxyconnect(servername, serverport); //start handshake dialogue manually s.starthandshake(); System.out.println("\nConnection established...\n"); System.out.println("Active cipher suite: " +s.getactiveciphersuite().getname()); System.out.println("Active compression method: " +s.getactivecompressionmethod().getname()); System.out.println("\nServer certificate chain:"); X509Certificate[] chain = s.getpeercertificatechain(); for (int i=0; i<chain.length; i++) System.out.println("Certificate "+i+": " +chain[i].getsubject()); System.out.println(); String request = new String("GET / HTTP/1.0"); System.out.println("Send request for server homepage..."); writer.println(request); writer.println(); writer.flush(); String line; do { line = reader.readline(); System.out.println("Server sends: "+line); while (line!= null); s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (IOException ex) { System.out.println(ex.getMessage()); catch (Exception ex) { System.out.println("Exception: "+ex.getmessage()); //wait till a key is pressed key.readline(); 112

113 SSLClient Note, that the finished version of our SSLClient also includes exception handling. Running the SSLClient we may get a screen output similar to: send client_hello... received server_hello... Server doesn t want to resume a previous session. CipherSuite selected by server: SSL_RSA_EXPORT_WITH_RC4_40_MD5 CompressionMethod selected by server: NULL received Certificate... Server certificate chain C=AT, SP=8010 Graz, L=Steyrergasse 30/I, O=Technical University Graz, OU=Computing and Information Services Center, CN=cisc.tu-graz.ac.at C=US, O=RSA Data Security, Inc., OU=Secure Server Certification Authority received server_hello_done... send ClientKeyExchange... send change_cipher_spec... send finished... received change_cipher_spec... received finished... Connection established... Active cipher suite: SSL_RSA_EXPORT_WITH_RC4_40_MD5 Active compression method: NULL Server certificate chain: Certificate 0: C=AT, SP=8010 Graz, L=Steyrergasse 30/I, O=Technical University Graz, OU=Computing and Information Services Center, CN=cisc.tu-graz.ac.at Certificate 1: C=US, O=RSA Data Security, Inc., OU=Secure Server Certification Authority Send request for server homepage... Server sends: HTTP/ OK Server sends: Server: Netscape-Enterprise/2.0a Server sends: Date: Thu, 22 Jan :05:47 GMT Server sends: Accept-ranges: bytes Server sends: Last-modified: Thu, 20 Mar :55:28 GMT Server sends: Content-length: 2834 Server sends: Content-type: text/html Server sends: Server sends: <HTML> Server sends: Server sends: <HEAD> Server sends: <TITLE>Enterprise Home Page</TITLE> Server sends: </HEAD> Server sends: Server sends: <BODY BGCOLOR="#ffffff" TEXT="#000000" LINK="#0000ff" VLINK="#01424a"> 113

114 SSLClient... Server sends: Server sends: </BODY> Server sends: </HTML> First the handshake messages are reported, followed by the data received from the server including its HTML formatted home page lines. The next - and already last - section provides a sample SSLServer implementation. 114

115 SSLServer A SSLServer Implementation Example As already done within the previous section when presenting a demo SSLServer implementation, we will build up our concluding SSLServer onto the server example briefly introduced in chapter when presenting the SSLServerSocket class. Remember, that this server waits for a SSL connections coming from some browser and only returns the string "SSL Test ok.". Our SSLServer will support all the cipher suites that can be supported when using the actual set of certificates and keys, and it shall claim for client authentication by requesting the client s certificate. Assuming that a specific server trust decider is implemented, we will include it into our SSLServer implementation. Cryptography parameter renegotiation can be switched on by an extra control variable. We won t use some particular security provider. Rather we will rely on the default IAIK provider making it superfluous to explicitly set some specific SecurityProvider implementation (see 3.3.1). We have to start with importing all the classes necessary for performing I/O, net and security operations, adding a provider, dealing with DSA, RSA, DH, PKCS, X.509 and ASN.1 structures and supporting ssl objects. For "reading in" keys and certificates from DER encoded files, we have to import iaik.utils.keyandcertificate, and password based private key de/encryption claims for importing iaik.pkcs.pkcs8.encryptedprivatekeyinfo. import java.io.*; import java.net.*; import java.security.*; import java.math.biginteger; import java.security.cert.x509certificate; import javax.crypto.spec; import iaik.security.ssl.*; import iaik.security.provider.iaik; import iaik.security.dsa.*; import iaik.security.dh.*; import iaik.security.rsa.*; import iaik.pkcs.*; import iaik.asn1.structures.name; import iaik.asn1.*; import iaik.utils.keyandcertificate; import iaik.pkcs.pkcs8.encryptedprivatekeyinfo; The method addline(string line) for writing Strings to a buffering byte array already has been presented in section Since the server s "SSL Test o.k." message shall be displayed by the browser connected to, the server creates the code for a HTML page that prints "SSL Test o.k.". This code line by line is written into the buffer array for 115

116 SSLServer later putting it onto the socket s output stream. The end of each line is marked by a carriage return line feed. The variable pos calculates the number of bytes read into the buffer. static byte[] buffer = new byte[10000]; //initially the buffer is empty static int pos = 0; //carriage return line feed static byte[] crlf = {13, 10; //method for reading a string into a byte array public static void addline(string line) { byte[] arr = line.getbytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2; The method arraycopy(object src, int src_pos, Object dst, int dst_pos) copies an sub array of the source array to the destination array. The sub array of the source array starts at src_pos and is copied to dst_pos within the destination array. The main procedure first adds the IAIK provider, declares a SSLSocket for communicating with the client, and creates a SSLServerContext object that may be supplied with particular properties. IAIK provider = new IAIK(); Security.addProvider(provider); SSLSocket ssl = null; SSLServerContext servercontext = new SSLServerContext(); In contrast to a SSLClient implementation where it is the responsibility of the client trust decider to supply certificates and keys for authentication, the SSLServer immediately has to take care for obtaining appropriate certificates, keys and parameters. Since our SSLServer intends to support all the cipher suites implemented by isasilk, it has to supply all the cryptographic parameters required. Remember that for our example we will read in certificates and keys from files holding IAIK KeyAndCertificate structures (see 3.3.2): try { // specify the DH parameters: BigInteger p = new BigInteger("da583c16d ", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral cipher suites servercontext.setdhparameter(dhparam); // create certificates and private keys and set them to the context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites 116

117 SSLServer kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setrsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setdsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setdhcertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey( new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getpublickey(); KeyPair tempkeypair = new KeyPair(tpk, tsk); servercontext.setrsatempkeypair(tempkeypair); catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getmessage()); System.exit(0); catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); System.exit(0); catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); System.out.println("No server certs found!"); System.exit(0); All generated certificates and corresponding private keys are incorporated into the server context using the several set*certificate(..) methods. Remember, that the SSLServerContext class requires X.509 certificates, as returned by the KeyAndCertifcate s method getcertificatechain (see 3.3.2). Calling the updateciphersuites() method of the SSLServerContext class automatically will enable all the cipher suites that can be supported based on the particular keys and certificates that just have been set: (see ): CipherSuite[] enabledcs = servercontext.updateciphersuites(); 117

118 SSLServer We assume, that a server trust decider has been implemented for checking the trustworthiness of certificates received from the client. We ll take the demo server trust decider of section and set it for the server context: // set a TrustDecider which checks the certificates sent by clients SampleServerTrustDecider trustdecider = new SampleServerTrustDecider(true); servercontext.settrustdecider(trustdecider); In supplying the SampleServerTrustDecider constructor with the boolean true value, we switch on the printing of debugging information to System.out. Our SSLServer shall request a certificate from the client. Therefore, the server has to specify the certification authorities and certificate types it is willing to accept. The server informs its server handshaker to send a certificate request message by supplying the server context s setrequireclientcertificate(..) method with the intended certification authorities and certificate types (see section ): // specifiy the certification authorities to be accepted Name[] acceptedcas = new Name[1]; Name verisign = new Name(); verisign.addrdn(objectid.country, "US"); verisign.addrdn(objectid.organization, "VeriSign, Inc."); verisign.addrdn(objectid.organizationalunit, "Class 1 Public Primary Certification Authority"); acceptedcas[0] = verisign; // specify the certificate types to be accepted byte[] types = new byte[4]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; types[2] = ClientTrustDecider.rsa_ephemeral_dh; types[3] = ClientTrustDecider.dss_ephemeral_dh; // inform the handshaker to send a certificate request message servercontext.setrequireclientcertificate(types, acceptedcas); After defining and setting all particular security properties, a SSLServerSocket object may be created to listen on a specific port for incoming client requests that are accepted by creating a SSLSocket object for connecting to the client. Subsequently, output and input streams are opened onto the socket for communicating with the client. A debug stream cares for printing debugging information to System.out. First, the browser s request is read in and printed to System.out, then the server sends its HTML page lines using the HTTP protocol. If the boolean renegotiate variable is set to true, a renegotiation procedure is initiated for refreshing the cryptographic settings of the current session (see ) before writing to the browser: SSLServerSocket server = new SSLServerSocket(port, servercontext); while (true) { 118

119 SSLServer try { ssl = (SSLSocket)server.accept(); // debug information to System.out ssl.setdebugstream(system.out); OutputStream os = ssl.getoutputstream(); InputStream is = ssl.getinputstream(); //read in data sent from the client byte[] arr = new byte[300]; int l=-1; for (int i=0; i<10 && l<0; i++) l = is.read(arr); System.out.println("client sends: "+l); for (int j=0; j<l; j++) System.out.print((char)arr[j]); if (renegotiate) { //initially set to false System.out.println("renegotiating cipher suite..."); CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_3DES_EDE_CBC_SHA; SSLContext con = ssl.getcontext(); //refresh the enabled cipher suites of this context con.setenabledciphersuites(new_cs); ssl.setcontext(con); //start renegotiation with client ssl.renegotiate(); System.out.println("send reply..."); // send data to client pos = 0; addline("http/ OK"); addline("content-type: text/html"); addline("server: IAIK-SSL Testserver"); addline(""); addline("<html><head>"); addline("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;CHARSET=iso \">"); addline("<title>ssl Test</TITLE>"); addline("</head>"); addline("<body>"); addline("<h1>ssl Test ok.</h1>"); addline("</body>"); addline("</html>"); os.write(buffer, 0, pos); os.flush(); s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); 119

120 SSLServer catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); After closing the SSLSocket, the implementation of all intended tasks is completed and we may take a look on the final version of our demo SSLServer: import java.io.*; import java.net.*; import java.security.*; import java.math.biginteger; import java.security.cert.x509certificate; import javax.crypto.spec; import iaik.security.ssl.*; import iaik.security.provider.iaik; import iaik.security.dsa.*; import iaik.security.dh.*; import iaik.security.rsa.*; import iaik.pkcs.*; import iaik.asn1.structures.name; import iaik.asn1.*; import iaik.utils.keyandcertificate; import iaik.pkcs.pkcs8.encryptedprivatekeyinfo; /** * Demo SSL server implementation. * * Waits for a SSL connection from a SSL browser and returns the * string: * "SSL Test ok.". */ public class SSLServer { static boolean renegotiate = false; //default: no renegotiation static int port = 4433; static byte[] buffer = new byte[10000]; static int pos = 0; static byte[] crlf = {13, 10; public static void addline(string line) { byte[] arr = line.getbytes(); int len = arr.length; System.arraycopy(arr, 0, buffer, pos, len); pos += len; System.arraycopy(crlf, 0, buffer, pos, 2); pos += 2; public static void main(string arg[]) throws IOException { 120

121 SSLServer IAIK provider = new IAIK(); Security.addProvider(provider); SSLSocket ssl = null; SSLServerContext servercontext = new SSLServerContext(); try { // At this time we use this way of specifying the DH parameters // since not before JDK 1.2 a AlgorithmParameterGenerator will // be available BigInteger p = new BigInteger("da583c16d d0e4af756f4cca92 dd4be533b804fb0fed94ef9c8a4403ed d36999db29d776276ba2d3d412 e218f4dd1e084cf6d8003e7c4774e833", 16); BigInteger g = BigInteger.valueOf(2); DHParameterSpec dhparam = new DHParameterSpec(p, g); // set the DH parameter for ephemeral and anon cipher suites servercontext.setdhparameter(dhparam); // create certificates and private keys and set them to the // context: KeyAndCertificate kac; EncryptedPrivateKeyInfo epki; // set the RSA certificate/private key for RSA cipher suites kac = new KeyAndCertificate("certs/serverRSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setrsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DSA certificate/private key for DSA cipher suites kac = new KeyAndCertificate("certs/serverDSA1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setdsacertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the DH certificate/private key for DH cipher suites kac = new KeyAndCertificate("certs/serverDH1024.der"); epki = (EncryptedPrivateKeyInfo)kac.getPrivateKey(); epki.decrypt("this is the passphrase!"); servercontext.setdhcertificate(kac.getcertificatechain(), epki.getprivatekey()); // set the temporary RSA key pair for RSA_EXPORT cipher suites RSAPrivateKey tsk = new RSAPrivateKey( new FileInputStream("certs/tempRSAPrivateKey.der")); PublicKey tpk = tsk.getpublickey(); KeyPair tempkeypair = new KeyPair(tpk, tsk); servercontext.setrsatempkeypair(tempkeypair); catch (InvalidKeyException ex) { System.out.println("InvalidKeyException: "+ex.getmessage()); System.exit(0); catch (NoSuchAlgorithmException ex) { System.out.println("NoSuchAlgorithmException:"+ex.getMessage()); 121

122 SSLServer System.exit(0); catch (GeneralSecurityException ex) { System.out.println("GeneralSecurityException:"+ex.getMessage()); System.exit(0); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); System.out.println("No server certs found!"); System.exit(0); // enable all possible cipher suites CipherSuite[] enabledcs = servercontext.updateciphersuites(); // set a TrustDecider to check the certificates sent by clients SampleServerTrustDecider trustdecider = new SampleServerTrustDecider(true); servercontext.settrustdecider(trustdecider); // specifiy the certification authorities to be accepted Name[] acceptedcas = new Name[1]; Name verisign = new Name(); verisign.addrdn(objectid.country, "US"); verisign.addrdn(objectid.organization, "VeriSign, Inc."); verisign.addrdn(objectid.organizationalunit, "Class 1 Public Primary Certification Authority"); acceptedcas[0] = verisign; // specify the certificate types to be accepted byte[] types = new byte[4]; types[0] = ClientTrustDecider.rsa_sign; types[1] = ClientTrustDecider.dss_sign; types[2] = ClientTrustDecider.rsa_ephemeral_dh; types[3] = ClientTrustDecider.dss_ephemeral_dh; // inform the handshaker to send a certificate request message servercontext.setrequireclientcertificate(types, acceptedcas); System.out.println(serverContext); System.out.println("listening on port "+port+"..."); SSLServerSocket server = new SSLServerSocket(port, servercontext); while (true) { try { ssl = (SSLSocket)server.accept(); // debug information to System.out ssl.setdebugstream(system.out); OutputStream os = ssl.getoutputstream(); InputStream is = ssl.getinputstream(); //read in data sent from the client byte[] arr = new byte[300]; int l=-1; for (int i=0; i<10 && l<0; i++) 122

123 SSLServer l = is.read(arr); System.out.println("client sends: "+l); for (int j=0; j<l; j++) System.out.print((char)arr[j]); if (renegotiate) { //initially set to false System.out.println("renegotiating cipher suite..."); CipherSuite[] new_cs = new CipherSuite[1]; new_cs[0] = CipherSuite.SSL_RSA_WITH_3DES_EDE_CBC_SHA; SSLContext con = ssl.getcontext(); //refresh the enabled cipher suites of this context con.setenabledciphersuites(new_cs); ssl.setcontext(con); //start renegotiation with client ssl.renegotiate(); System.out.println("send reply..."); pos = 0; addline("http/ OK"); addline("content-type: text/html"); addline("server: IAIK-SSL Testserver"); addline(""); addline("<html><head>"); addline("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;CHARSET=iso \">"); addline("<title>ssl Test</TITLE>"); addline("</head>"); addline("<body>"); addline("<h1>ssl Test ok.</h1>"); addline("</body>"); addline("</html>"); os.write(buffer, 0, pos); os.flush(); s.close(); catch (UnknownHostException ex) { System.out.println("UnknownHostException: "+ex.getmessage()); catch (SSLException ex) { System.out.println("SSLException: "+ex.getmessage()); catch (IOException ex) { System.out.println("IOException: "+ex.getmessage()); When running the SSLServer we may get the following screen output reporting SSL security features of the server: add Provider IAIK... enabled cipher suites: 123

124 SSLServer SSL_RSA_WITH_NULL_MD5 SSL_RSA_WITH_NULL_SHA SSL_RSA_EXPORT_WITH_RC4_40_MD5 SSL_RSA_WITH_RC4_MD5 SSL_RSA_WITH_RC4_SHA SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 SSL_RSA_WITH_IDEA_CBC_SHA SSL_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_RSA_WITH_DES_CBC_SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA SSL_DH_DSS_WITH_DES_CBC_SHA SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DH_RSA_WITH_DES_CBC_SHA SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_DSS_WITH_DES_CBC_SHA SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA SSL_DHE_RSA_WITH_DES_CBC_SHA SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 SSL_DH_anon_WITH_RC4_MD5 SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA SSL_DH_anon_WITH_DES_CBC_SHA SSL_DH_anon_WITH_3DES_EDE_CBC_SHA enabled compression methods: NULL RSA certificate chain: C=AT, O=IAIK, CN=einstein, OU=RSA Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification Authority RSA private key: RSA Private Key temporary rsa key pair: RSA Private Key DSA certificate chain: C=AT, O=IAIK, CN=einstein, OU=DSA Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification Authority DSA private key: DSA DH certificate chain: C=AT, O=IAIK, CN=einstein, OU=DH Server Certificate C=AT, O=TU Graz, OU=IAIK, CN=IAIK Test Certification Authority DH private key: DH Private Key DH parameter: OK require client certificate: yes 124

125 SSLServer listening on port When the server indicates to listen on port 4433 we can start a SSL supporting browser (f.i. Netscape Communicator 4.x or Microsoft Internet Explorer 4.x) and enter the URL: " After accepting the certificate, the browser shall display the "SSL Test o.k." message: 125

CS 393 Network Security. Nasir Memon Polytechnic University Module 12 SSL

CS 393 Network Security. Nasir Memon Polytechnic University Module 12 SSL CS 393 Network Security Nasir Memon Polytechnic University Module 12 SSL Course Logistics HW 4 due today. HW 5 will be posted later today. Due in a week. Group homework. DoD Scholarships? NSF Scholarships?

More information

Lecture 9a: Secure Sockets Layer (SSL) March, 2004

Lecture 9a: Secure Sockets Layer (SSL) March, 2004 Internet and Intranet Protocols and Applications Lecture 9a: Secure Sockets Layer (SSL) March, 2004 Arthur Goldberg Computer Science Department New York University artg@cs.nyu.edu Security Achieved by

More information

Overview. SSL Cryptography Overview CHAPTER 1

Overview. SSL Cryptography Overview CHAPTER 1 CHAPTER 1 Secure Sockets Layer (SSL) is an application-level protocol that provides encryption technology for the Internet. SSL ensures the secure transmission of data between a client and a server through

More information

Configuring Secure Socket Layer HTTP

Configuring Secure Socket Layer HTTP This feature provides Secure Socket Layer (SSL) version 3.0 support for the HTTP 1.1 server and HTTP 1.1 client within Cisco IOS software. SSL provides server authentication, encryption, and message integrity

More information

Configuring Secure Socket Layer HTTP

Configuring Secure Socket Layer HTTP This feature provides Secure Socket Layer (SSL) version 3.0 support for the HTTP 1.1 server and HTTP 1.1 client within Cisco IOS software. SSL provides server authentication, encryption, and message integrity

More information

PSK Cipher Suites. isasilk Version 5. Stiftung SIC

PSK Cipher Suites. isasilk Version 5. Stiftung SIC PSK Cipher Suites isasilk Version 5 Stiftung SIC http://jce.iaik.tugraz.at Copyright 2006 2015 Stiftung Secure Information and Communication Technologies SIC Java and all Java-based marks are trademarks

More information

Universität Hamburg. SSL & Company. Fachbereich Informatik SVS Sicherheit in Verteilten Systemen. Security in TCP/IP. UH, FB Inf, SVS, 18-Okt-04 2

Universität Hamburg. SSL & Company. Fachbereich Informatik SVS Sicherheit in Verteilten Systemen. Security in TCP/IP. UH, FB Inf, SVS, 18-Okt-04 2 Universität Hamburg SSL & Company Fachbereich Informatik SVS Sicherheit in Verteilten Systemen Security in TCP/IP UH, FB Inf, SVS, 18-Okt-04 2 SSL/TLS Overview SSL/TLS provides security at TCP layer. Uses

More information

Transport Level Security

Transport Level Security 2 Transport Level Security : Security and Cryptography Sirindhorn International Institute of Technology Thammasat University Prepared by Steven Gordon on 28 October 2013 css322y13s2l12, Steve/Courses/2013/s2/css322/lectures/transport.tex,

More information

Encryption. INST 346, Section 0201 April 3, 2018

Encryption. INST 346, Section 0201 April 3, 2018 Encryption INST 346, Section 0201 April 3, 2018 Goals for Today Symmetric Key Encryption Public Key Encryption Certificate Authorities Secure Sockets Layer Simple encryption scheme substitution cipher:

More information

E-commerce security: SSL/TLS, SET and others. 4.1

E-commerce security: SSL/TLS, SET and others. 4.1 E-commerce security: SSL/TLS, SET and others. 4.1 1 Electronic payment systems Purpose: facilitate the safe and secure transfer of monetary value electronically between multiple parties Participating parties:

More information

HTTPS--HTTP Server and Client with SSL 3.0

HTTPS--HTTP Server and Client with SSL 3.0 The feature provides Secure Socket Layer (SSL) version 3.0 support for the HTTP 1.1 server and HTTP 1.1 client within Cisco IOS software. SSL provides server authentication, encryption, and message integrity

More information

CSCE 715: Network Systems Security

CSCE 715: Network Systems Security CSCE 715: Network Systems Security Chin-Tser Huang huangct@cse.sc.edu University of South Carolina Web Security Web is now widely used by business, government, and individuals But Internet and Web are

More information

WAP Security. Helsinki University of Technology S Security of Communication Protocols

WAP Security. Helsinki University of Technology S Security of Communication Protocols WAP Security Helsinki University of Technology S-38.153 Security of Communication Protocols Mikko.Kerava@iki.fi 15.4.2003 Contents 1. Introduction to WAP 2. Wireless Transport Layer Security 3. Other WAP

More information

Oracle Tuxedo. Using Security in CORBA Applications 11g Release 1 ( ) March 2010

Oracle Tuxedo. Using Security in CORBA Applications 11g Release 1 ( ) March 2010 Oracle Tuxedo Using Security in CORBA Applications 11g Release 1 (11.1.1.1.0) March 2010 Oracle Tuxedo Using Security in CORBA Applications, 11g Release 1 (11.1.1.1.0) Copyright 1996, 2010, Oracle and/or

More information

Distributed Systems. 26. Cryptographic Systems: An Introduction. Paul Krzyzanowski. Rutgers University. Fall 2015

Distributed Systems. 26. Cryptographic Systems: An Introduction. Paul Krzyzanowski. Rutgers University. Fall 2015 Distributed Systems 26. Cryptographic Systems: An Introduction Paul Krzyzanowski Rutgers University Fall 2015 1 Cryptography Security Cryptography may be a component of a secure system Adding cryptography

More information

The World Wide Web is widely used by businesses, government agencies, and many individuals. But the Internet and the Web are extremely vulnerable to

The World Wide Web is widely used by businesses, government agencies, and many individuals. But the Internet and the Web are extremely vulnerable to 1 The World Wide Web is widely used by businesses, government agencies, and many individuals. But the Internet and the Web are extremely vulnerable to compromises of various sorts, with a range of threats

More information

(2½ hours) Total Marks: 75

(2½ hours) Total Marks: 75 (2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Makesuitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together.

More information

HTTPS--HTTP Server and Client with SSL 3.0

HTTPS--HTTP Server and Client with SSL 3.0 The feature provides Secure Socket Layer (SSL) version 3.0 support for the HTTP 1.1 server and HTTP 1.1 client within Cisco IOS XE software. SSL provides server authentication, encryption, and message

More information

Cryptography (Overview)

Cryptography (Overview) Cryptography (Overview) Some history Caesar cipher, rot13 substitution ciphers, etc. Enigma (Turing) Modern secret key cryptography DES, AES Public key cryptography RSA, digital signatures Cryptography

More information

Core Security Services and Bootstrapping in the Cherubim Security System

Core Security Services and Bootstrapping in the Cherubim Security System Core Security Services and Bootstrapping in the Cherubim Security System Charles Willis cfwillis@uiuc.edu Technical Report 2 July 1998 University of Illinois at Urbana-Champaign Department of Computer

More information

Computer Security. 10r. Recitation assignment & concept review. Paul Krzyzanowski. Rutgers University. Spring 2018

Computer Security. 10r. Recitation assignment & concept review. Paul Krzyzanowski. Rutgers University. Spring 2018 Computer Security 10r. Recitation assignment & concept review Paul Krzyzanowski Rutgers University Spring 2018 April 3, 2018 CS 419 2018 Paul Krzyzanowski 1 1. What is a necessary condition for perfect

More information

Cipher Suite Configuration Mode Commands

Cipher Suite Configuration Mode Commands The Cipher Suite Configuration Mode is used to configure the building blocks for SSL cipher suites, including the encryption algorithm, hash function, and key exchange. Important The commands or keywords/variables

More information

CSE 127: Computer Security Cryptography. Kirill Levchenko

CSE 127: Computer Security Cryptography. Kirill Levchenko CSE 127: Computer Security Cryptography Kirill Levchenko October 24, 2017 Motivation Two parties want to communicate securely Secrecy: No one else can read messages Integrity: messages cannot be modified

More information

CSC/ECE 774 Advanced Network Security

CSC/ECE 774 Advanced Network Security Computer Science CSC/ECE 774 Advanced Network Security Topic 2. Network Security Primitives CSC/ECE 774 Dr. Peng Ning 1 Outline Absolute basics Encryption/Decryption; Digital signatures; D-H key exchange;

More information

CSE 3461/5461: Introduction to Computer Networking and Internet Technologies. Network Security. Presentation L

CSE 3461/5461: Introduction to Computer Networking and Internet Technologies. Network Security. Presentation L CS 3461/5461: Introduction to Computer Networking and Internet Technologies Network Security Study: 21.1 21.5 Kannan Srinivasan 11-27-2012 Security Attacks, Services and Mechanisms Security Attack: Any

More information

Computer Security. Two main issues are current regarding security for computer communication systems

Computer Security. Two main issues are current regarding security for computer communication systems Computer Security Two main issues are current regarding security for computer communication systems Data encryption User authentication Encryption and authentication between single users can be performed

More information

APNIC elearning: Cryptography Basics

APNIC elearning: Cryptography Basics APNIC elearning: Cryptography Basics 27 MAY 2015 03:00 PM AEST Brisbane (UTC+10) Issue Date: Revision: Introduction Presenter Sheryl Hermoso Training Officer sheryl@apnic.net Specialties: Network Security

More information

Transport Layer Security

Transport Layer Security CEN585 Computer and Network Security Transport Layer Security Dr. Mostafa Dahshan Department of Computer Engineering College of Computer and Information Sciences King Saud University mdahshan@ksu.edu.sa

More information

CSC 774 Network Security

CSC 774 Network Security CSC 774 Network Security Topic 2. Review of Cryptographic Techniques CSC 774 Dr. Peng Ning 1 Outline Encryption/Decryption Digital signatures Hash functions Pseudo random functions Key exchange/agreement/distribution

More information

Cryptographic Concepts

Cryptographic Concepts Outline Identify the different types of cryptography Learn about current cryptographic methods Chapter #23: Cryptography Understand how cryptography is applied for security Given a scenario, utilize general

More information

IBM i Version 7.2. Security Digital Certificate Manager IBM

IBM i Version 7.2. Security Digital Certificate Manager IBM IBM i Version 7.2 Security Digital Certificate Manager IBM IBM i Version 7.2 Security Digital Certificate Manager IBM Note Before using this information and the product it supports, read the information

More information

Configuring Secure Socket Layer HTTP

Configuring Secure Socket Layer HTTP Finding Feature Information, page 1 Information about Secure Sockets Layer (SSL) HTTP, page 1 How to Configure Secure HTTP Servers and Clients, page 4 Monitoring Secure HTTP Server and Client Status, page

More information

KALASALINGAM UNIVERSITY

KALASALINGAM UNIVERSITY KALASALINGAM UNIVERSITY (Kalasalingam Academy of Research and Education) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CLASS NOTES CRYPTOGRAPHY AND NETWOTK SECURITY (CSE 405) Prepared by M.RAJA AP/CSE

More information

Chapter 8 Web Security

Chapter 8 Web Security Chapter 8 Web Security Web security includes three parts: security of server, security of client, and network traffic security between a browser and a server. Security of server and security of client

More information

Sample excerpt. Virtual Private Networks. Contents

Sample excerpt. Virtual Private Networks. Contents Contents Overview...................................................... 7-3.................................................... 7-5 Overview of...................................... 7-5 IPsec Headers...........................................

More information

Public Key Algorithms

Public Key Algorithms Public Key Algorithms 1 Public Key Algorithms It is necessary to know some number theory to really understand how and why public key algorithms work Most of the public key algorithms are based on modular

More information

Security+ Guide to Network Security Fundamentals, Third Edition. Chapter 11 Basic Cryptography

Security+ Guide to Network Security Fundamentals, Third Edition. Chapter 11 Basic Cryptography Security+ Guide to Network Security Fundamentals, Third Edition Chapter 11 Basic Cryptography Objectives Define cryptography Describe hashing List the basic symmetric cryptographic algorithms 2 Objectives

More information

MTAT Applied Cryptography

MTAT Applied Cryptography MTAT.07.017 Applied Cryptography Transport Layer Security (TLS) Advanced Features University of Tartu Spring 2016 1 / 16 Client Server Authenticated TLS ClientHello ServerHello, Certificate, ServerHelloDone

More information

Chapter 4: Securing TCP connections

Chapter 4: Securing TCP connections Managing and Securing Computer Networks Guy Leduc Chapter 5: Securing TCP connections Computer Networking: A Top Down Approach, 6 th edition. Jim Kurose, Keith Ross Addison-Wesley, March 2012. (section

More information

Wireless Terminal Emulation Advanced Terminal Session Management (ATSM) Device Management Stay-Linked

Wireless Terminal Emulation Advanced Terminal Session Management (ATSM) Device Management Stay-Linked Wireless Terminal Emulation Advanced Terminal Session Management (ATSM) Device Management Stay-Linked Secure Communications Stay-Linked Secure Communications Guide Page 1 Rev. 10.0.0 Dated: 04/26/10 Table

More information

Secure Socket Layer. Security Threat Classifications

Secure Socket Layer. Security Threat Classifications Secure Socket Layer 1 Security Threat Classifications One way to classify Web security threats in terms of the type of the threat: Passive threats Active threats Another way to classify Web security threats

More information

Kurose & Ross, Chapters (5 th ed.)

Kurose & Ross, Chapters (5 th ed.) Kurose & Ross, Chapters 8.2-8.3 (5 th ed.) Slides adapted from: J. Kurose & K. Ross \ Computer Networking: A Top Down Approach (5 th ed.) Addison-Wesley, April 2009. Copyright 1996-2010, J.F Kurose and

More information

Telemetry Data Sharing Using S/MIME

Telemetry Data Sharing Using S/MIME Telemetry Data Sharing Using S/MIME Item Type text; Proceedings Authors Kalibjian, Jeffrey R. Publisher International Foundation for Telemetering Journal International Telemetering Conference Proceedings

More information

1.264 Lecture 28. Cryptography: Asymmetric keys

1.264 Lecture 28. Cryptography: Asymmetric keys 1.264 Lecture 28 Cryptography: Asymmetric keys Next class: Anderson chapters 20. Exercise due before class (Reading doesn t cover same topics as lecture) 1 Asymmetric or public key encryption Receiver

More information

CS Computer Networks 1: Authentication

CS Computer Networks 1: Authentication CS 3251- Computer Networks 1: Authentication Professor Patrick Traynor 4/14/11 Lecture 25 Announcements Homework 3 is due next class. Submit via T-Square or in person. Project 3 has been graded. Scores

More information

Overview of SSL/TLS. Luke Anderson. 12 th May University Of Sydney.

Overview of SSL/TLS. Luke Anderson. 12 th May University Of Sydney. Overview of SSL/TLS Luke Anderson luke@lukeanderson.com.au 12 th May 2017 University Of Sydney Overview 1. Introduction 1.1 Raw HTTP 1.2 Introducing SSL/TLS 2. Certificates 3. Attacks Introduction Raw

More information

06/02/ Local & Metropolitan Area Networks. 0. Overview. Terminology ACOE322. Lecture 8 Network Security

06/02/ Local & Metropolitan Area Networks. 0. Overview. Terminology ACOE322. Lecture 8 Network Security 1 Local & Metropolitan Area Networks ACOE322 Lecture 8 Network Security Dr. L. Christofi 1 0. Overview As the knowledge of computer networking and protocols has become more widespread, so the threat of

More information

Outline. Data Encryption Standard. Symmetric-Key Algorithms. Lecture 4

Outline. Data Encryption Standard. Symmetric-Key Algorithms. Lecture 4 EEC 693/793 Special Topics in Electrical Engineering Secure and Dependable Computing Lecture 4 Department of Electrical and Computer Engineering Cleveland State University wenbing@ieee.org Outline Review

More information

The question paper contains 40 multiple choice questions with four choices and students will have to pick the correct one (each carrying ½ marks.).

The question paper contains 40 multiple choice questions with four choices and students will have to pick the correct one (each carrying ½ marks.). Time: 3hrs BCA III Network security and Cryptography Examination-2016 Model Paper 2 M.M:50 The question paper contains 40 multiple choice questions with four choices and students will have to pick the

More information

SEEM4540 Open Systems for E-Commerce Lecture 03 Internet Security

SEEM4540 Open Systems for E-Commerce Lecture 03 Internet Security SEEM4540 Open Systems for E-Commerce Lecture 03 Internet Security Consider 2. Based on DNS, identified the IP address of www.cuhk.edu.hk is 137.189.11.73. 1. Go to http://www.cuhk.edu.hk 3. Forward the

More information

Computer Security. 08. Cryptography Part II. Paul Krzyzanowski. Rutgers University. Spring 2018

Computer Security. 08. Cryptography Part II. Paul Krzyzanowski. Rutgers University. Spring 2018 Computer Security 08. Cryptography Part II Paul Krzyzanowski Rutgers University Spring 2018 March 23, 2018 CS 419 2018 Paul Krzyzanowski 1 Block ciphers Block ciphers encrypt a block of plaintext at a

More information

Today s Lecture. Secure Communication. A Simple Protocol. Remote Authentication. A Simple Protocol. Rules. I m Alice. I m Alice

Today s Lecture. Secure Communication. A Simple Protocol. Remote Authentication. A Simple Protocol. Rules. I m Alice. I m Alice Today s Lecture Secure Communication Tom Chothia Computer Security, Lecture 8 Protocols in and ob notation Some Key Establishment Protocol Secure Sockets Layer (SSL) / Transport Later Security (TLS) Certificates

More information

CS 161 Computer Security

CS 161 Computer Security Popa & Wagner Spring 2016 CS 161 Computer Security Midterm 2 Print your name:, (last) (first) I am aware of the Berkeley Campus Code of Student Conduct and acknowledge that academic misconduct will be

More information

Encryption Algorithms Authentication Protocols Message Integrity Protocols Key Distribution Firewalls

Encryption Algorithms Authentication Protocols Message Integrity Protocols Key Distribution Firewalls Security Outline Encryption Algorithms Authentication Protocols Message Integrity Protocols Key Distribution Firewalls Overview Cryptography functions Secret key (e.g., DES) Public key (e.g., RSA) Message

More information

Computers and Security

Computers and Security The contents of this Supporting Material document have been prepared from the Eight units of study texts for the course M150: Date, Computing and Information, produced by The Open University, UK. Copyright

More information

BCA III Network security and Cryptography Examination-2016 Model Paper 1

BCA III Network security and Cryptography Examination-2016 Model Paper 1 Time: 3hrs BCA III Network security and Cryptography Examination-2016 Model Paper 1 M.M:50 The question paper contains 40 multiple choice questions with four choices and student will have to pick the correct

More information

PROTECTING CONVERSATIONS

PROTECTING CONVERSATIONS PROTECTING CONVERSATIONS Basics of Encrypted Network Communications Naïve Conversations Captured messages could be read by anyone Cannot be sure who sent the message you are reading Basic Definitions Authentication

More information

Introduction to Cryptography and Security Mechanisms: Unit 5. Public-Key Encryption

Introduction to Cryptography and Security Mechanisms: Unit 5. Public-Key Encryption Introduction to Cryptography and Security Mechanisms: Unit 5 Public-Key Encryption Learning Outcomes Explain the basic principles behind public-key cryptography Recognise the fundamental problems that

More information

Cryptography in Lotus Notes/Domino Pragmatic Introduction for Administrators

Cryptography in Lotus Notes/Domino Pragmatic Introduction for Administrators Cryptography in Lotus Notes/Domino Pragmatic Introduction for Administrators Belfast, 11-Nov-2010 Innovative Software Solutions. Thomas Bahn - graduated in mathematics, University of Hannover - developing

More information

David Wetherall, with some slides from Radia Perlman s security lectures.

David Wetherall, with some slides from Radia Perlman s security lectures. David Wetherall, with some slides from Radia Perlman s security lectures. djw@cs.washington.edu Networks are shared: Want to secure communication between legitimate participants from others with (passive

More information

Outline. Public Key Cryptography. Applications of Public Key Crypto. Applications (Cont d)

Outline. Public Key Cryptography. Applications of Public Key Crypto. Applications (Cont d) Outline AIT 682: Network and Systems Security 1. Introduction 2. RSA 3. Diffie-Hellman Key Exchange 4. Digital Signature Standard Topic 5.2 Public Key Cryptography Instructor: Dr. Kun Sun 2 Public Key

More information

Lecture 30. Cryptography. Symmetric Key Cryptography. Key Exchange. Advanced Encryption Standard (AES) DES. Security April 11, 2005

Lecture 30. Cryptography. Symmetric Key Cryptography. Key Exchange. Advanced Encryption Standard (AES) DES. Security April 11, 2005 Lecture 30 Security April 11, 2005 Cryptography K A ciphertext Figure 7.3 goes here K B symmetric-key crypto: sender, receiver keys identical public-key crypto: encrypt key public, decrypt key secret Symmetric

More information

CSCI 454/554 Computer and Network Security. Topic 5.2 Public Key Cryptography

CSCI 454/554 Computer and Network Security. Topic 5.2 Public Key Cryptography CSCI 454/554 Computer and Network Security Topic 5.2 Public Key Cryptography Outline 1. Introduction 2. RSA 3. Diffie-Hellman Key Exchange 4. Digital Signature Standard 2 Introduction Public Key Cryptography

More information

Introduction to Cryptography and Security Mechanisms. Abdul Hameed

Introduction to Cryptography and Security Mechanisms. Abdul Hameed Introduction to Cryptography and Security Mechanisms Abdul Hameed http://informationtechnology.pk Before we start 3 Quiz 1 From a security perspective, rather than an efficiency perspective, which of the

More information

key distribution requirements for public key algorithms asymmetric (or public) key algorithms

key distribution requirements for public key algorithms asymmetric (or public) key algorithms topics: cis3.2 electronic commerce 24 april 2006 lecture # 22 internet security (part 2) finish from last time: symmetric (single key) and asymmetric (public key) methods different cryptographic systems

More information

Key Exchange. References: Applied Cryptography, Bruce Schneier Cryptography and Network Securiy, Willian Stallings

Key Exchange. References: Applied Cryptography, Bruce Schneier Cryptography and Network Securiy, Willian Stallings Key Exchange References: Applied Cryptography, Bruce Schneier Cryptography and Network Securiy, Willian Stallings Outlines Primitives Root Discrete Logarithm Diffie-Hellman ElGamal Shamir s Three Pass

More information

Outline. CSCI 454/554 Computer and Network Security. Introduction. Topic 5.2 Public Key Cryptography. 1. Introduction 2. RSA

Outline. CSCI 454/554 Computer and Network Security. Introduction. Topic 5.2 Public Key Cryptography. 1. Introduction 2. RSA CSCI 454/554 Computer and Network Security Topic 5.2 Public Key Cryptography 1. Introduction 2. RSA Outline 3. Diffie-Hellman Key Exchange 4. Digital Signature Standard 2 Introduction Public Key Cryptography

More information

SSL/TLS & 3D Secure. CS 470 Introduction to Applied Cryptography. Ali Aydın Selçuk. CS470, A.A.Selçuk SSL/TLS & 3DSec 1

SSL/TLS & 3D Secure. CS 470 Introduction to Applied Cryptography. Ali Aydın Selçuk. CS470, A.A.Selçuk SSL/TLS & 3DSec 1 SSL/TLS & 3D Secure CS 470 Introduction to Applied Cryptography Ali Aydın Selçuk CS470, A.A.Selçuk SSL/TLS & 3DSec 1 SSLv2 Brief History of SSL/TLS Released in 1995 with Netscape 1.1 Key generation algorithm

More information

Security Protocols and Infrastructures. Winter Term 2010/2011

Security Protocols and Infrastructures. Winter Term 2010/2011 Winter Term 2010/2011 Chapter 4: Transport Layer Security Protocol Contents Overview Record Protocol Cipher Suites in TLS 1.2 Handshaking Protocols Final Discussion 2 Contents Overview Record Protocol

More information

Modern cryptography 2. CSCI 470: Web Science Keith Vertanen

Modern cryptography 2. CSCI 470: Web Science Keith Vertanen Modern cryptography 2 CSCI 470: Web Science Keith Vertanen Modern cryptography Overview Asymmetric cryptography Diffie-Hellman key exchange (last time) Pubic key: RSA Pretty Good Privacy (PGP) Digital

More information

Protocols, Technologies and Standards Secure network protocols for the OSI stack P2.1 WLAN Security WPA, WPA2, IEEE i, IEEE 802.1X P2.

Protocols, Technologies and Standards Secure network protocols for the OSI stack P2.1 WLAN Security WPA, WPA2, IEEE i, IEEE 802.1X P2. P2 Protocols, Technologies and Standards Secure network protocols for the OSI stack P2.1 WLAN Security WPA, WPA2, IEEE 802.11i, IEEE 802.1X P2.2 IP Security IPsec transport mode (host-to-host), ESP and

More information

CS 6324: Information Security More Info on Key Establishment: RSA, DH & QKD

CS 6324: Information Security More Info on Key Establishment: RSA, DH & QKD ERIK JONSSON SCHOOL OF ENGINEERING & COMPUTER SCIENCE Cyber Security Research and Education Institute CS 6324: Information Security Dr. Junia Valente Department of Computer Science The University of Texas

More information

Cryptography SSL/TLS. Network Security Workshop. 3-5 October 2017 Port Moresby, Papua New Guinea

Cryptography SSL/TLS. Network Security Workshop. 3-5 October 2017 Port Moresby, Papua New Guinea Cryptography SSL/TLS Network Security Workshop 3-5 October 2017 Port Moresby, Papua New Guinea 1 History Secure Sockets Layer was developed by Netscape in 1994 as a protocol which permitted persistent

More information

Cryptography MIS

Cryptography MIS Cryptography MIS-5903 http://community.mis.temple.edu/mis5903sec011s17/ Cryptography History Substitution Monoalphabetic Polyalphabetic (uses multiple alphabets) uses Vigenere Table Scytale cipher (message

More information

Acronyms. International Organization for Standardization International Telecommunication Union ITU Telecommunication Standardization Sector

Acronyms. International Organization for Standardization International Telecommunication Union ITU Telecommunication Standardization Sector Acronyms 3DES AES AH ANSI CBC CESG CFB CMAC CRT DoS DEA DES DoS DSA DSS ECB ECC ECDSA ESP FIPS IAB IETF IP IPsec ISO ITU ITU-T Triple DES Advanced Encryption Standard Authentication Header American National

More information

ח'/סיון/תשע "א. RSA: getting ready. Public Key Cryptography. Public key cryptography. Public key encryption algorithms

ח'/סיון/תשע א. RSA: getting ready. Public Key Cryptography. Public key cryptography. Public key encryption algorithms Public Key Cryptography Kurose & Ross, Chapters 8.28.3 (5 th ed.) Slides adapted from: J. Kurose & K. Ross \ Computer Networking: A Top Down Approach (5 th ed.) AddisonWesley, April 2009. Copyright 19962010,

More information

L13. Reviews. Rocky K. C. Chang, April 10, 2015

L13. Reviews. Rocky K. C. Chang, April 10, 2015 L13. Reviews Rocky K. C. Chang, April 10, 2015 1 Foci of this course Understand the 3 fundamental cryptographic functions and how they are used in network security. Understand the main elements in securing

More information

Introduction to Cryptography. Vasil Slavov William Jewell College

Introduction to Cryptography. Vasil Slavov William Jewell College Introduction to Cryptography Vasil Slavov William Jewell College Crypto definitions Cryptography studies how to keep messages secure Cryptanalysis studies how to break ciphertext Cryptology branch of mathematics,

More information

Data Security and Privacy. Topic 14: Authentication and Key Establishment

Data Security and Privacy. Topic 14: Authentication and Key Establishment Data Security and Privacy Topic 14: Authentication and Key Establishment 1 Announcements Mid-term Exam Tuesday March 6, during class 2 Need for Key Establishment Encrypt K (M) C = Encrypt K (M) M = Decrypt

More information

Dr. Jinyuan (Stella) Sun Dept. of Electrical Engineering and Computer Science University of Tennessee Fall 2010

Dr. Jinyuan (Stella) Sun Dept. of Electrical Engineering and Computer Science University of Tennessee Fall 2010 CS 494/594 Computer and Network Security Dr. Jinyuan (Stella) Sun Dept. of Electrical Engineering and Computer Science University of Tennessee Fall 2010 1 Public Key Cryptography Modular Arithmetic RSA

More information

Summary of PGP Services

Summary of PGP Services Table 15.1 Summary of PGP Services Function Algorithms Used Description Digital signature Message encryption Compression Email compatibility DSS/SHA or RSA/SHA CAST or IDEA or Three-key Triple DES with

More information

Information Security CS 526

Information Security CS 526 Information Security CS 526 Topic 14: Key Distribution & Agreement, Secure Communication Topic 14: Secure Communication 1 Readings for This Lecture On Wikipedia Needham-Schroeder protocol (only the symmetric

More information

ASYMMETRIC CRYPTOGRAPHY

ASYMMETRIC CRYPTOGRAPHY ASYMMETRIC CRYPTOGRAPHY CONTENT: 1. Number Theory 2. One Way Function 3. Hash Function 4. Digital Signature 5. RSA (Rivest-Shamir Adleman) References: 1. Applied Cryptography, Bruce Schneier 2. Cryptography

More information

Configuring SSL. SSL Overview CHAPTER

Configuring SSL. SSL Overview CHAPTER 7 CHAPTER This topic describes the steps required to configure your ACE appliance as a virtual Secure Sockets Layer (SSL) server for SSL initiation or termination. The topics included in this section are:

More information

Computer Security 3/23/18

Computer Security 3/23/18 s s encrypt a block of plaintext at a time and produce ciphertext Computer Security 08. Cryptography Part II Paul Krzyzanowski DES & AES are two popular block ciphers DES: 64 bit blocks AES: 128 bit blocks

More information

Displaying SSL Configuration Information and Statistics

Displaying SSL Configuration Information and Statistics CHAPTER 7 Displaying SSL Configuration Information and Statistics This chapter describes the show commands available for displaying CSS SSL configuration information and statistics and an explanation of

More information

Security Protocols and Infrastructures. Winter Term 2015/2016

Security Protocols and Infrastructures. Winter Term 2015/2016 Winter Term 2015/2016 Nicolas Buchmann (Harald Baier) Chapter 8: Transport Layer Security Protocol Key Questions Application context of TLS? Which security goals shall be achieved? Approaches? 2 Contents

More information

CS 356 Internet Security Protocols. Fall 2013

CS 356 Internet Security Protocols. Fall 2013 CS 356 Internet Security Protocols Fall 2013 Review Chapter 1: Basic Concepts and Terminology Chapter 2: Basic Cryptographic Tools Chapter 3 User Authentication Chapter 4 Access Control Lists Chapter 5

More information

Computer Networks 1 (Mạng Máy Tính 1) Lectured by: Dr. Phạm Trần Vũ

Computer Networks 1 (Mạng Máy Tính 1) Lectured by: Dr. Phạm Trần Vũ Computer Networks 1 (Mạng Máy Tính 1) Lectured by: Dr. Phạm Trần Vũ Chapter 8 Network Security Computer Networking: A Top Down Approach, 5 th edition. Jim Kurose, Keith Ross Addison-Wesley, April 2009.

More information

Ubuntu (Artful Aardvark)

Ubuntu (Artful Aardvark) NAME ciphers SSL cipher display and cipher list tool. SYNOPSIS openssl ciphers [ v] [ V] [ ssl2] [ ssl3] [ tls1] [cipherlist] DESCRIPTION The ciphers command converts textual OpenSSL cipher lists into

More information

3 Symmetric Key Cryptography 3.1 Block Ciphers Symmetric key strength analysis Electronic Code Book Mode (ECB) Cipher Block Chaining Mode (CBC) Some

3 Symmetric Key Cryptography 3.1 Block Ciphers Symmetric key strength analysis Electronic Code Book Mode (ECB) Cipher Block Chaining Mode (CBC) Some 3 Symmetric Key Cryptography 3.1 Block Ciphers Symmetric key strength analysis Electronic Code Book Mode (ECB) Cipher Block Chaining Mode (CBC) Some popular block ciphers Triple DES Advanced Encryption

More information

Computer Security: Principles and Practice

Computer Security: Principles and Practice Computer Security: Principles and Practice Chapter 2 Cryptographic Tools First Edition by William Stallings and Lawrie Brown Lecture slides by Lawrie Brown Cryptographic Tools cryptographic algorithms

More information

Configuring SSL CHAPTER

Configuring SSL CHAPTER 7 CHAPTER This chapter describes the steps required to configure your ACE appliance as a virtual Secure Sockets Layer (SSL) server for SSL initiation or termination. The topics included in this section

More information

But where'd that extra "s" come from, and what does it mean?

But where'd that extra s come from, and what does it mean? SSL/TLS While browsing Internet, some URLs start with "http://" while others start with "https://"? Perhaps the extra "s" when browsing websites that require giving over sensitive information, like paying

More information

Sankalchand Patel College of Engineering, Visnagar Department of Computer Engineering & Information Technology. Question Bank

Sankalchand Patel College of Engineering, Visnagar Department of Computer Engineering & Information Technology. Question Bank Sankalchand Patel College of Engineering, Visnagar Department of Computer Engineering & Information Technology Question Bank Subject: Information Security (160702) Class: BE Sem. VI (CE/IT) Unit-1: Conventional

More information

Digital Certificates Demystified

Digital Certificates Demystified Digital Certificates Demystified Ross Cooper, CISSP IBM Corporation RACF/PKI Development Poughkeepsie, NY Email: rdc@us.ibm.com August 9 th, 2012 Session 11622 Agenda Cryptography What are Digital Certificates

More information

Cryptography & Key Exchange Protocols. Faculty of Computer Science & Engineering HCMC University of Technology

Cryptography & Key Exchange Protocols. Faculty of Computer Science & Engineering HCMC University of Technology Cryptography & Key Exchange Protocols Faculty of Computer Science & Engineering HCMC University of Technology Outline 1 Cryptography-related concepts 2 3 4 5 6 7 Key channel for symmetric cryptosystems

More information

Security. Communication security. System Security

Security. Communication security. System Security Security Communication security security of data channel typical assumption: adversary has access to the physical link over which data is transmitted cryptographic separation is necessary System Security

More information

Cryptography and secure channel. May 17, Networks and Security. Thibault Debatty. Outline. Cryptography. Public-key encryption

Cryptography and secure channel. May 17, Networks and Security. Thibault Debatty. Outline. Cryptography. Public-key encryption and secure channel May 17, 2018 1 / 45 1 2 3 4 5 2 / 45 Introduction Simplified model for and decryption key decryption key plain text X KE algorithm KD Y = E(KE, X ) decryption ciphertext algorithm X

More information

COSC 301 Network Management. Lecture 15: SSL/TLS and HTTPS

COSC 301 Network Management. Lecture 15: SSL/TLS and HTTPS COSC 301 Network Management Lecture 15: SSL/TLS and HTTPS Zhiyi Huang Computer Science, University of Otago COSC301 Lecture 15: SSL/TLS and HTTPS 1 Today s Focus WWW WWW How to secure web applications?

More information