You are on page 1of 145

CNS05P07A

CNS05P07A
Web Secure

Web Secure Programming


Programming

TRAINING FOR
INFORMATION PROCESSING

NOTES

OKINAWA INTERNATIONAL CENTRE


JAPAN INTERNATIONAL COOPERATION AGENCY
Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION

All products, names and services used in this book may be trademarks or registered
trademarks of their respective owners.

No part of this text book may be copied or reproduced in any way and by any means
without the permission of the copyright holder .
Contents

Web Secure Programming ................................................................................ 1

Objectives ........................................................................................................... 2

Contents ............................................................................................................... 3

Chapter 1 Security Outline .......................................................................... 1-1

1.1 Security and Java Language 1-2

1.2 Web Application Security 1-8

1.3 Security Measures for Web Applications 1-9

Chapter 2 The Encrypt Method ...................................................................... 2-1

2.1 Java Cryptography Architecture 2-2

2.2 JCE 2-11

2.3 KeyGenerator Class 2-12

2.4 Cipher Class 2-17

Chapter 3 Message Digest.............................................................................. 3-1

3.1 Message Digest 3-2

3.2 MD5/SHA 3-4

3.3 MessageDigest Class 3-5

3.4 Applications Executing Message Digest 3-9

Chapter 4 Digital Signature and Certificate................................................... 4-1

4.1 Digital Signature 4-2

4.2 Application Examples of Digital Signature 4-4

4.3 Certificate 4-13

4.4 Signature Utilityies 4-16

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.5 X.509 Certificate 4-17

4.6 keytool Utility 4-19

4.7 jarsigner Utility 4-32

Chapter 5 JAAS(Java Authentication and Authorization Service) .............. 5-1

5.1 JAAS 5-2

5.2 JAAS Core Class/Interface 5-3

5.3 Login Module Configuration File 5-6

5.4 LoginContext 5-10

5.5 LoginModule 5-12

5.6 Callback 5-15

5.7 JAAS Security Policy File 5-27

5.8 Policy Tool Utility 5-29

Chapter 6 JSSE(Java Secure Socket Extension).......................................... 6-1

6.1 JSSE 6-2

6.2 Socket Factory 6-4

6.3 Keystore and Truststore 6-10

6.4 Example of Communication Using JSSE 6-11

Chapter 7 Web Application Security.............................................................. 7-1

7.1 Java Servlet Security 7-2

7.2 User Authentication via Tomcat 7-3

7.3 Tomcat/SSL Settings 7-4

7.4 Realms 7-5

7.5 Secure Application Programming 7-6

ii

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


Web Secure Programming

Web Secure Programming 1

Sun Microsystems™, Java™,JDK™, J2SE™,JSP™, JVM™ , Java Server Page™,JDBC™


and JavaScript™ are trademarks or registered trademarks of Sun Microsystems, Inc. in the
United States and other countries.
Microsoft® software , Windows® operating system are either registered trademarks or
trademarks of Microsoft Corporation in the United States and/or other countries.

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


Objectives

Upon completion of this class, you are expected to :

1. Understand the outline of web application security.

2. Explain the API of encryption provided by Java 2 SDK.

3. Explain about message digests.

4. Explain about JAAS (Java Authentication and Authorization Service).

5. Explain about JSSE (Java Secure Socket Extension).

Web Secure Programming 2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


Contents

Chapter 1. Security Outline


Chapter 2. The Encrypt Method
Chapter 3. Message Digest
Chapter 4. Digital Signature and Certificate
Chapter 5. JAAS(Java Authentication and Authorization Service)
Chapter 6. JSSE(Java Secure Socket Extension)
Chapter 7. Web Application Security

Web Secure Programming 3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1. Security Outline

1.1 Security and Java Language

1.2 Web Application Security

1.3 Security Measures for Web Applications

1. Security Outline 1-1

1-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1 Security and Java Language

1.1.1 Security and Java Language

1.1.2 Sandbox Model

1.1.3 Improvement of Sandbox Model

1.1 Security and Java Language 1-2

1-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1.1 Security and Java Language (1/3)
Data transactions in open networks are always
at risk.
Data

Tapping
User Application
Server
Alteration

Malicious
Attacker user

1.1.1 Security and Java Language 1-3

Transactions taking place via open networks such as the Internet are always at risk. There are
cases of network tapping where a attacker eavesdrops on the data exchanged on the network
and where a attacker alters data on a server in order to sneak hazardous programs into the
server.
With the explosive increase of Internet usage, the risk is growing rapidly. It is thus
particularly necessary to take security into account when designing systems involving Web
applications.

1-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1.1 Security and Java Language (2/3)
By making use of encryption, authentication and similar
processing, it is possible to construct secure systems.

Encrypted Encrypted
data communication

Detection of
alteration
Tapping
User Application
Server
Sophisticated Alteration
authentication
processing Malicious
Malicious user
user

1.1.1 Security and Java Language 1-4

It is possible to construct secure systems by making use of encryption, sophisticated


authentication processing and other measures. It is possible to prevent data tapping by
encrypting the data transaction and detect alterations by checking the data exchanged between
clients and servers. Furthermore, sophisticated authentication processing plays an important
role when preventing user spoofing. There are various methods to implement such encryption
and authentication processing and system developers are required to make appropriate choices.

1-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1.1 Security and Java Language (3/3)
Java includes various security functions for
executing code safely.

Authentication processing Access management


JAAS Security Manager

JAVA

Digital signature Cryptography architecture


X.509 JCE, JSSE

1.1.1 Security and Java Language 1-5

Java comes with various security functions as standard. Many of these functions used to be
provided as optional packages at first, but they have been incorporated in the standard class
libraries as standard functions since Java 1.4.
Security Manager, which uses a security model called sandbox, controls access to computer
resources such as hard disks etc.
JCE (Java Cryptography Extension) and JSSE (Java Secure Socket Extension) are libraries
that perform encryption processing. JCE can implement message encryption and unique
encryption algorithms. JSSE can encrypt socket-based communication such as HTTPS.
JAAS provides a function to perform authentication using user-specific information such as
ID and password and allows central management of the authentication processing, including
when multiple applications are involved.
Keytool, jarsigner and other tools allow appending signatures to JAR files created using
X.509 certification processing. Under normal circumstances, certificates are issued by third
party organizations that conduct fair verification; it is possible to heighten the reliability and
safety of programs by appending signatures to data transferred via networks.

1-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1.2 Sandbox Model
When executing programs downloaded via networks and
the like, access to various resources should be restricted.

Access
Applet etc. Various resources
restriction
Java Download Sandbox
program
Java
program
Remote code
File system
Java
program
Local code JVM
(Java Virtual Machine)
Network

1.1.2 Sandbox Model 1-6

The Java runtime environment JVM implements a security model called sandbox. The
Sandbox model restricts all access to various resources on the computers on which they run,
such as the local file system and network resources when executing remote code such as
Applets and Java programs downloaded from the Internet.
That is, it permits local code located on the computer itself to access resources as reliable
code, but only permits remote code to access a strictly limited set of resources on the system,
as the remote code cannot be considered reliable.

Note that sandbox is a concept; no class called Sandbox or similar is implemented.

1-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.1.3 Improvement of Sandbox Model
Java2 executes security processing for all code,
including local code.
Access
JVM(Java Virtual Machine) restriction Various resource
Sandbox

Java Domain A
Class
program
Loader
Domain B File system
Java Security
program Manager

Domain C
Security
Policy Network

1.1.3 Improvement of Sandbox Model 1-7

In Java2, the security model has been improved; security processing is now performed at
execution of all programs, not only for remote code, but also for local code.
When JVM is launched, the data of the Security Policy file is read and stored in the Security
Manager object first. The Security Policy file specifies information concerning access rights,
including access permission to various resources in units called protection domains. Protection
domains refer to specifications of certain access rights, and all classes are executed under one
of these protection domains. The Security Policy file is located at
JRE_HOME/lib/security/java.policy.
ClassLoader is a class included in the java.lang package; it is used when reading class
definition data from the file system or other sources. When a class is read, Security Manager
determines the protection domain, whereby its access rights to various resources are
determined.
Local code is now subjected to the security control, but access to various resources are
granted as standard for the domain of local code.

1-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.2 Web Application Security
Security measures must be taken for Web
applications that are made available to the public
via the Internet and other open networks.
Communication
may be tapped Web container
Web browser
Request

Web
server Web
Response application

User Program
impersonation, substitution,
spoofing etc. rewriting

1.2 Web Application Security 1-8

Various security measures must be taken for Web applications that are made available to the
public via the Internet and other open networks used by an unspecified number of users.
・When exchanging personal information and other important information, the communicated
data may be tapped on open networks.
・In the majority of cases, Web applications perform authentication processing to identify
users, but attackers may impersonate or spoof users.
・There is a risk that attackers may substitute or alter programs of Web applications.

1-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.3 Security Measures for Web Applications

1.3.1 Communication Encryption via SSL

1.3.2 Centralized Management of Authentication Processing

1.3.3 Digital Signatures of Programs

1.3.4 Continuous Measures

1.3 Security Measures for Web Applications 1-9

1-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.3.1 Communication Encryption via SSL
It is possible to use SSL to encrypt communication
between a Web application and a browser.

Web container
Web browser Encryption

HTTPS Web
Server Web
application
Request
Public key response Private key

1.3.1 Communication Encryption via SSL 1-10

By using SSL (Secure Socket Layer), it is possible to encrypt communication between a Web
browser and a Web server. The protocol that encrypts HTTP using SSL technologies is called
HTTPS.
In the HTTP protocol, the POST/GET parameters exchanged as part of requests to a Web
server and responses from the Web server are streamed via the network as is; thus, if the
network is tapped, the data may be stolen. HTTPS, on the other hand, encrypts all transactions
with the Web server; thus, even if the network is tapped by a attacker, it is difficult to restore
the data.
In HTTPS, the client uses the public key of the server implemented in the Web browser to
securely transfer a secret key used for the actual encrypted communication.

1-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.3.2 Centralized Management of Authentication Processing

By centralizing the user authentication processing, it


is possible to perform comprehensive access
management efficiently.
Authentication
processing Web Web
application application

Web
Web application
application
Authentication Web
Web browser processing Web browser application
Web Authentication
Authentication application processing
processing
User database
User database

1.3.2 Centralized Management of Authentication Processing 1-11

It is difficult to take completely foolproof countermeasures against user impersonation and


spoofing due to various factors such as information leakage caused by human errors.
It is, however, possible to reduce the burden on users involved in ID management by
employing centralized authentication, which allows using various Web applications with a
single user ID and password. Moreover, since all the methods and procedures of
authentication processing can be integrated in centralized authentication management, the
security and reliability can be improved from a system development point of view, which
means that the development man-hours can be reduced and comprehensive access
management to various resources becomes possible.

1-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.3.3 Digital Signatures of Programs
By appending a digital signature to a program, it is
possible to prevent or at least detect program
alteration.
Download
Web Server
Signature
Applet
Web browser

Java Web Start

Download Digital
Java application certificate

1.3.3 Digital Signatures of Programs 1-12

When using applets in Web applications or when using Java Web Start to execute Java
applications on users’ computers, it is possible to append digital signatures to JAR files in
order to guarantee that the programs have not been tampered with.
Users can confirm the information about the provider of a program by checking the signature
before executing the program. If the program was tampered with by a attacker, the fact can be
detected by checking the signature. Java generates errors for applets and applications of Java
Web Start without signatures and prevent them from being executed. Moreover, even when a
signature is present, Java notifies a warning if the signature is not a signature of a certificate
issued by a third party organization,.

1-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


1.3.4 Continuous Measures
It is important to take continuous measures in
order to maintain the security of Web applications.

・Reinforcement of network security via firewall


and other measures
・Collection of information about security holes
and new types of virus
・Collection of information by analyzing logs of
servers
・Continuous countermeasures against security
holes, including patching of existing code

1.3.4 Continuous Measures 1-13

In addition to taking security measures in the Web applications themselves, a continuous broad
spectrum of security measures including network security measures and countermeasures
against viruses will be required to maintain the security of Web applications.
If users can be identified as in the case of Intranets, it is also important that users understand
the importance of security, and educational campaigns are thus important.

1-13

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2. The Encrypt Method

2.1 Java Cryptography Architecture

2.2 JCE

2.3 KeyGenerator Class

2.4 Cipher Class

2. The Encrypt Method 2-1

2-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1 Java Cryptography Architecture
2.1.1 JCA

2.1.2 Provider Class

2.1.3 Engine Class

2.1.4 Signature Class

2.1.5 KeyPairGemerator Class

2.1.6 KeyStore Class

2.1 Java Cryptography Architecture 2-2

2-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.1 JCA (1/2)
Java includes a framework related to encryption,
which is called JCA (Java Cryptography
Architecture).

Class Interface

java.security.Provider java.security.Key

java.security.Security

java.security.Signature

2.1.1 JCA 2-3

Java includes a framework related to encryption in the standard class library. The framework is
called JCA (Java Cryptography Architecture).
JCA is included in the java.security package; the most important classes and interfaces of
this framework include Provider, Security, Signature and Key.
JCA is designed taking independence of implementation and algorithm into consideration; it
is possible to incorporate unique encryption services and algorithms.

2-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.1 JCA (2/2)
JCE (Java Cryptography Extension) allows
implementing unique encryption processing within the
JCA framework.
JCA
Basic classes/ JCE
interfaces
Provider implementations
Provider
Provider Key
Key

Signature
Signature Cipher
Cipher

KeyGenerator
KeyGenerator Provider implementations

2.1.1 JCA 2-4

JCE (Java Cryptography Extension) is one of the frameworks included in JCA. By using JCE,
it becomes possible to implement unique encryption methods and related processing in JCA.
JCA puts together various encryption services in the Provider class. JCE allows the user to
implements these services in his/her own ways.

2-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.2 Provider Class
The Provider class provides a package or a set
of packages that executes one or more
encryption processing.
Security
Engine class
Provider
Priority

Provider

addProvider

removeProvider

2.1.2 Provider Class 2-5

The Provider class provides a package or set of packages that executes one or more encryption
processing. The classes dealing with the execution of the encryption algorithms are called
Engine classes; they include the MessageDigest class that deals with encrypting character
strings, the Signature class that generates and verifies digital signatures and the KeyGenerator
class that generates keys for encryption. Objects of the Provider class contain various
combinations of these Engine classes and is managed centrally by a Security object. System
developers can acquire and use Providers to fit their purposes.
The Provider class is implemented in order to secure independence of implementation.
When there are several implementations that execute the same processing, it is possible to
choose the one that is the fastest or the one that is the most secure, for instance.
In order to add or delete Providers to/from the Security object, use the addProvider method
and removeProvider method. Each Provider has a priority order; if no particular Provider is
provided, the Provider with the highest priority order is used.

2-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.3 Engine Class
Engine classes represent encryption services
associated with specific encryption algorithms.
Representative Engine classes

MessageDigester Encrypts character strings and similar data

Signature Appends and verifies digital signatures

KeyPairGenerator Generates a key pair consisting of a public


key and a private key
KeyStore Creates/manages a keystore, which is a
database of keys

2.1.3 Engine Class 2-6

Engine classes represent encryption service associated with specific algorithms. Engine classes
that perform various types of processing necessary for encryption have been defined in
advance.
An Engine class is associated with one or more algorithms and it is possible to specify an
algorithm at execution. A class for each algorithm is defined separately from the Engine
classes and it is possible to define unique algorithm classes as well. JCA ensures independence
of algorithms with this structure.

2-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.4 Signature Class (1/2)
This class allows appending a digital signature
to a message.
Data to
be signed
Signature class
update Private key

initSign

Signed
Signature
data
object sign
static getInstance

Provider

2.1.4 Signature Class 2-7

The Signature class allows appending and validating digital signatures.


To append a digital signature, first call the getInstance method of the Signature class to
generate an instance of the Signature class. It is possible to specify the specific algorithm and
Provider to be used when calling the method. If the specification of a Provider is omitted, the
Provider with the highest priority order is used.
Next, use the update method and set the data to be signed in the Signature class. The data to
be set should be specified as a byte array. Afterward, use the initSign method to set a private
key and call the sign method. A byte array containing the signed data is returned as the return
value of the sign method.

2-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.4 Signature Class (2/2)
This class allows verifying a message with a
digital signature.
Data to be
verified
Signature class
update

Signature Verification
object verify
static getInstance

Provider Public key


initVerify

2.1.4 Signature Class 2-8

In order to validate the digital signature, first use the getInstance method of the Signature class
to acquire an instance of the Signature class.
After acquiring/setting an algorithm to be used from the public key used for verification, call
the initVerify method to initialize the verification processing.
Next, use the update method to set the data to be verified in the Signature class. The data to
be set should be specified as a byte array.
Lastly, call the verify method to judge the validity of the digital signature.

2-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.5 KeyPairGenerator Class
This class generates a key pair consisting of a
public key and a private key.
KeyPairGenerator class

KeyPair

Private key
KeyPairGenerator
object Public key
static getInstance
Generate

Provider

2.1.5 KeyPairGenerator Class 2-9

The KeyPairGenerator class allows generating a key pair consisting of a public key and a
private key.
To generate a key pair, first call the getInstance method of the KeyPairGenerator class to
generate an instance of the KeyPairGenerator class. It is possible to specify the specific
algorithm and Provider to be used when calling the method. If the specification of a Provider is
omitted, the Provider with the highest priority order is used.
After generating the instance, call the initialize method to initialize the generator. At this
point, it is possible to set parameters for the encryption algorithm and random numbers to be
used.
After initializing the generator, the generate method can be called in order to generate a
private key and a public key and acquire an instance of KeyPair, which includes the two keys.

2-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.1.6 KeyStore Class
This class manages a keystore, which is a
database of keys.
KeyStore
KeyStore class Load file
Store

getKeyEntry
Private key
KeyStore
object Public key
static getInstance setKeyEntry

Provider

2.1.6 KeyStore Class 2-10

The KeyStore class allows managing a keystore, which is a database of keys.


To manage a keystore, call the getInstance method of the KeyStore class to generate an
instance of the KeyStore class. At this point, it is possible to specify the specific Provider to be
used. If the specification of a Provider is omitted, the Provider with the highest priority order is
used.
First, the key entries are loaded into the KeyStore object from a keystore file. Then, the
getKeyEntry method can be used to obtain information of each registered key entry, and the
setKeyEntry method can be used to register specified key information as a key entry. When the
key entry operations are completed, it is possible to call the store method to output/save the
key entry information.

2-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.2 JCE
JCE (Java Cryptography Extension) is a
framework that expands the JCA functions.
Class

java.crypto.Cipher

java.crypto.CipherInputStream

java.crypto.CipherOutputStream

java.crypto.KeyGenerator

2.2 JCE 2-11

JCE stands for Java Cryptography Extension and is a framework that extends the functions of
JCA.
The java.crypto.Cipher class is used to implement encryption and decryption functions. In
order to implement unique encryption services, a subclass of this class is created and the
algorithms are implement there.
The CipherInputStream and CipherOutputStream classes implement encrypted input/output
streams. Specify an appropriate Cipher class for encrypting a given stream when generating an
instance.

2-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.3 KeyGenerator Class

2.3.1 KeyGenerator Class

2.3.2 Generation of Instances

2.3.3 Initialization

2.3.4 Generation of Keys

2.3 KeyGenerator Class 2-12

2-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.3.1 KeyGenerator Class
The KeyGenerator class generates secret keys.

KeyGenerator class

KeyGenerator Secret key


object
static getInstance
Generate

Provider

2.3.1 KeyGenerator Class 2-13

The KeyGenerator class allows generating secret keys.


An instance can be generated by calling the getInstance method of the KeyGenerator class.
At this point, it is possible to specify the specific algorithm and Provider to be used. If the
specification of a Provider is omitted, the Provider with the highest priority order is used.
After generating the instance, call the initialize method and initialize the generator. At this
point, it is possible to set parameters for the encryption algorithm and random numbers to be
used. Afterward, call the generate method to generate the secret key.

2-13

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.3.2 Generation of Instances
Use the getInstance method to generate
instances of the KeyGenerator class.
Syntax
(1) public static final KeyGenerator getInstance(String algorithm )
(2) public static final KeyGenerator getInstance(String algorithm, String p)
(3) public static final KeyGenerator getInstance(String algorithm, Provider p);

Example

KeyGenerator kg = KeyGenerator.getInstance(“DES”);

2.3.2 Generation of Instances 2-14

Use the getInstance method to generate an instance of the KeyGenerator class.


Three syntaxes are defined for the getInstance method, which takes one or two arguments.
The first argument specifies the algorithm name with a character string. Either “DES” or
“RSA” can be specified as standard. The second argument specifies a Provider; specify the
Provider name as a character string in case of syntax (2) or as an instance of the Provider class
in case of syntax (3). The Provider setting is omitted in syntax (1); in this case, the Provider
with the highest priority order is automatically set.
If a specified algorithm or Provider does not exist, an exception is thrown.

2-14

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.3.3 Initialization
Execute the init method to initialize instances
of KeyGenerator.
Syntax
(1) public final void init(SecureRandom r)
(2) public final void init(int keySize)
(3) public final void init(int keySize, SecureRandom r)
(4) public final void init(AlgorithmParameterSpec p)
(5) public final void init(AlgorithmParameterSpec p, SecureRandom r)

Example

SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance(“DSA”);
kg.init(r);

2.3.3 Initialization 2-15

It is necessary to initialize the KeyGenerator class by executing the init method before
generating keys.
The SecureRandom class is a random number generator included in the java.security
package and enhanced for encryption processing. It uses the SHA1PRNG algorithm as
standard. In syntaxes (1), (3) and (5), random numbers are generated from a given
SecureRandom object to perform encryption processing. If a SecureRandom object is not
specified as in the cases of syntaxes (2) and (4), the SecureRandom object is acquired from the
specified Provider. If the specified Provider does not include a SecureRandom object, the
standard random generator provided by the system is used.

2-15

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.3.4 Generation of Keys
Execute the generate method to generate
keys.
Syntax
(1) public final SecretKey generateKey()

Example

SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
KeyGenerator kg = KeyGenerator.getInstance(“DSA”);
kg.init(r);
Key k = kg.generateKey();

2.3.4 Generation of Keys 2-16

It is possible to generate keys by initializing an instance of KeyGenerator with the init method
and executing the generateKey method.

2-16

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4 Cipher Class
2.4.1 Cipher Class

2.4.2 Transformation

2.4.3 Encryption Algorithm

2.4.4 Conversion Mode

2.4.5 Padding

2.4.6 Encryption/Decryption

2.4.7 Sample Program

2.4 Cipher Class 2-17

2-17

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.1 Cipher Class
The Cipher class is a core class of JCE that
encrypts and decrypts data.

Cipher class
update Data to be
doFinal encrypted/
decrypted
Cipher
object
Encrypted/
decrypted data
static getInstance

Provider ENCRYPT_MODE
init DECRYPT_MODE

2.4.1 Cipher Class 2-18

The Cipher class provides functions for encrypting and decrypting data and is a core class of
JCE.
An instance of the Cipher class can be acquired by calling the getInstance method. When
doing so, it is not only possible to specify a Provider, but also a Transformation as a character
string argument for the getInstance method. A Transformation is a character string specifying
the encryption algorithm, conversion mode and/or padding, and various combinations can be
specified.
Next, specify an operation mode and execute the init method. Either ENCRYPT_MODE or
DECRYPT_MODE can be specified. The operation mode specified here determines the
processing carried out in doFinal, which can be either encryption or decryption. With the init
method, it is possible to set not only the operation mode, but also key and algorithm
parameters and random number generator.
After the data is passed to the Cipher object with the update method, encrypted/decrypted
data is returned. When the last data is returned, call the doFinal method and reset the
encryption processing. The reset Cipher object can encrypt/decrypt new data.

2-18

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.2 Transformation
A transformation character string is composed of
an encryption algorithm, a conversion mode and
padding scheme.
Syntax
(1) Encryption algorithm/conversion mode/padding
(2) Encryption algorithm

Example

Cipher c1 = Cipher.getInstance(“DES/CBC/PKCS5Padding “);


Cipher c2 = Cipher.getInstance(“DES”);

2.4.2 Transformation 2-19

The Cipher class allows specifying a Transformation character string for the getInstance
method. A Transformation character string is composed of an encryption algorithm, a
conversion mode and a padding scheme.

2-19

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.3 Encryption Algorithm
AES Designated as a FIPS (Federal Information Processing Standard) draft for an
advanced encryption standard by NIST (National Institute of Standards and
Technology). It is a 128-bit block cipher based on the Rijndael algorithm
created by Joan Daemen and Vincent Rijmen and supports 128-bit, 192-bit
and 256-bit keys.

Blowfish A block cipher designed by Bruce Schneier

DES An encryption standard defined in FIPS PUB 46-2

DESede Encryption via triple DES

PBEWithMD5And A password-based encryption algorithm defined in “PKCS #5: Password-


Based Encryption Standard” version 1.5 by the RSA Laboratories in
DES November 1993

PBEWithHmacSH A password-based encryption algorithm defined in “PKCS #5: Password-


Based Encryption Standard” version 2.0 by the RSA Laboratories in March
A1AndDESede 1993

RC2, RC4, RC5 A variable key-size encryption algorithm developed by Ron Rivest of
RSA Data Security, Inc

RSA An RSA encryption algorithm defined in PKCS #1

2.4.3 Encryption Algorithm 2-20

The table shows encryption algorithms that can be specified in a Transformation character
string.

2-20

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.4 Conversion Mode

NONE No conversion mode


CBC A Cipher Block Chaining mode defined in FIPS PUB
81
CFB A Cipher Feedback mode defined in FIPS PUB 81
ECB An Electronic Codebook mode defined in FIPS PUB
81 “DES Modes of Operation” published by NIST
(December 1980)
OFB An Output Feedback mode defined in FIPS PUB 81

PCBC A Propagating Cipher Block Chaining defined in


Kerberos version 4

2.4.4 Conversion Mode 2-21

The table shows conversion modes that can be specified in a Transformation character string.

2-21

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.5 Padding

NoPadding No padding
PKCS5Padding A padding scheme prescribed in “PKCS #5:
Password-Based Encryption Standard” version 1.5
(RSA Laboratories, November 1993)

SSL3Padding A padding scheme prescribed in Section 5.2.3.2


(CBC block cipher) of SSL Protocol version 3.0
OAEPWith<digest> An Optimal Asymmetric Encryption Padding scheme
And<mgf>Padding defined in PKCS #1
<digest> is replaced by a message digest and <mgf>
by a mask generation function. (Example:
OAEPWithMD5AndMGF1Padding)

2.4.5 Padding 2-22

The table shows padding schemes that can be specified in a Transformation character string.

2-22

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.6 Encryption/Decryption
Call the update method in order to set the data to be
encrypted/decrypted and complete the processing
by calling the doFinal method.
update syntax
(1) public final byte[] update(byte[] input)
(2) public final byte[] update(byte[] input, int offset, int length)
(3) public final int update(byte[] input, int offset, int length, byte[] output)
(4) public final int update(byte[] input, int offset, int length, byte[] output, int
outputOffset)
doFinal syntax
(1) public final byte[] doFinal(byte[] input)
(2) public final byte[] doFinal(byte[] input, int offset, int length)
(3) public final int doFinal(byte[] input, int offset, int length, byte[] output)
(4) public final int doFinal(byte[] input, int offset, int length, byte[] output, int
outputOffset)

2.4.6 Encryption/Decryption 2-23

Call the update method to perform encryption/decryption with the Cipher class; once data has
been specified as a byte array, it is possible to acquire encrypted/decrypted data. The update
method may have different parameters depending on how the data to be encrypted/decrypted is
specified and how the resulting encrypted/decrypted data is acquired.
Once all the necessary data has been processed with the update method, call the doFinal
method when passing the last data. The doFinal method executes data encryption/decryption in
the same way as the update method, but it also resets the object after processing all data in the
buffer. The reset Cipher object can then encrypt or decrypt new data using different settings.

2-23

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.7 Sample Program (1/3)
Sample Program
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Sample0201 {


public static final int KEY_SIZE = 112;

public static String toHexString(byte[] data){ Method for


StringBuffer buf = new StringBuffer(); returning a hash
for(int i = 0, n = data.length; i < n; i ++){ value as a string of
buf.append(Integer.toHexString(0xFF & data[i])); hexadecimal
} numbers
return buf.toString();
}

public static void main(String[] args) { Generation of a


String algorithm = args[0]; secret key
try {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
kg.init(KEY_SIZE);
SecretKey key = kg.generateKey();

Cipher cp = Cipher.getInstance(algorithm);
cp.init(Cipher.ENCRYPT_MODE, key); Encryption
byte[] result = cp.doFinal(args[1].getBytes()); processing
System.out.println("DATA:" + toHexString(result));

2.4.7 Sample Program 2-24

2-24

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.7 Sample Program (2/3)
Sample Program

cp.init(Cipher.DECRYPT_MODE, key);
byte[] decrypt = cp.doFinal(result);
System.out.println("DECRYPT:" + new String(decrypt));

} catch (Exception e) {
e.printStackTrace();
} Decryption
} processing
}

2.4.7 Sample Program 2-25

2-25

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


2.4.7 Sample Program (3/3)
Lines 8 to 14
Method for returning the specified byte type array as a string of
hexadecimal numbers

Lines 19 to 20
Initialize the KeyGenerator tool to create a secret key used for
encryption/decryption. Use the algorithm specified in the first
argument.

Lines 21 to 22
Initialize the Cipher instance associating it with the generated key.

Lines 26 to 28
Encrypt the string passed via the second argument and print the
data as hexadecimal numbers

Lines 30 to 32
Decrypt the encrypted data and print it as a string
Execution result
C:\java Sample0201 DESede “Web Secure Programming”

KEY:1cabc5fa6684fc45b111e7e820c3ec511cabc5fa6684fc45
9ba5d11fe1f2d8f3
DATA:6592d6f73f8238d3566eec43ce2cf72121a9dad8dd7f1f
DECRYPT:Web Secure Programming

2.4.7 Sample Program 2-26

2-26

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3. Message Digest

3.1 Message Digest

3.2 MD5/SHA

3.3 MessageDigest Class

3.4 Applications Executing Message Digest

3. Message Digest 3-1

3-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.1 Message Digest (1/2)
In message digest, data is hashed and output
with a fixed length.

Fixed length
Any length
Update Digest

Data to be
MessageDigest Hash value
hashed

Cannot be restored

3.1 Message Digest 3-2

Message digest refers to a form of processing that outputs data of a fixed length from data of
arbitrary length using a specific algorithm. The output data is called a hash value or digest
value.
It is not possible for the same hash value to be output unless the data is exactly identical
because the order of the data also influences hash values. Moreover, computing a hash value is
an irreversible operation; it is very difficult to restore the original data from the hash value.

3-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.1 Message Digest (2/2)
A generated hash value can be used to verify
that data has not been tampered with.
Disclose
Download

JAR file JAR file

Hash value MessageDigest

Compare
Hash value

3.1 Message Digest 3-3

Hash values can be used as unique reliable identifiers of any data and it is thus can be used to
check that data of programs, documents etc. download via a network have not been tampered
with. For example, when publishing a program, the developer might disclose the JAR file that
contains all the software along with the hash value. A user downloading the software and hash
value can then verify that the software has not been tampered with by executing the same
message digest processing and checking that the same hash value is created.
For this reason, hash values are sometimes called digital fingerprints.

3-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.2 MD5/SHA
The MD5 and SHA algorithms are used for
generating hash values.
Representative digest algorithms

MD5 Stands for Message Digest 5


Developed by RSA encryption developers
Ronald Rivest and others and
standardized as RFC 1321 in IETF
SHA Stands for Secure Hash Algorithm-1
Employed by NIST as the standard hash
function to be used by the US government
in 1995

3.2 MD5/SHA 3-4

There are various algorithms for generating hash values, with MD5 and SHA being the
representative ones. These digest algorithms are implemented in the standard Java class
library.

3-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.3 MessageDigest Class

3.3.1 MessageDigest Class

3.3.2 Instance Generation

3.3.3 Digest Processing

3.3 MessageDigest Class 3-5

3-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.3.1 MessageDigest Class
The MessageDigest class generates hash
values from specified data
Data to be
MessageDigest hashed
class
Update

MessageDigest Hash value


object Digest
static getInstance

Provider

3.3.1 MessageDigest Class 3-6

The MessageDigest class allows processing data of any length and generate a hash value based
on it.
Call the getInstance method to generate an instance of the MessageDigest class. At this
point, it is possible to specify the algorithm and/or Provider used for MessageDigest. Either
MD5 or SHA can be specified for the algorithm.
Call the update method to load the data to be hashed into the MessageDigest object. The
data should be specified as a byte array. When all the data is loaded, call the digest method to
acquire the hash value of the data.

3-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.3.2 Instance Generation
Use the getInstance method to generate an
instance of the MessageDigest class.
Syntax
(1) public static MessageDigest getInstance(String algorithm )
(2) public static MessageDigest getInstance(String algorithm, String p)
(3) public static MessageDigest getInstance(String algorithm, Provider p);

Example

MessageDigest md = MessageDigest.getInstance(“SHA”);

3.3.2 Instance Generation 3-7

Use the getInstance method to generate an instance of the MessageDigest class.


Three syntaxes are defined for the getInstance method, which takes one or two arguments.
The first argument specifies an algorithm name with a character string; either MD5 or SHA
can be specified. The second argument specifies a Provider; specify the Provider name as a
character string in case of syntax (2) or as an instance of the Provider class in case of syntax
(3). The Provider setting is omitted in syntax (1); in this case, the Provider with the highest
priority order is automatically set.
If a specified algorithm or Provider does not exist, an exception is thrown.

3-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.3.3 Digest Processing
Use the update method to load data and the
digest method to generate the hash value.
update syntax
(1) public void update(byte input)
(2) public void update(byte[] input)
(3) public void update(byte[] input, int offset, int length)

digest syntax
(1) public byte[] digest()
(2) public byte[] digest(byte[] input)
(3) public int digest(byte[] output, int offset, int length)

3.3.3 Digest Processing 3-8

The update method of the MessageDigest class is used when loading data of an arbitrary
length, from which a hash value is derived. The arguments of the update method are specified
differently depending on how the data is passed. It is possible to load data of large size by
calling the update method repeatedly.
After loading all the data, it is possible to acquire the hash value by calling the digest
method. The arguments of the digest method are specified differently depending on the method
of acquiring the hash value. After calling the digest method, the data loaded so far by the
update method is reset and the MessageDigest object can load new data again.

3-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.4 Applications Executing Message Digest (1/2)

Sample program
import java.security.MessageDigest;

public class Sample0301 {

static char[] hexChar = {


'0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' ,
'8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f‘ }; Method for
returning a hash
public static String toHexString ( byte[] b ){ value as a string
StringBuffer sb = new StringBuffer( b.length * 2 ); of hexadecimal
for ( int i=0; i<b.length; i++ ){ numbers
sb.append( hexChar [( b[i] & 0xf0 ) >>> 4]);
sb.append( hexChar [b[i] & 0x0f] );
}
return sb.toString();
}
Specify MD5 as
public static void main(String[] args) { the algorithm
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(args[0].getBytes()); Load data
byte[] hash = md.digest();
System.out.print(toHexString(hash)); Acquisition of
hash value
} catch (Exception e) {
e.printStackTrace();
}
}
}

3.4 Applications Executing Message Digest 3-9

3-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


3.4 Applications Executing Message Digest (2/2)

Lines 5 to 16
Define the toHexString() method, which returns a generated
hash value as a string of hexadecimal numbers. The byte array
given by the argument is converted into hexadecimal numbers
and the character string is returned.

Line 20
Acquire an instance of the MessageDigest class. MD5 is
specified for the hash algorithm.

Line 21
Specify the first argument of the command line in
MessageDigest as a message.

Line 23
Call the digest method to acquire the hash value.

Execution result

C:\java Sample03 MessageDigest


f56af35aa72464851e0f5b4b1da3d67c

3.4 Applications Executing Message Digest 3-10

3-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4. Digital Signature and Certificate

4.1 Digital Signature


4.2 Application Examples of Digital Signature
4.3 Certificate
4.4 Signature Utilities
4.5 X.509 Certificate
4.6 keytool Utility
4.7 jarsigner Utility

4. Digital Signature and Certificate 4-1

4-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.1 Digital Signature (1/2)
A digital signature can be used for authentication
as well as denial/refusal of a signatory of a
message.

Sign with
Private key Public key
Verification
Private key Public key

Signed Signed
data data
Delivery

4.1 Digital Signature 4-2

Digital signature refers to signing data such as messages, documents and files electronically,
just like with a manual signature.
In digital signature, a key pair consisting of a private key and a public key is used. The
signatory uses the private key to sign the data. A user receiving the data can then use the
public key of the signatory, which is publicly available, to verify the validity of the signature.

4-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.1 Digital Signature (2/2)

Digital signature advantages

・Signed data cannot be changed. If it is changed


illegally, the fact can be detected by examining
the signature.

・It is possible to use the public key to examine


the validity of a signature.

・Unless the private key is known to others, it is


impossible to forge a signature.

4.1 Digital Signature 4-3

One of the important advantages of using digital signatures is that it is possible to prove that
signed data has not been illegally rewritten. This is effective when exchanging data via the
Internet and other open networks, as well as when exchanging highly important data. If data
has been changed illegally, the fact can be detected by examining the signature.
Moreover, it is possible to verify the validity of a signature using the public key provided by
the signatory. A signature cannot be forged unless the private key is known to others.

4-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2 Application Examples of Digital Signature

4.2.1 What is Keystore?

4.2.2 Sample Application: Appending Signatures

4.2.3 Sample Application: Verifying Signatures

4.2 Application Examples of Digital Signature 4-4

4-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.1 What is Keystore?
Java manages keys and certificates using
databases called keystores.
keystore
Keystores are
password
protected Entry Entry Entry

Alias name Alias name Alias name

Each key entry is


password
protected
Private key Certificate Key Certificate

4.2.1 What is Keystore? 4-5

Java manages keys and certificates using databases called keystores. The data is managed in
units called entries; each entry has a unique alias name. A entry can be either a key entry, a
certificate entry or a combined entry containing private a key and the corresponding public key
certificate.

4-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.2 Sample Application: Appending Signatures (1/3)

(1) Acquire private key

Signature

keystore

(3) Append (2) Read and


signature update Data

Signed data

(1) Extract a specific private key from the keystore


specified via the command line.
(2) Read the specified data file.
(3) Sign the data and save it in a file.

4.2.2 Sample Application: Appending Signatures 4-6

4-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.2 Sample Application: Appending Signatures (2/3)

Sample program
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;

public class Sample0401 {

public static final String KEYSTORE_TYPE = "JKS";


public static String HASH_ALGORITHM = "SHA1";

public static void main(String[] args) {


Parse parameters
from the command
String storeFileName = args[0];
line
String storePassword = args[1];
String entryName = args[2];
String entryPassword = args[3];
String targetFileName = args[4];
String signatureFileName = args[5];
Open keystore
try {
KeyStore store = KeyStore.getInstance(KEYSTORE_TYPE);
store.load(new FileInputStream(storeFileName),
storePassword.toCharArray());

PrivateKey privateKey =
(PrivateKey)store.getKey(entryName, Acquire private
entryPassword.toCharArray()); key

To be continued

4.2.2 Sample Application: Appending Signatures 4-7

4-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.2 Sample Application: Appending Signatures (3/3)

Continued Initialize
signature object
String keyAlgorithm =
HASH_ALGORITHM + "with" + privateKey.getAlgorithm();
Signature signature = Signature.getInstance(keyAlgorithm);
signature.initSign(privateKey);

FileInputStream in = new FileInputStream(targetFileName);


byte[] buf = new byte[1024];
int len = 0;
Read data file
while((len = in.read(buf)) >= 0){
signature.update(buf, 0, len);
}
in.close(); Sign the data

byte[] result = signature.sign();


FileOutputStream out =
new FileOutputStream(signatureFileName);
out.write(result);
out.close();
System.out.println(“Signature has been created:”
+ signatureFileName);

} catch (Exception e) { Write the


e.printStackTrace(); signature to the
} standard output
}
}

Execution result
C:\java Sample0401 C:\temp\keystore.ks password testentry
password C:\temp\input.txt C:\temp\signature.dat
Signature has been created: C:\temp\signature.dat

4.2.2 Sample Application: Appending Signatures 4-8

4-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.3 Sample Application: Verifying Signatures (1/4)

(1) Acquire public key

Signature

keystore

(2) Read
(3) Verify and update Data

Signed data

(1) Acquire a specific public key from the keystore


specified via the command line.
(2) Read the specified data file.
(3) Read the specified signed file and verify the
data.

4.2.3 Sample Application: Verifying Signatures 4-9

4-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.3 Sample Application: Verifying Signatures (2/4)

Sample program
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;

public class Sample0402 {

public static final String KEYSTORE_TYPE = "JKS";


public static String HASH_ALGORITHM = "SHA1";

public static void main(String[] args) { Parse parameters


from the command
String storeFileName = args[0]; line
String storePassword = args[1];
String entryName = args[2];
String entryPassword = args[3];
String targetFileName = args[4];
String signatureFileName = args[5];

try { Open keystore

KeyStore store = KeyStore.getInstance(KEYSTORE_TYPE);


store.load(new FileInputStream(storeFileName),
storePassword.toCharArray()); Acquire public
key
Certificate cert = store.getCertificate(entryName);
PublicKey publicKey = cert.getPublicKey();

Continued

4.2.3 Sample Application: Verifying Signatures 4-10

4-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.3 Sample Application: Verifying Signatures (3/4)

Initialize signature
Sample program object
String keyAlgorithm = HASH_ALGORITHM + "with"
+ publicKey.getAlgorithm();
Signature signature = Signature.getInstance(keyAlgorithm);
signature.initVerify(publicKey);

File sigFile = new File(signatureFileName);


FileInputStream sig = new FileInputStream(sigFile);
byte[] sigdata = new byte[(int)sigFile.length()];
sig.read(sigdata, 0, sigdata.length);
Read a signature
sig.close();

FileInputStream in = new FileInputStream(targetFileName);


byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf)) >= 0){
signature.update(buf, 0, len); Read data file
}
in.close();
Verify the signature
if(signature.verify(sigdata)){
System.out.println("Valid Signature.");
}else{
System.out.println("Invalid Signature.");
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

4.2.3 Sample Application: Verifying Signatures 4-11

4-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.2.3 Sample Application: Verifying Signatures (4/4)

Execution result(success)
C:\java Sample0401 C:\temp\keystore.ks password testentry
password C:\temp\input.txt C:\temp\signature.dat

Valid Signature

Execution result (failure)


C:\java Sample0401 C:\temp\keystore.ks password testentry
password C:\temp\input.txt C:\temp\signature.dat

Invalid Signature

4.2.3 Sample Application: Verifying Signatures 4-12

4-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.3 Certificate

4.3.1 What is a Certificate?

4.3.2 CA (Certificate Authority)

4.3 Certificate 4-13

4-13

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.3.1 What is Certificate?
A certificate is data that proves the validity of a public
key. It is normally used to provide information of the
creator of a public key.
Information of public
key and creator

Generation

Key pair
Key generator

Private key
Public key Prove validity of Certificate
public key

4.3.1 What is Certificate? 4-14

Public keys are used to prove the validity of data that has been digitally signed, whereas
certificates are data proving that the public keys are generated by the key generator without
doubt. Normally, a certificate is created based on a public key and information about the key
generator.
A user using a public key to verify a digital signature can confirm the validity of the public
key and information of the generator with the corresponding certificate.

4-14

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.3.2 CA (Certificate Authority)
A CA is an organization that issues certificates and
normally refers to a third party certificate authority
other than the person in question.
Public key Certificate issuance
Key generator registration
User
CA

Confirmation Confirmation of
of generator certificate

Signed with
Signed document Private key Verification with public key
4.3.2 CA (Certificate Authority) 4-15

An organization that issues certificates of keys is called a CA (Certificate Authority).


Key generators can create certificates and become CAs by using various tools. Certificates
created by the key generators themselves are called “self-signed certificates” and cannot be
said to be reliable certificates.
Under normal circumstances, it is necessary to use a certificate issued by a CA established
by an organization other than the key generators’ own in order to be able to append highly
reliable signatures. A CA that issues such certificates is called a third party certificate
authority.
A third party certificate authority acquires a public key and information of an individual or
corporation from a key generator, verifies the validity of the key generator using various
methods such as certificates issued by public organizations and confirmation of the user’s
existence via telephone calls, and then issues a certificate. One of the most famous third party
certificate authorities is VeriSign.

4-15

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.4 Signature Utilities
Signature utilities

keytool Tool for managing keystores


It is also possible to import certificates issued
from third party certificate authorities.

jarsigner This tool appends digital signatures to JAR files


using keys and certificates included in a
“keystore.” It is possible to verify signatures as
well.

4.4 Signature Utilities 4-16

Java SDK includes various tools for appending digital signatures as standard.
keytool is a utility for managing keystores. It can generate a new key for a keystore or
confirm keystore data. It is also possible to import a certificate issued by a third party
certificate authority and associate this with a corresponding private key.
jarsigner uses private keys and certificates included in a specified keystore to append digital
signatures on JAR files. It is also possible to verify signatures by using the -verify option.

4-16

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.5 X.509 Certificate (1/2)
X.509 certificates conform to X.509, which is a standard
for data included in a certificate and its format
Information defined in the X.509 standard
Field Description

Version Version number of the X.509 standard, either v1,v2 or v3

Serial number Serial number for identifying a certificate

Signature algorithm identifier Algorithm used by CA when signing a certificate

Issuer information Information related to an issuer of a certificate, written in a


format conforming to the X.500 standard.
Valid duration Number of days in which the certificate remains valid

Information of person to be Information related to the generator of a public key, written in a


authenticated format conforming to the X.500 standard.
Public key information Information of a public key corresponding to a certificate

4.5 X.509 Certificate 4-17

The X.509 standard is a standard that prescribes what data to include in certificates and how it
should be formatted. Certificates conforming to the X.509 standard is called X.509 certificates.
The data included in a X.509 certificate consists of version, serial number, signature
algorithm identifier, issuer information, valid duration, information of person to be
authenticated and information of the public key corresponding to the certificate. Information
about issuers normally include information about CAs.

4-17

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.5 X.509 Certificate (2/2)
Information about issuers and people to be authenticated
must be written in a format conforming to the X.500
standard.
Information defined in the X.500 standard
Field Abbreviation Description
commonName CN Name of person to be authenticated (e.g. ABC
Systems)
organizationUnit OU Division name (e.g. Development Team)
organizationName O Formal organization name or parent organization
name (e.g. ABC Systems, Inc.)
localityName L Area, city name (e.g. Palo Alto)
stateName S State or region name (e.g. California)
countryName C Two-character country code (e.g. us, jp)

Example
CN=Mark Smith, OU=JavaSoft, O=Sun, L=Cupertino, S=California, C=US

4.5 X.509 Certificate 4-18

The information about issuer and person to be authenticated included in a X.509 certificate
must be written in a format conforming to the X.500 standard. Information defined by the
X.500 standard include commonName, organizationName, stateName and countryName. This
information is specified using comma-separated format, where each value is specified using
the format “identifier = value.”

4-18

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6 keytool Utility

4.6.1 keytool Utility

4.6.2 Data Addition to Keystore

4.6.3 Data Export

4.6.4 Data Display

4.6.5 Keystore Management

4.6 keytool Utility 4-19

4-19

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.1 keytool Utility
The keytool utility is a tool for managing
keystores included in JavaSDK as standard.
keytool commands
Operation Option Description
Data addition to a keystore -genkey Key generation

-import Importing certificates


Data export -certreq Generating certificate signature requests (CSR) for CAs

-export Exporting certificates


Data display -list Displaying a list of all entries included in a keystore
-printcert Displaying data of a certificate
Keystore management -keyclone Copying entries of a keystore
-storepasswd Changing a password of a keystore

-keypasswd Changing a password for a key entry


-delete Deleting an entry of a keystore

4.6.1 keytool Utility 4-20

The keytool utility is a tool included in JavaSDK as standard; it allows managing keystores.
The keytool commands can largely be divided into four categories: data addition to a
keystore, data export, data display and keystore management. The operations are specified via
options.

4-20

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.2 Data Addition to Keystore (1/3)
Syntax
keytool –genkey {-alias alias} {-keyalg keyalg} {-keysize keysize} {-sigalg sigalg}
[-dname dname] [-keypass keypass]
{-validity valDays} {-storetype storetype} {-keystore keystore}
[-storepass storepass] [-provider provider_class_name]

Parameters
alias Alias name to be generated storetype Keystore type
keyalg Algorithm to be used for key keystore Keystore file path
generation
storepass Keystore password
keysize Size of the key to be generated
provider_cl Name of provider class to be used for
sigalg Algorithm to be used for signature ass_name processing
dname Information about a person to be
authenticated, written in a format
conforming to the X.500 standard
(generator of the key)
keypass Password of a key to be generated
valDays Number of days in which the
certificate remains valid

4.6.2 Data Addition to Keystore 4-21

The -genkey option generates a new KeyPair (private key and public key) and stores it in a
keystore with the specified alias name.
By default, DSA and 1024 are specified for the key generation algorithm and key size,
respectively. A generated private key is stored together with a self-authentication certificate
created based on the information about the person to be authenticated specified via the dname
parameter. sigalg is used for the signature algorithm.
If any information necessary for generating a key is omitted, the keytool utility acquires the
information from the user via interactive questions.

4-21

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.2 Data Addition to Keystore (2/3)
Syntax
keytool –import {-alias alias} {-file cert_file} [-keypass keypass]
{-storetype storetype} {-keystore keystore} [-storepass storepass]
[-provider provider_class_name]

Parameters
alias Alias name used when importing a storetype Keystore type
certificate
keystore Keystore file path
cert_file Certificate file to be imported
storepass Keystore password
keypass key password
provider_cl Name of provider class to be used for
ass_name processing

4.6.2 Data Addition to Keystore 4-22

The -import option imports a certificate to a specified entry.


It is used to associate a certificate issued by a reliable CA with a specific private key.

4-22

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.2 Data Addition to Keystore (3/3)
Syntax
keytool –selfcert {-alias alias} {-sigalg sigalg} {-dname dname} {-validity valDays}
[-keypass keypass] {-storetype storetype} {-keystore keystore}
[-storepass storepass] [-provider provider_class_name]

Parameters
alias Alias name to be generated storetype Keystore type
sigalg Algorithm used for signature keystore Keystore file path
dname Information about a person to be storepass Keystore password
authenticated, written in a format
provider_cl Name of provider class to be used for
conforming to the X.500 standard
ass_name processing
(generator of the key)

valDays Number of days in which the


certificate remains valid
keypass Password of a key to be generated

4.6.2 Data Addition to Keystore 4-23

The -selfcert option generates self-signed certificates conforming to the X.509 standard.

4-23

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.3 Data Export (1/2)
Syntax
keytool –certreq {-alias alias} {-sigalg sigalg} {-file certreq_file} [-keypass keypass]
{-storetype storetype} {-keystore keystore} [-storepass storepass]
[-provider provider_class_name]

Parameters
alias Alias name to be generated storetype Keystore type
sigalg Algorithm used for signature keystore Keystore file path
certreq_file Destination path of the CSR file to be storepass Keystore password
generated
provider_cl Name of provider class to be used for
keypass Password for the key to be generated ass_name processing

4.6.3 Data Export 4-24

The -certreq option generates a certificate signature request (CSR), which is used to request a
third party certificate authority etc. to issue a certificate.
It is possible to specify a specific entry’s alias name and password and the destination path
of the corresponding CSR file to create the CSR file.

4-24

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.3 Data Export (2/2)
Syntax
keytool –export {-alias alias} {-file cert_file} {-storetype storetype}
{-keystore keystore} [-storepass storepass] [-provider provider_class_name]

Parameters
alias Alias name to be exported storetype Keystore type
cert_file Destination path of the CSR file to be keystore Keystore file path
generated
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing

4.6.3 Data Export 4-25

The -export option reads a certificate included in a specified entry and exports it to a specified
file.

4-25

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.4 Data Display (1/2)
Syntax
keytool –list {-alias alias} {-storetype storetype}
{-keystore keystore} [-storepass storepass] [-provider provider_class_name]

Parameters
alias Alias name to be displayed storetype Keystore type
keystore Keystore file path
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing

4.6.4 Data Display 4-26

The -list option writes information of a key entry identified by a specified alias name to the
standard output. If no alias name is specified, the information of all the key entries in the
keystore is written.

4-26

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.4 Data Display (2/2)
Syntax
keytool –printcert {-file cert_file}]

Parameters
cert_file Path of the certificate file to be displayed

4.6.4 Data Display 4-27

The -printcert option reads a specified certificate file and writes the content to the standard
output.

4-27

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.5 Keystore Management (1/4)
Syntax
keytool -keyclone {-alias alias} [-dest dest_alias] [-keypass keypass]
[-new new_keypass] {-storetype storetype} {-keystore keystore}
[-storepass storepass] [-provider provider_class_name]

Parameters
alias Copy origin of alias name storetype Keystore type
dest_alias Copy destination of alias name keystore Keystore file path
keypass Copy origin of key password storepass Keystore password
new_keypass Copy destination of key password provider_cl Name of provider class to be used for
ass_name processing

4.6.5 Keystore Management 4-28

By using the -keyclone option, it is possible to copy a specific entry to another entry. Specify
the alias names and key passwords of the copy origin and copy destination, respectively.

4-28

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.5 Keystore Management (2/4)
Syntax
keytool -storepasswd [-new new_storepass] {-storetype storetype}
{-keystore keystore} [-storepass storepass] [-provider provider_class_name]

Parameters
new_storepass New password storetype Keystore type
keystore Keystore file path
storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing

4.6.5 Keystore Management 4-29

With the -storepasswd option, it is possible to change the password of a specified keystore.

4-29

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.5 Keystore Management (3/4)
Syntax
keytool -keypasswd {-alias alias} [-keypass old_keypass] [-new new_keypass]
{-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider
provider_class_name]]

Parameters
alias Alias name storetype Keystore type
old_keypass Old key password keystore Keystore file path
new_keypass New key password storepass Keystore password
provider_cl Name of provider class to be used for
ass_name processing

4.6.5 Keystore Management 4-30

By using the -keypasswd option, it is possible to change the key password of a specific entry.
In this case, it is necessary to specify both the old and the new key passwords.

4-30

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.6.5 Keystore Management (4/4)
Format
keytool -delete [-alias alias] {-storetype storetype} {-keystore keystore}
[-storepass storepass] [-provider provider_class_name]

Parameter
alias Alias name of an entry to be storetype keystore type
deleted
keystore keystore file path
storepass keystore password
provider_cl Name of provider class to be used for
ass_name processing

4.6.5 Keystore Management 4-31

By using the -delete option, it is possible to delete an entry with a specified alias name.

4-31

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.7 jarsigner Utility (1/3)
Using the jarsigner utility allows appending
digital signatures in JAR files.

jarsigner

keystore
Sign

JAR file Signed


JAR file

4.7 jarsigner Utility 4-32

Java allows placing programs, images, sound files and other files together in a JAR (Java
ARchive) file for efficient delivery of software. The jarsigner utility can use the private key of
a specified keystore to append a digital signature on a JAR file. The jarsigner utility can sign
any files except for files in the META-INF directory. The generated signature information is
stored in the META-INF directory.
It is possible to prove that the contents of the JAR file have not been modified illegally by
verifying the signature of a signed JAR file. If the contents were modified, the illegal changes
can be detected by verification as an error is generated.
Applets, Java Web Start applications etc. are always treated as unreliable programs unless
the program to be executed is signed. If a program is delivered to an unspecified number of
people, it is desirable to append a digital signature using the jarsigner utility.

4-32

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.7 jarsigner Utility (2/3)
Syntax
jarsigner [-keypass keypass] [-signedjar signedjar]
{-storetype storetype} {-keystore keystore}
[-storepass storepass] [-provider provider_class_name] jarfile alias

Parameters
jarfile Name of the JAR file to be signed storetype Keystore type
keystore Keystore file path
alias Alias name of the entry to be
storepass Keystore password
signed
provider_cl Name of provider class to be used for
keypass Key password ass_name processing
signedjar Destination path for the signed
JAR file

4.7 jarsigner Utility 4-33

The jarsigner utility appends a signature using a JAR file name and an alias name of the key
entry to be used for the signature.
Keystore information, key password, file name to which a signed JAR file is output etc. are
specified with the options. If the output destination of a signed JAR file is not specified, the
JAR file to be signed is overwritten as a signed JAR file.

4-33

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


4.7 jarsigner Utility (3/3)
Syntax
jarsigner –verify [-keystore keystore] jarfile

Parameters
jarfile JAR file to be verified
keystore path of keystore file

Example

C:\ jarsigner –verify abc.jar

C:\ jarsigner –verify –keystore keystore.ks abc.jar

4.7 jarsigner Utility 4-34

By using the -verify option, it is possible to verify signatures of signed JAR files.
If no keystore is specified, the system keystore, which includes certificates of the certificate
authorities set in Java in advance, is used. If a keystore is specified, the certificates included in
the keystore are verified.

4-34

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5. JAAS (Java Authentication and Authorization Service)

5.1 JAAS
5.2 JAAS Core Class/Interface
5.3 Login Module Configuration File
5.4 LoginContext
5.5 LoginModule
5.6 Callback
5.7 JAAS Security Policy File
5.8 Policy Tool Utility

5. JAAS (Java Authentication and Authorization Service) 5-1

5-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.1 JAAS
JAAS provides functionality for “authentication” of
users and “authorization” for checking access
rights required for the processing.
JAAS Plug-in
Authentication
server Application

Authentication
server
Application

Authentication
Authentication Authorization Application
server

Transparent authentication processing

5.1 JAAS 5-2

JAAS (Java Authentication and Authorization Service) consists of two main functions: an
“authentication” function to identify users in a highly reliable manner and an “authorization”
function for confirming user access rights. JAAS is positioned as a Java standard PAM
(Pluggable Authentication Module) and has been incorporated in SDK from Java1.4 as a
standard package.
Since JAAS authentication is executed as a plug-in, it operates independently of the
individual applications requiring authentication. For this reason, it is not necessary to change
any programs on the application side even if a new authentication method is employed or an
authentication method is changed.
JAAS can be linked to one or more authentication servers, allowing transparent
authentication processing using various methods, including Kerberos, NTUser, UNIXUser and
other forms of authentication.

5-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.2 JAAS Core Class/Interface (1/3)
Information related to a single entity, such as
authenticated users and services, is handled
based on a concept called Subject.
Subject Subject identification
information

Principal Principal

Public credentials Private credentials Object

5.2 JAAS Core Class/Interface 5-3

JAAS handles a single entity such as authenticated users and services using the concept of a
“subject.” A subject includes one or more principals. A principal refers to identification
information, such as user ID, that distinguishes the subject from other subjects.
In addition to this, a subject maintains a credential, which is a collection of various objects,
as attribute information. A credential either belongs to the set of public credentials, which can
be accessed from external classes, or the set of private credentials, which can only be used
from within the scope of the subject. The format of credentials and various other objects
included within credentials do not have to follow any specific format.

5-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.2 JAAS Core Class/Interface (2/3)
javax.security.auth.Subject
Constructor
Subject()
Subject(boolean readOnly, Set principals, Set pubCredentials, Set privCredentials)
Main methods

Set getPrincipals() Obtains the specified set of principals


Set getPublicCredentials() Obtains the set of public credentials
Set getPrivateCredentials() Obtains the set of private credentials
boolean isReadOnly() Returns whether or not the Subject is read only
void setReadOnly() Specifies that the Subject is read only

5.2 JAAS Core Class/Interface 5-4

The Subject class is included in the javax.security.auth package.


Use the getPrincipals method in order to obtain the specified set of principals. Since more
than one principals may be stored in the Subject, a collection of principles is returned via an
object implementing the Set interface as the return value.
Use either the getPublicCredentials method or the getPrivateCredentials method in order to
obtain the corresponding set of credentials. Since more than one credentials may be stored in
the Subject, a collection of credentials is returned via an object implementing the Set interface
as the return value.
By using the isReadOnly method and setReadOnly method, it is possible to check the read-
only attribute of the target subject and set it to read only.

5-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.2 JAAS Core Class/Interface (3/3)
java.security.Principal

Main method

String getName() Obtains the principal name


boolean equals(Object o) Methods of the Object class to be overridden
int hashCode()
String toString()

Main classes implementing the interface


javax.security.kerberos.KerberosPrincipal
javax.security.x500.X500Principal

5.2 JAAS Core Class/Interface 5-5

The Principal interface is included in the java.security package.


It defines the getName method, which is used to obtain the principal name, as well as
methods of the Object class to be overridden. Classes implementing the Principal interface
must also implement the java.io.Serializable interface.

5-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.3 Login Module Configuration File (1/4)
Classes implementing login protocols are
determined by login module configuration files.

Login Login
LoginModule
LoginContext
implementation

Subject
NTUser
Login Determination
Kerberos

UNIXUser Login module


Authentication server
configuration file

5.3 Login Module Configuration File 5-6

JAAS uses the LoginContext class to execute the authentication processing of subjects. The
LoginContext object passes the authentication processing to an object implementing the
LoginModule interface, as determined by a setting file called a login module configuration file.
All the operations an application needs to perform is related to these LoginContext and
LoginModule objects; the actual authentication method and settings related to the
authentication processing are specified in the login module configuration file. For this reason,
the application can operate entirely independently of the authentication processing.

5-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.3 Login Module Configuration File (2/4)
A login module configuration file contains one
or more entries.
Syntax

<entry name> {

<LoginModule> <flag> <LoginModuleOptions>;


<LoginModule> <flag> <LoginModuleOptions>;
..........
};

Example

SampleEntry{
com.sun.security.auth.module.Krb5LoginModule required;
};

5.3 Login Module Configuration File 5-7

A login module configuration file contains one or more entries. Any name can be specified for
<entry name>.
Each entry is comprised of one or more login modules. Each login module is comprised of a
<LoginModule> value, which specifies the class name of the login module, a <flag> value,
which specifies whether login is necessary, along with any <LoginModuleOptions> values
required in the implementation of the login module. If multiple login modules are specified, all
login modules are executed in the order of description.

5-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.3 Login Module Configuration File (3/4)
Several login module implementations are
incorporated in the standard library.
login module
com.sun.security.auth.module
Krb5LoginModule Login module implementing Kerberos authentication

NTLoginModule Login module implementing the Windows NT


authentication model
UnixLoginModule Login module implementing the UNIX authentication
model
JndiLoginModule Login module using JINDI

KeyStoreLoginModule Login module performing authentication processing


based on certificates stored in KeyStores

5.3 Login Module Configuration File 5-8

JAAS includes five login modules as standard.


Among them, the Kerberos authentication module is supported by a wide range of operating
systems, including UNIX OS as well as Windows 2000, Windows XP and MacOSX, and is
positioned as the basic module of JAAS.
LoginModuleOptions are composed of different parameter and value combinations
depending on the module.

5-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.3 Login Module Configuration File (4/4)
The necessity of login authentication can be
specified by flag values.
Flag values
Value Necessity of Continuation of authentication processing
authentication
Required Mandatory Processing is continued according to the list
whether the login succeeds or fails
Requisite Mandatory Processing is continued if the login succeeds
and control is switched to the application side
if fails
Sufficient Not necessary to Control is switched to the application side if
succeed the login succeeds and processing is
continued according to the list if it fails
Optional Not necessary to Processing is continued according to the list
succeed whether the login succeeds or fails

5.3 Login Module Configuration File 5-9

It is possible to specify the necessity of login authentication and behavior after authentication
by setting flags accordingly in a login module configuration file.
If Required or Requisite is specified, the authentication processing must succeed. If the
authentication fails, an exception is thrown. If Sufficient or Optional is set, an exception is not
thrown even if authentication processing does not succeed.
If multiple login modules are specified for one entry, the value of the flag also determines
whether or not to continue the authentication processing. If Required or Optional is set, the
authentication processing is continued according to the list of enumerated login modules
regardless of whether the authentication succeeds or fails.
If Requisite is set, the authentication processing is continued if the processing succeeds and
the control is switched to the application side if it fails. If Sufficient is set, the control is
switched to the application side if the authentication processing succeeds and the processing is
continued according to the list if it fails.

5-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.4 LoginContext (1/2)
LoginContext provides methods required to
authenticate subjects.

LoginContext
class

Entry search
Constructor
LoginContext
instance

Subject
Login module
configuration file Entity
Entity name
name

5.4 LoginContext 5-10

The LoginContext class provides methods required to authenticate subjects. LoginContext


plays the role as the interface between the JAAS authentication processing and the application
in question; the application simply initiates the processing by invoking the LoginContext
object, and the actual authentication processing is then handled by JAAS.
Specify an entry name for the LoginContext constructor. LoginContext searches for the
login module configuration file based on the passed entry name and determines the login
module to be executed.

5-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.4 LoginContext (2/2)
javax.security.auth.login.LoginContext
Constructor
LoginContext(String entryName)
LoginContext(String entryName, Subject target)
LoginContext(String entryName, CallbackHandler handler)
LoginContext(String entryName, Subject target, CallbackHandler handler)

Main methods

void login() Performs login processing


void logout() Performs logout processing
Subject getSubject() Obtains the authenticated Subject

5.4 LoginContext 5-11

The LoginContext class is included in the javax.security.auth.login package.


In the constructor, specify an entity name as well as a subject and CallbackHandler.

5-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.5 LoginModule (1/3)
LoginModule is the basic interface that all
classes implementing authentication processing
must implement.

JNDI

Keystore Login

LoginModule LoginContext
NTUser

Kerberos

UNIXUser

5.5 LoginModule 5-12

LoginModule is the basic interface that all classes implementing authentication processing
must implement. A login module includes multiple implementations as standard, and it is
possible to create various LoginModule classes that execute unique authentication processing
by implementing this interface.

5-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.5 LoginModule (2/3)
Login processing is performed in two phases.

1st phase 2nd phase


Login Commit

LoginModule1 LoginModule1

Login Commit
Login Login
LoginModule2 context LoginModule2 context

Login Abort
LoginModule3 LoginModule3

LoginModule1 LoginModule1
LoginModule2 Login module LoginModule2 Login module
LoginModule3 configuration file LoginModule3 configuration file

5.5 LoginModule 5-13

Seen from the LoginContext side, the login processing represents a single operation, but in fact
the login processing on the LoginModule side is executed in two phases.
In the first phase, the login method of each of the LoginModule objects that are targets of
the login processing is executed. The login method returns success or failure, or throws an
exception.
In the second phase, the commit method or abort method of each LoginModule object is
called based on the overall login success and failure. Principals and credentials are set for
authenticated subjects during this phase.

5-13

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.5 LoginModule (3/3)
javax.security.auth.spi.LoginModule
Main methods

boolean login() Performs login processing (1st phase)


boolean logout() Performs logout processing
boolean commit() Commits login processing (2nd phase)
boolean abort() Aborts login processing (2nd phase)

Main classes implementing the interface


com.sun.security.auth.module.Krb5LoginModule
com.sun.security.auth.module.NTLoginModule
com.sun.security.auth.module.UnixLoginModule
com.sun.security.auth.module.JndiLoginModule
com.sun.security.auth.module.KeyStoreLoginModule

5.5 LoginModule 5-14

The LoginModule interface is included in the javax.security.auth.spi package.


It provides basic methods that classes executing login processing must implement in order to
interact with other login modules.

5-14

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (1/12)
CallbackHandler objects handle various requests
from LoginModule objects via Callbacks.

Request
Callback Handler
LoginModule Login LoginContext Login

Display dialog boxes


and/or error messages
NTUser based on a specified
callback
Kerberos

UNIXUser Application
Callback Callback

5.6 Callback 5-15

When executing authentication processing, LoginModule objects may prompt a user to enter
information or display various error messages. The Callback and CallbackHandler interfaces
constitute a framework for handling various requests from LoginModule objects and are
implemented on the application side.
Callback objects represent requests passed from a LoginModule object to the user
application. Normally, several Callback objects are sent at the same time. A CallbackHandler
object executes the Callback processing; specify an appropriate object on the application side
as an argument when generating an instance of LoginContext. Then, when a request to a user
or similar is generated by the actual LoginModule object, an array of Callback instances is
passed to the specified CallbackHandler object.
With this Callback mechanism, it is possible for the application side to implement the
processing using the optimal method for the system in question. For example, in case of GUI-
based (Graphical User Interface) applications, it is possible to implement the prompt for user
ID and password as dialog boxes and display error messages as error dialog boxes.
It is possible to process the Callback and CallbackHandler mechanisms even when unique
LoginModule objects are implemented.

5-15

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (2/12)
javax.security.auth.callback.Callback
No methods are defined for Callback.

Main classes implementing the interface

ChoiceCallback Prompts the user to select an option


ConfirmationCallback Prompts the user to reply with YES/NO
LanguageCallback Obtains locale information
NameCallback Obtains name information from a user
PasswordCallback Obtains password information from a user
TextInputCallback Prompts the user to enter text information
TextOutputCallback Displays text information such as errors and
warnings to the user

5.6 Callback 5-16

The Callback interface is included in the javax.security.auth.callback package. The Callback


interface does not define any method in order to guarantee format interoperability.
The Callback classes used in the basic authentication services included with Java SDK, such
as Kerberos authentication, UNIXUser authentication and NTUser authentication, are included
in the package as standard classes.
As shown in the table, the Callback interface is implemented by seven different subclasses
representing various types of requests.

5-16

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (3/12)
javax.security.auth.callback.ChoiceCallback
Constructor

ChoiceCallback(String prompt, String[] choices,


int defaultChoice, boolean multipleSelectionsAllowed)
Main methods

boolean allowMultipleSelections() Returns True if multiple selection is permitted


String[] getChoices() Obtains the option character strings
int getDefaultChoice() Obtains the default selection
int[] getSelectedIndexes() Obtains the indices of the selected options
void setSelectedIndex(int idx) Specifies the selected option
void setSelectedIndexes(int[] idx) Specifies several selected options
String getPrompt() Obtains the prompt string

5.6 Callback 5-17

The ChoiceCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It provides functionality for prompting a user to select
from various options, which can be obtained using getChoices. Multiple options may be
selected in some cases; whether or not multiple selection is allowed or not can be checked by
calling the allowMultipleSelections method.

5-17

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (4/12)
javax.security.auth.callback.ConfirmationCallback
Constructor
ConfirmationCallback(int messageType, int optionType, int defaultOption)
ConfirmationCallback(int messageType, String[] options, int defaultOption)
ConfirmationCallback(String prompt, int messageType, int optionType, int default)
ConfirmationCallback(String prompt, int messageType, String[] options, int default)
Main methods
int getMessageType() Obtains the message type
int getOptionType() Obtains the option type
String[] getOptions() Obtains the option character strings
int getSelectedIndex() Obtains the selected confirmation option
void setSelectedIndex(int idx) Specifies a selected confirmation option
String getPrompt() Obtains the prompt string

5.6 Callback 5-18

The ConfirmationCallback class is a subclass implementing the Callback interface included in


the javax.security.auth.callback package. It is a Callback class that prompts a user to select
from among a limited set of options, such as YES, NO or CANCEL.
For OptionType, YES_NO_OPTION, YES_NO_CANCEL_OPTION and
OK_CANCEL_OPTION can be specified. If unique check items are set, however,
UNSPECIFIED_OPTION is set for OptionType and the option character strings can be
obtained using the getOptions method.
MessageType can be either INFORMATION, WARNING or ERROR.

5-18

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (5/12)
javax.security.auth.callback.LanguageCallback
Constructor

LanguageCallback()

Main methods
Locale getLocale() Obtains the specified locale information
void setLocale(Locale l) Specifies locale information

5.6 Callback 5-19

The LanguageCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It is used when it is necessary to obtain information
about the system locale.
It implements the getLocale and setLocale methods, which return and specify the locale
information, respectively. The CallbackHandler object either returns locale information of a
system or sets locale information selected by a user via a dialog box etc.

5-19

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (6/12)
javax.security.auth.callback.NameCallback
Constructor
NameCallback(String prompt)
NameCallback(String prompt, String defaultName)

Main methods
String getDefaultName() Obtains the default name
String getName() Obtains the previously specified name
void setName(String name) Specifies the name
String getPrompt() Obtains the prompt string

5.6 Callback 5-20

The NameCallback class is a class implementing the Callback interface included in the
javax.security.auth.callback package. It is a used when name information such as user name
and ID is required. The CallbackHandler object sets and returns information entered by a user
using the setName method.

5-20

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (7/12)
javax.security.auth.callback.PasswordCallback
Constructor
PasswordCallback(String prompt, boolean echoOn)

Main methods
void clearPassword() Clears the specified password
String getPassword() Obtains the previously specified password
void setPassword(String pwd) Specifies the name
boolean isEchoOn() Returns True if passwords are echoed on the
screen when entered
String getPrompt() Obtains the prompt string

5.6 Callback 5-21

The PasswordCallback class is a subclass implementing the Callback interface included in the
javax.security.auth.callback package. It is a Callback class used when password information is
required. The CallbackHandler object sets and returns password information entered by a user
using the setPassword method.
The isEchoOn method indicates whether or not to echo the password input (to the screen).

5-21

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (8/12)
javax.security.auth.callback.TextInputCallback
Constructor
TextInputCallback(String prompt)
TextInputCallback(String prompt, String defaultText)

Main methods
String getDefaultText() Obtains the default character string
String getText() Obtains the previously specified text
void setText(String txt) Specifies the text string
String getPrompt() Obtains the prompt string

5.6 Callback 5-22

The TextInputCallback class is a subclass implementing the Callback interface included in the
javax.security.auth.callback package. It is a Callback class used when a LoginModule object
requires text input. The CallbackHandler object specifies and returns text information entered
by a user or generated in processing etc. using the setText method.

5-22

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (9/12)
javax.security.auth.callback.TextOutputCallback
Constructor
TextOutputCallback(int messageType, String message)

Main methods
int getMessageType() Obtains the message type.
Constants for INFORMATION, WARNING and
ERROR have been set.
String getMessage() Obtains the message

5.6 Callback 5-23

The TextOutputCallback class is a subclass implementing the Callback interface included in


the javax.security.auth.callback package. It is a Callback class used when a LoginModule
object needs to notify a message to the user, such as errors or warnings. The CallbackHandler
object handles displaying messages in dialog boxes or as text, and/or writing them into logs.
It is not necessary to set values for this Callback class from the CallbackHandler side.

5-23

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (10/12)
javax.security.auth.callback.CallbackHandler
Method

void handle(Callback[] callbacks) Processes a passed Callback object

LoginModule
LoginContext Application
Callback Register
NTUser Callback
handler
Kerberos instance

UNIXUser

5.6 Callback 5-24

CallbackHandler is an interface included in the javax.security.auth.callback package.


CallbackHandler is an interface used for handling various requests passed from LoginModule
objects to the invoking application via Callback objects. The user should create classes
implementing this interface on the application side. Callback is a class used by a LoginModule
object to request various information from an application and these requests are passed to the
registered CallbackHandler object as a Callback object array. Methods for displaying dialog
boxes in which login information is entered and where error messages and similar can be
displayed should be created in the classes implementing CallbackHandler.

5-24

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (11/12)
Sample program
import javax.security.auth.login.LoginContext;
import com.sun.security.auth.callback.TextCallbackHandler;

public class Sample0501 {


public static void main(String[] args) { Entry name
LoginContext ctx = null;
try{
ctx = new LoginContext("Sample0501", new TextCallbackHandler());
ctx.login();
System.out.println("Authentication Succeeded.");
}catch(Exception e){ Callback handler
System.out.println("Authentication Failed.");
e.printStackTrace();
}
}
}

5.6 Callback 5-25

This sample program shows how to use the LoginContext class and LoginModule interface
explained so far.
In the call to the LoginContext constructor, “Sample0501” is specified for the entry name,
which will be used as an identifier, and a TextCallbackHandler object, which is a text-based
handler included as standard, is specified as the CallbackHandler. It is possible to perform
authentication processing by writing and executing a login configuration file corresponding to
this program.

5-25

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.6 Callback (12/12)
Example:jaas.conf
Sample0501 {
com.sun.security.auth.module.Krb5LoginModule required;
};

Execution result
C:\java -Djava.security.krb5.realm=Realm name
-Djava.security.krb5.kdc=Address authentication host This should actually
-Djava.security.auth.login.config=jaas.conf Sample0501 be on the same line

UserName: user name


Enter in a text prompt
Password: password

Authentication Succeeded

5.6 Callback 5-26

jaas.conf is a login configuration file that specifies that the Sample0501 entry performs
Kerberos authentication.
At the execution, it is necessary to use the -D option several times to set various system
properties. The login configuration file is also specified with the -D option.

5-26

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.7 JAAS Security Policy File (1/2)
A policy file describes access to resources,
rights to execute programs etc.

Resources Access to
resources
Security
Java
manager
program

Permission Load
objects
Policy file

5.7 JAAS Security Policy File 5-27

A policy file contains information related to various access rights such as access rights to
resources and code execution rights. JVM generates permission objects based on these policy
files. Created permission objects are managed via a security manager and applied to execution
of all programs.
The default policy files are located at $JRE_HOME/lib/security/java.policy. Under normal
circumstances, if an application requiring settings specified in a policy file is created, a new
policy file should be created for the particular application rather than using the default policy
file.
To use a created policy file, specify the name of the policy file for the system property
java.security.policy. The system property is specified with the -D option at execution of JVM.
Example: java –Djava.security.policy = policy-file-name class-name

5-27

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.7 JAAS Security Policy File (2/2)
Policy file syntax

grant
[signedBy <signer name>, codeBase “URL” ,]
[principal <principal class name> “principal name”]
{
permission <permission class name> “target_name” “action”,
permission <permission class name> “target_name” “action”,
...
}

Example

grant principal myclass.MyPrincipal “admin”


{
permission java.io.FilePermission “/home/system” “read”
}

5.7 JAAS Security Policy File 5-28

After “grant,” it is possible to specify JAR file signature information and information about
principals with authenticated logins in a policy file; this is called an entry. Various access
rights can be entered for each entry under “permission.”
If signedBy is specified in a grant entry, it is possible to control access targeted for programs
included in a JAR file signed with a specific certificate. If principal is specified in a grant
entry, it is possible to control access for subjects with particular principal information after
JAAS authentication.
In the example above, file reading rights are granted for the /home/system directory only,
insofar as the authenticated subject contains the myclass.MyPrincipal class and its name is
admin.

5-28

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


5.8 Policy Tool Utility
SDK comes with Policy Tool, a GUI tool for
generating policy files.
$JAVA_HOME/bin/policytool “policy-filename”

5.8 Policy Tool Utility 5-29

A policy file can easily be created using a text editor or similar, but Java SDK also supplies a
GUI tool for creating policy files as standard. By using Policy Tool, it is possible to prevent
syntax mistakes while improving the operability.
It is possible to edit a specific policy by executing “$JAVA_HOME/bin/policytool policy
file name” in the command prompt or similar. Policy Tool allows not only editing files but also
creating new policy files.

5-29

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6. JSSE (Java Secure Socket Extension)

6.1 JSSE

6.2 Socket Factory

6.3 Keystore and Truststore

6.4 Example of Communication Using JSSE

6. JSSE (Java Secure Socket Extension) 6-1

6-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.1 JSSE (1/2)
JSSE allows encrypted and secure
communication via SSL (Secure Socket Layer).

Encrypted communication

Host Secure Socket Layer Host

Various protocols such as HTTP,


FTP and Telnet

6.1 JSSE 6-2

JSSE (Java Secure Socket Extension) is a framework that provides encrypted communication
via SSL (Secure Socket Layer).
The Internet and other open networks are exposed to various risks.
・The person with whom you are communicating may not necessarily be the person you expect.
・The communication may be tapped by attackers.
・If the communication can be tapped, attackers can alter the content before the data is sent to
the receiver.
SSL allows encrypted and secure communication, thus avoiding these risks. SSL operates
below the application layer and can thus use various protocols such as HTTP and FTP.
SSL was developed by Netscape in 1994 and has become the standard encrypted
communication protocol on the Internet. The standard is currently managed by IETF (Internet
Engineering Task Force) and the name was changed to TLS (Transport Layer Socket).

6-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.1 JSSE (2/2)
In SSL, encrypted communication is not started until
after a negotiation where the encryption method to be
used is decided and the server is authenticated.
Send information about supported encryption methods
Sender Receiver
client Determination of encryption method server

Authenticate the server by a certificate or similar


Certificate Obtain information about the public key
Secret key
Send the secret key used for the communication

Start encrypted communication

Decrypt information using the secret key

6.1 JSSE 6-3

In SSL, encrypted communication is not started until after a negotiation where the encryption
method to be used is decided and the server is authenticated.
First, a client sends information about the encryption methods it supports to a server. The
server determines the optimal encryption method based on the information it received and
returns this information to the client. At this point, the encryption algorithm, key size and other
information are determined.
The client then authenticates the server using a certificate and/or other sources and obtains
information about the server’s public key. In the most popular form of SSL communication,
HTTPS, several certificates issued by trusted CAs are registered in a Web browser and the
users can obtain the public key without performing any special operations. If self-authenticated
certificates are to be used, it is necessary to obtain the public key on the client side in advance.
In the encrypted communication, the client and server use the same secret key. The client
encrypts the secret key using the public key generated and obtained from the certificate and
sends it to the server. The encrypted key can only be decrypted by the server’s secret key,
which is paired with the public key attached to the certificate; it is thus not possible for the key
information to be decrypted by entities other than the server.
It is only after these procedures have been completed that the actual encrypted
communication is started using the determined encryption method and the secret key obtained
by both sides.

6-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (1/6)

javax.net.ssl.SSLSocketFactory

javax.net.ssl.SSLSocket

javax.net.ssl.SSLServerSocketFactory

javax.net.ssl.SSLServerSocket

6.2 Socket Factory 6-4

JSSE is included in javax.net.ssl as a sub-package of java.net. JSSE was added as standard


package starting from Java 1.4.
The main classes of JSSE include SSLSocket and SSLSocketFactory as well as
SSLServerSocket and SSLServerSocketFactory. SSLSocket and SSLServerSocket mostly
provide the same functions, but SSLServerSocket implements functions specific to the server
side (receiving side). SSLSocketFactory and SSLServerSocketFactory are factory classes for
generating instances of the corresponding Socket classes.

6-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (2/6)
Client side Server side

SSLSocketFactory SSLSocketFactory
class class

getDefault() getDefault()

SSLSocketFactory SSLSocketFactory
instance instance

createSocket(host, port) createServerSocket


(host, port)
Input/Output
SSLSocket SSLSocket
instance instance

6.2 Socket Factory 6-5

SSLSocket and SSLServerSocket are used mostly the same way.


The client side, i.e., the originator of the communication, uses the getDefault method of
SSLSocketFactory to generate an instance of SSLSocketFactory. An instance of SSLSocket is
then generated by specifying the address and port number of the connection destination as
arguments to the createSocket method of the created instance.
Similarly, the server side also uses the getDefault method of SSLServerSocketFactory to
generate an instance of SSLServerSocketFactory. An instance of SSLSercerSocket is then
generated by specifying the address and port number to which communication is bound as
arguments to the createServerSocket method of the generated instance.
SSLSocket and SSLServerSocket can obtain input/output streams, respectively, using the
getInputStream method and getOutputStream method. By using these streams, it is possible to
exchange encrypted data.

6-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (3/6)
javax.net.ssl.SSLSocketFactory
Constructor
SSLSocketFactory()

Main methods

SSLSocketFactory getDefault() Returns the default


SSLSocketFactory instance
Socket createSocket(InternetAddress remote, int port); Generates a socket for a
Socket createSocket(InternetAddress remote, int rport, specified transmission
InternetAddress local, int lport); destination
Socket createSocket(String remote, int port);
Socket createSocket(String remote, int rport, String local, int
lport);

6.2 Socket Factory 6-6

SSLSocketFactory is included in the javax.net.ssl package.


To generate an instance, use the static getDefault method, rather than the constructor.
Specify the address and port of the connection destination as well as the connection origin
for createSocket for which a socket is created. If no connection origin is specified, the address
of the host on which the program is executed is automatically set.

6-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (4/6)
javax.net.ssl.SSLSocket
Constructor
This class has no public constructor.
Main methods
void startHandshake() Initiates a new SSL connection (handshake)

void close() Closes the current SSL connection


InputStream getInputStream() Obtains a stream for reading from the current
connection
OutputStream getOutputStream() Obtains a stream for writing to the current
connection
String[] getSupportedProtocols() Obtains protocols supported by this
connection
String[] getSupportedCipherSuites() Obtains encryption methods supported by this
connection

6.2 Socket Factory 6-7

The SSLSocket class is included in the javax.net.ssl package.


No public constructor is defined; the createSocket method of the SSLSocketFactory class is
used to generate an instance.
SSLSocket provides the startHandshake method, which initiates a new connection, the close
method, which closes the connection, as well as the getInputStream and getOutputStream
methods, which return input and output streams for connection.
In addition, many methods for obtaining supported protocols and encryption methods,
necessity of authentication etc., are defined.

6-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (5/6)
javax.net.ssl.SSLServerSocketFactory
Constructor
SSLServerSocketFactory()

Main methods

SSLSocketServerFactory getDefault() Returns the default


SSLSocketServerFactory
instance
ServerSocket createServerSocket(int port); Generates a socket bound to a
ServerSocket createServerSocket(int port, int backlog); specified receiver
ServerSocket createServerSocket(int port, int backlog,
InternetAddress bindAddress);

6.2 Socket Factory 6-8

SSLServerSocketFactory is included in the javax.net.ssl package.


In the same way as for SSLSocketFactory, the static getDefault method, rather than the
constructor, is used to generate an instance.
When calling createServerSocket, which generates a socket, it is possible to specify the port
number where the socket awaits connection, the number of connections allowed in the socket
queue, and the address to be bound as arguments.

6-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.2 Socket Factory (6/6)
javax.net.ssl.SSLServerSocket
Constructor
This class has no public constructor.

Main method
void startHandshake() Initiates a new SSL connection (handshake)
void close() Closes the current SSL connection
InputStream getInputStream() Obtains a stream for reading from the current
connection
OutputStream getOutputStream() Obtains a stream for writing to the current
connection
void setSupportedProtocols(String[] p) Sets protocols supported by this connection
void setSupportedCipherSuites(String[] c) Sets encryption methods supported by this
connection

6.2 Socket Factory 6-9

SSLServerSocket class is included in the javax.net.ssl package.


No public constructor is defined; the createServerSocket method of the
SSLServerSocketFactory class is used to generate an instance.
In the same way as SSLSocket, SSLServerSocket provides the startHandshake method,
which initiates a new connection, the close method, which closes the connection, as well as the
getInputStream and getOutputStream methods, which obtain input and output streams for
connection, respectively.
Almost the same functions are implemented in the SSLServerSocket class as in the
SSLSocket class. However, whereas SSLSocket defines methods for obtaining various
information including supported protocols and encryption methods as well as necessity of
authentication, SSLServerSocket defines methods for setting such information.

6-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.3 Keystore and Truststore
A truststore is a keystore that stores certificate
and public key information issued by a trusted CA.

Client Secure Socket Layer Server

Public key information


issued from a trusted CA

Information about secret


key and public key

truststore keystore

6.3 Keystore and Truststore 6-10

A truststore is a keystore that stores certificate and public key information issued by a trusted
CA. Technically, it is not different from a keystore; only the stored data and purposes are
different.
Normally, public key information from trusted third parson certificate authorities such as
Verisign and Geo Trust is stored in a truststore. Web browsers and other applications search
for public key information necessary for SSL communication in truststores. In this way, many
applications can execute encrypted and more secure communication smoothly without the
need of a user installing CA certificates.
Java also incorporates a truststore provided by Sun as standard; it is placed in
$JRE_HOME/lib/security/cacerts.

6-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.4 Example of Communication Using JSSE (1/4)

(1) Specify host, port and path

Sample
SSL Web server
program

(2) GET request

(3) Response

(1) Specify the connected host name, port and path


via the command line.
(2) Establish SSL connection and send a HTTP
GET request.
(3) Write the acquired HTML data to the standard
output.

6.4 Example of Communication Using JSSE 6-11

6-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.4 Example of Communication Using JSSE (2/4)

Sample program
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class Sample0601 {

public static void main(String[] args) {


Parse parameters
from the
String host = args[0];
command line
String path = args[1];
int port = 443;
try{

if(args[2] != null){
port = Integer.parseInt(args[2]); Generation of the
} Socket class

SSLSocketFactory factory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket =
(SSLSocket) factory.createSocket(host, port);

socket.startHandshake(); Initiate SSL connection

To be continued

6.4 Example of Communication Using JSSE 6-12

6-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.4 Example of Communication Using JSSE (3/4)

Sample program
PrintWriter out = new PrintWriter(
new BufferedWriter( Create output
new OutputStreamWriter( stream
socket.getOutputStream())));

out.println("GET http://" + host + path + " HTTP/1.1");


Send GET
out.println();
method
out.flush();

BufferedReader in = new BufferedReader(


new InputStreamReader( Create input
socket.getInputStream())); stream

String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close(); Write response
out.close(); to screen
socket.close();

}catch(Exception e){
e.printStackTrace();
}
}
}

6.4 Example of Communication Using JSSE 6-13

6-13

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


6.4 Example of Communication Using JSSE (4/4)

Execution result
>java Sample0601 www.verisign.com / 443

<html>
...
...
[snip]
...
...
</html>

6.4 Example of Communication Using JSSE 6-14

6-14

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.Web Application Security

7.1 Java Servlet Security

7.2 User Authentication via Tomcat

7.3 Tomcat/SSL Settings

7.4 Realms

7.5 Secure Application Programming

7.Web Application Security 7-1

7-1

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.1 Java Servlet Security
Web containers provide user authentication
frameworks and access control via URL.

Web Container

Web browser User authentication process


Authentication
processing Web Application

Servlet
Access
control JSP

static HTML

7.1 Java Servlet Security 7-2

Web containers are entities implementing user authentication frameworks in advance and
allow specific Web applications to control access to Servlet, JSP, static HTML and similar
content through authentication processing. In this way, developers of Web applications do not
need to implement authentication functions from scratch.

7-2

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.2 User Authentication via Tomcat
Tomcat authenticates users based on information
stored in a user database called a realm.
server.xml
TOMCAT

Realm

<Realm className="... class name


Web Application
for this implementation"
... other attributes for this Servlet
implementation .../>
JSP

static HTML

7.2 User Authentication via Tomcat 7-3

Tomcat authenticates users based on information stored in a user database called a realm. A
realm includes user ID, password and role information indicating privilege. There are various
realm implementations: the user information may be stored using a relational database or in
XML files, LDAP may be used for authentication etc. Realm settings should be described in
server.xml, which is one of the setting files of Tomcat; describe realm implementation classes
to be used and other attribute information in this file according to the realm to be used.

7-3

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.3 Tomcat/SSL Settings
Tomcat’s own HTTP servers support SSL
connections.
server.xml
TOMCAT
<Connector
Realm
port="8443“ maxThreads="150"
minSpareThreads="25"
maxSpareThreads="75" Web Application
enableLookups="false"
disableUploadTimeout="true" Servlet
acceptCount="100" debug="0"
scheme="https" secure="true" JSP
clientAuth="false" sslProtocol="TLS" />
static HTML

7.3 Tomcat/SSL Settings 7-4

Tomcat is a genuine Web container and can thus operate in collaboration with various HTTP
servers including well-known Apache. However, Tomcat comes with HTTP servers
implemented 100% in pure Java as standard as well, so that it can operate as a stand-alone
package by itself.
SSL communication is normally handled by a HTTP server; specify Apache or another
HTTP server as the frontend for receiving requests from users. Tomcat’s own HTTP servers
also support SSL communication. They become available by specifying the settings in
server.xml, which is a setting file used by Tomcat.

7-4

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.4 Realms
Realms provide classes that implement various
authentication methods including storage in
databases, files and authentication via LDAP.
Realms Sources Description
JDBCRealm RDB Realm that uses a relational
database
DataSourceRealm DataSource Class Realm that uses a specified
DataSource class
JINDIRealm LDAP Realm that uses LDAP

MemoryRealm XML file Realm that uses user information


stored in XML files
JAASRealm JAAS LoginModule Realm that uses the LoginModule
class provided by JAAS

7.4 Realm 7-5

Realms can use various data sources as their user databases.


The different realms include JDBCRealm, which uses databases, DataSourceRealm, where a
JDBC DataSource class is specified, JNDIRealm, which uses LDAP (Light weight Directory
Access Protocol), MemoryRealm, which uses XML files to contain user information in a
prescribed format, and JAASRealm, which uses the LoginModule class provided by JAAS.
In addition, it is possible to implement application-specific realms.
Tomcat specifies MemoryRealm by default.

7-5

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5 Secure Application Programming

7.5.1 Path-traversal

7.5.2 Parameter Alteration

7.5.3 Overflow

7.5.4 Command Injection

7.5.5 Cross-Site Scripting

7.5.6 Programming Countermeasures

7.5 Secure Application Programming 7-6

7-6

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.1 Path-traversal
Information, which is normally hidden, is displayed
by specifying special characters for a URL.

URL
http://abc.com/cgi-bin/list.cgi?file=../../user_list.txt

Web browser Illegal character string

Web server

7.5.1 Path-traversal 7-7

Path-traversal refers to a phenomenon where information that normally must not be shown in a
system is streamed to a user by specifying an illegal URL such as “upper directory” for
parameters etc.
In the majority of the cases, it is possible to prevent path-traversal simply by setting the
security settings of the Web servers tightly. In addition, system developers should always take
precautions about information that must not be made public by locating it in a non-disclosed
directory and other secure area.

7-7

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.2 Parameter Alteration
Sending illegal parameters by assuming purposes
of a variable from the HTML source code.

HTML source <input type=“hidden” name=“session_info” value=“1234”/>


<input type=“hidden” name=“user_code” value=“101”/>

Web server
Web browser

7.5.2 Parameter Alteration 7-8

Many Web browsers allow viewing the source of a downloaded HTML file.
HIDDEN type tags that are not rendered on the webpage display can be used for INPUT
tags that return variable values to the server, but since it is possible examine the HTML source,
the hidden data may be revealed and exploited.
Since it is possible to tamper with these parameters and send them back to the server, there
may be circumstances where it is possible to execute processing not expected by the system.
Data that must not be tampered with must not be embedded in HIDDEN type tags, or they
must be encrypted or protected other ways.

7-8

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.3 Overflow
If an abnormally long data string is sent as a
parameter, the server may go down or illegal
processing may be executed.
User ID
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Web server
Web browser

7.5.3 Overflow 7-9

If countermeasures against long character strings and others are not taken in programs on the
server side, there may be cases where the server can be forced to go down or illegal processing
is executed.
Programs receiving parameters must take measures against these issues through strict
checking, including parameter length and prohibited characters, as well as encoding.

7-9

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.4 Command Injection
Illegal processing may be executed by embedding
SQL statements, commands etc. in parameters.

Correct processing Illegal processing

list.cgi?type=1 list.cgi?type=1;DELETE FROM


USERS

Application Application

SELECT
SELECT ** FROM
FROM USERS
USERS SELECT
SELECT ** FROM
FROM USERS
USERS
WHERE TYPE=1
WHERE TYPE=1 WHERE TYPE=1;
WHERE TYPE=1;
DELETE
DELETE FROM
FROM USERS
USERS
DB DB

7.5.4 Command Injection 7-10

Command injection is a form of attack where SQL statements, commands and similar are
embedded in parameters, causing illegal processing to be executed. If the value obtained from
a parameter is used directly in an SQL statement as shown above, a attacker may cause an
illegal SQL statement to be executed on the target system.
Countermeasures against command injection can be taken by checking the contents of
parameters rigorously. In Java, it is possible to use JDBC’s PreparedStatement to check the
content of each parameter and ensure that the data is of a pre-specified type.

7-10

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.5 Cross-Site Scripting
A malicious script or similar is executed when the
content of a parameter is sent to HTML.

Contents
<script>
................................... Tags are executed.
</script>

Contents
................................................

Web browser Web browser

7.5.5 Cross-Site Scripting 7-11

In cross-site scripting, a attacker may embed <script> and <object> tags in parameters if
values input to parameters are sent out as HTML, making the user open particular pages and
execute illegal processing.
HTML data is encoded according to specific rules when sent out. It is necessary to take
robust countermeasures by encoding entities included in parameters entered by users including
< and > as well as &lt; and &gt; carefully.

7-11

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION


7.5.6 Programming Countermeasures
・Verification of length
・Verification of encoding
・Verification that illegal character strings
are not used
・Verification that all parameter values are
within the appropriate range

Parameter acquisition
・When a parameter value is
used for SQL, check that
Business logic processing
illegal SQL is not included.

HTML generation processing


Web Browser

・When a parameter
value is used for HTML, Web application
check that the value is
encoded correctly.

7.5.6 Programming Countermeasures 7-12

In order to prevent the illegal procedures explained so far, it is necessary to take


countermeasures against these attacks into consideration when developing applications.
Rigorous verification of parameters obtained from users is particularly important in preventing
many illegal procedures. It is not only necessary to verify the parameter value length, but also
to perform meticulous checking of whether or not values are properly encoded, whether or not
illegal characters are used and whether values are in a proper range. Since these procedures are
often used in Web applications, it is a good idea to use a sophisticated library or create a
dedicated library for the purpose.
Furthermore, there are many cases where SQL is generated based on parameters during the
execution of business logic processing. In these cases as well, it is necessary to check that
illegal SQL is not included. This can for instance be done by using the PreparedStatement
class and similar classes that check parameter types.
When parameter values are included in a generated HTML document, it is necessary to
check that the content is properly encoded. It is very important to understand that proper
processing of parameters is the most important method to protect applications from illegal
processing.

7-12

Copyright 2007 NIPPON TELEGRAPH AND TELEPHONE EAST CORPORATION

You might also like