Key Management and PKCS#11 Tokens in Sun Java System Application Server 8.1
By Shing Wai Chan, May 19, 2005
Today, many enterprise applications exchange sensitive data passwords, credit card numbers, personal profile information and require a secure environment. Toward that end, most applications secure their communications with the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol. However, using those protocols presents a couple of challenges:
- Performance Both SSL and TLS require encryption of the symmetric key and public key. Encrypting the symmetric key can be fast, but encrypting the public key can be slow.
- Protection of private keys Cryptography of public keys depends on the confidentiality of private keys. Secure storage of private keys is difficult to achieve in SSL and TLS communications.
An alternative to resolve these issues is to use Public-Key Cryptography Standards #11 (PKCS#11) tokens. For example, you can use hardware accelerator tokens to improve the cryptographic performance and to furnish a secure key storage facility. Also, you can provide end users with mobile secure key storage by means of smart cards.
Sun Java System Application Server 8.1 Standard Edition or Enterprise Edition (henceforth, Application Server), when run on the Java 2 Platform, Standard Edition (J2SE platform) 5.0, supports the use of PKCS#11 tokens for SSL or TLS communications and Network Security Services (NSS) tools for managing keys and PKCS#11 tokens. This article describes how Application Server provides that support and walks you through the procedures for the related configurations.
Terminology
Here is an explanation of the terms used in this article:
- Public-Key Cryptography Standards #11 (PKCS#11) The definition of a standard native programming interface to cryptographic tokens, such as hardware cryptographic accelerators, smart cards, and so forth.
- PKCS#11 provider The cryptographic service provider that acts as a wrapper around a native PKCS#11 library.
- PKCS#11 token A token that generically refers to all the hardware and software tokens with a native PKCS#11 interface. A hardware token is a PKCS#11 token implemented in physical devices, such as hardware accelerators and smart cards. A software token is a PKCS#11 token implemented entirely in software.
- Hardware accelerator A hardware cryptographic chip or board.
- Smart card A personal security storage device.
- Personal Information Exchange Syntax Standard (PKCS#12) The definition of a standard format for storing private keys and their corresponding certificates.
- Network Security Services (NSS) A set of libraries that provides a programming interface and command-line tools for key management, communication by SSL or TLS, and token configurations for PKCS#11. The NSS libraries and tools are developed as part of an open-source effort.
Overview of Architecture and Environment Variable Settings
When used in conjunction with J2SE 5.0, Application Server can communicate with PKCS#11 tokens. Within Application Server are an NSS PKCS#11 token library (for the NSS Internal PKCS#11 Module, commonly known as the NSS soft token) and NSS command-line management tools. See Figure 1 for the basic architecture.
Figure 1 Application Server Support for PKCS#11
You use the NSS tools to create keys and certificates on PKCS#11 tokens and J2SE PKCS#11 providers to access token keys and certificates at runtime.
Note: If you run Application Server on the J2SE 1.4.x platform, Application Server supports only one PKCS#11 token the NSS soft token.
To access the native NSS tools, do the following:
- For the UNIX environment, add the location of
$AS_NSS(the directory in which the NSS libraries reside in your Application Server installation) to theLD_LIBRARY_PATHvariable and the location of$AS_NSS_BIN(the directory in which the NSS tools reside) to thePathenvironment variable.- If you use a Bourne shell, a Korn shell, or a Bash shell, type:
- If you use a
cshortcshshell, type:
LD_LIBRARY_PATH=$AS_NSS:$LD_LIBRARY_PATH export LD_LIBRARY_PATH PATH=$AS_NSS_BIN:$PATH export PATH - For the Microsoft Windows environment, add the location of
$AS_NSSand the NSS tools directory ($AS_NSS_BIN) to thePATHenvironment variable. Type:set path=%AS_NSS%;%AS_NSS_BIN%;%path%
For simplicity, the procedures described in the rest of this article use UNIX commands only. You should replace the UNIX $ variable with the Windows % variable, if appropriate.
The environment variables referred to in this article are set to their default values during installation. See Table 1.
Table 1 Default Values of Environment Variables
| Description | Environment Variable and Default Value |
|---|---|
| Configuration directory of Application Server | AS_DOMAIN_CONFIG = /var/opt/SUNWappserver/domains/domain1/config |
| Installation directory of Application Server | AS_INSTALL = /opt/SUNWappserver/appserver |
| NSS libraries |
AS_NSS = /usr/lib/mps |
| NSS tools |
AS_NSS_BIN = /opt/SUNWappserver/appserver/lib |
| NSS database directory |
AS_NSS_DB: same as AS_DOMAIN_CONFIG when you use the Domain Administration Server (DAS) |
Configuration of PKCS#11 Tokens
This section describes how to configure PKCS#11 tokens with the NSS security tool modutil. Follow these steps:
To configure a PKCS#11 token, type (all on one line):
% modutil -dbdir $AS_NSS_DB -nocertdb -force -add moduleName
-libfile absolute_path_of_pkcs11_library
-mechanisms list_of_security_mechanisms
For example, to configure a hardware accelerator token, type (all on one line):
% modutil -dbdir $AS_NSS_DB -nocertdb -force -add "Sun Crypto Accelerator" -libfile /opt/SUNWconn/crypto/lib/libpkcs11.so -mechanisms RSA:DSA:RC4:DES
The mechanisms must be a complete list of the cryptographic mechanisms that are available in the token. To use only some of the cryptographic mechanisms, see the section, " Configuration of J2SE 5.0 PKCS#11 Providers." For a list of the supported mechanisms, see the
modutil documentation on the NSS Security Tools site.
The hardware accelerator in this example is a SCA 1000 Cryptographic Accelerator. The corresponding PKCS#11 library is located in
/opt/SUNWconn/crypto/lib/libpkcs11.so. The examples that follow assume that the token name specified at token installation time is
mytoken.
Verify that the hardware accelerator is configured properly. Type:
% modutil -list -dbdir $AS_NSS_DB
The standard output looks like this:
Using database directory /var/opt/SUNWappserver/domains/domain1/config ...
Listing of PKCS#11 Modules
-----------------------------------------------------------
1. NSS Internal PKCS#11 Module
slots: 2 slots attached
status: loaded
slot: NSS Internal Cryptographic Services
token: NSS Generic Crypto Services
slot: NSS User Private Key and Certificate Services
token: NSS Certificate DB
2. Sun Crypto Accelerator
library name: /opt/SUNWconn/crypto/lib/libpkcs11.so
slots: 1 slot attached
status: loaded
slot: Sun Crypto Accelerator:mytoken
token: mytoken
-----------------------------------------------------------
Key Management
This section describes a few common procedures for creating and managing keys and certificates and for running those tasks with certutil and pk12util. For details, see the certutil and pk12util documentation on the NSS Security Tools site.
Note: By configuring a PKCS#11 provider in the java.security properties file (located in the $JAVA_HOME/jre/lib/security directory of the Java runtime), you can also use the J2SE keytool utility to manage keys and certificates. For details, see the Java PKCS#11 Reference Guide .
Listing Keys and Certificates
To list the keys and certificates in the configured PKCS#11 tokens, run the following command:
% certutil -L -d $AS_NSS_DB [-h tokenname ]
For example, to list the contents of the default NSS soft token, type:
% certutil -L -d $AS_NSS_DB
The standard output is as follows:
verisignc1g1 T,c,c
verisignc1g2 T,c,c
verisignc1g3 T,c,c
verisignc2g3 T,c,c
verisignsecureserver T,c,c
verisignc2g1 T,c,c
verisignc2g2 T,c,c
verisignc3g1 T,c,c
verisignc3g2 T,c,c
verisignc3g3 T,c,c
s1as u,u,u
The output displays the name of the token in the left column and a set of three trust attributes in the right column, most commonly T,c,c for Application Server certificates. Unlike the J2SE java.security.KeyStore API, which contains only one level of trust, the NSS technology contains several levels of trust. The Application Server technology is primarily interested in the first trust attribute, which describes how this token uses SSL. For this attribute:
Tindicates that the Certificate Authority (CA) is trusted for issuing client certificates.uindicates that you can use the certificates (and keys) for authentication or signing.
The attribute combination of u,u,u indicates that a private key exists in the database.
To list the contents of the hardware token mytoken, type:
% certutil -L -d $AS_NSS_DB -h mytoken
You are then prompted for the password for the hardware token. The standard output is as follows:
Enter Password or Pin for "mytoken":
mytoken:Server-Cert u,u,u
Creating Private Keys and Certificates
To create a self-signed certificate, type (all on one line):
% certutil -S -x -n nickname -t trustargs -v num_of_valid_months -s subjectDN -d $AS_NSS_DB [-h tokenname ]
To create a certificate request, type (all on one line):
% certutil -R -k [rsa|dsa] -s subjectDN [-h tokenname] -d $AS_NSS_DB [-p phone ] [-o output-file ]
For example, to create a self-signed certificate in an NSS soft token, type:
% certutil -S -x -n "mycert" -t "u,u,u" -v 120 -s "cn=nobody,ou=Org,o=Sun,L=Santa Clara,ST=California,C=US" -d $AS_NSS_DB
Here is the standard output:
A random seed must be generated that will be used in the
creation of your key. One of the easiest ways to create a
random seed is to use the timing of keystrokes on a keyboard.
To begin, type keys on the keyboard until this progress meter
is full. DO NOT USE THE AUTOREPEAT FUNCTION ON YOUR KEYBOARD!
Continue typing until the progress meter is full:
|************************************************************|
Finished. Press enter to continue:
Enter Password or Pin for "NSS Certificate DB":
Generating key. This may take a few moments ...
Warning: It is not safe to use options to specify the location of a password file and a noise file (a stream of random characters) in order to eliminate prompting in the command. If you do choose to use those options, here is the syntax:
[-f passwordfile ] [-z noisefile ]
Importing Or Exporting Certificates
To import a certificate, type (all on one line):
% certutil -A -n [ tokenname :] aliasname -t trustargs -d $AS_NSS_DB -h tokenname -i certfile
To export a certificate, type (all on one line):
% certutil -L -n [ tokenname :] aliasname [-r | -a] -d $AS_NSS_DB > afile
Note the following:
- If you use the
-roption, the corresponding certificate file is encoded with Distinguished Encoding Rules (DER) encoding. - If you use the
-aoption, the corresponding certificate file is in Base64 DER encoding.
For example, to export s1as certificates from an NSS soft token and then import them into your PKCS#11 hardware token, type:
% certutil -L -n s1as -r -d $AS_NSS_DB > s1as.cert
% certutil -A -n mys1as -t "T,c,c" -d $AS_NSS_DB -h mytoken -r -i s1as.cert
Importing Or Exporting Private Keys
To exchange private keys and certificates with an NSS database, first convert the private key and corresponding certificate to PKCS#12 format with the pk12util utility.
To import a PKCS#12 format file into an NSS database, type:
% pk12util -i pkcs12file -d $AS_NSS_DB [-h tokenname ]
To export a key into a PKCS#12 format file, type:
% pk12util -o pkcs12file -n [ tokenname :] aliasname -d $AS_NSS_DB
Most hardware accelerators do not support the exporting of private keys.
For example, to import a PKCS#12 format file, mps.p12, into an NSS soft token, type:
% pk12util -i mps.p12 -d $AS_NSS_DB
You are then prompted for the passwords for the NSS soft token and PKCS#12 file. The standard output is as follows:
Enter Password or Pin for "NSS Certificate DB":
Enter password for PKCS12 file:
pk12util: PKCS12 IMPORT SUCCESSFUL
Warning:not
[-kslotpwfile] [-Kslotpw] [-wp12pwfile] [-Wp12pw]
Deleting Keys Or Certificates
You delete the keys and certificates by referencing their associated alias names, as follows:
% certutil -D -n [ tokenname :] aliasname -d $AS_NSS_DB
For example, to delete the key that corresponds to the alias myalias in an NSS soft token, type:
% certutil -D -n myalias -d $AS_NSS_DB
To delete the key that corresponds to the alias myalias in the hardware token mytoken, type:
% certutil -D -n mytoken:mys1as -d $AS_NSS_DB
You are then prompted for the password for the hardware token.
Changing Passwords
To modify the NSS password, use the asadmin change-master-password command, as follows:
Stop the domain. Type:
% asadmin stop-domain domain1
Modify the master password. Type:
% asadmin change-master-password
Warning: It is not safe to use an asadmin option to save the master password in the local disk. If you do choose to do so, then the syntax is as follows:
% asadmin change-master-password --savemasterpassword
Enter the new master password twice at the prompt, as follows:
Please enter the new master password>
Please enter the new master password again>
Master password changed for domain domain1
Start the domain. Type:
% asadmin start-domain --user admin domain1
Warning: In Application Server, do not modify the NSS password directly with the NSS tools certutil and modutil. If you do so, security data in Application Server might become corrupted.
Configuration of J2SE 5.0 PKCS#11 Providers
As mentioned, Application Server relies upon J2SE PKCS#11 providers to access keys and certificates that are located in PKCS#11 tokens at runtime. By default, Application Server configures a J2SE PKCS#11 provider for the NSS soft token. This section describes how to override the default configuration for the J2SE PKCS#11 provider.
Note: A future release of Application Server will enable you to customize the PKCS#11 configuration in the administration GUI. In the meantime, follow the steps in this section to perform the customization.
In Application Server, the following default PKCS#11 configuration parameters are generated for each PKCS#11 token:
- Configuration for the default NSS soft token:
- Configuration for the SCA 1000 hardware accelerator:
name=internal
library=${com.sun.enterprise.nss.softokenLib}
nssArgs="configdir='${com.sun.appserv.nss.db}'
certPrefix='' keyPrefix='' secmod='secmod.db'"
slot=2
omitInitialize = true
name=HW1000
library=/opt/SUNWconn/crypto/lib/libpkcs11.so
slotListIndex=0
omitInitialize=true
The above configurations conform to the syntax described in the Java PKCS#11 Reference Guide . Note that the name parameter has no requirements other than that it must be unique. Certain older versions of J2SE 5.0 support alphanumeric characters only.
You can override the default configuration parameters by creating a custom configuration file. For example, you can explicitly disable the RSA Cipher and RSA Key Pair Generator in SCA 1000. (For details, see the NSS site.) To create a custom configuration file, do the following:
Create a configuration file called $AS_INSTALL/mypkcs11.cfg with the following code. Save the file.
name=HW1000
library=/opt/SUNWconn/crypto/lib/libpkcs11.so
slotListIndex=0
disabledMechanisms = {
CKM_RSA_PKCS
CKM_RSA_PKCS_KEY_PAIR_GEN
}
omitInitialize=true
Update the NSS database, if necessary.
In this case, update the NSS database so that it will disable RSA: Run the following command (all on one line):
% modutil -undefault "Sun Crypto Accelerator" -dbdir $AS_NSS_DB -mechanisms RSA
The name of the algorithm on the mechanisms list differs from the one in the default configuration. For a list of valid mechanisms in NSS, see the modutil documentation on the NSS Security Tools site.
Inform the server of this change by adding a property in the appropriate location, as follows:
<property name="mytoken" value="$AS_INSTALL/mypkcs11.cfg"/>
The location is either of the following:
- If the provider is for a DAS or server instance, add the property under the associated
<security-service>element in thedomain.xmlfile. - If the provider is for a node agent, add the property under the associated
<node-agent>element in thedomain.xmlfile.
Restart the server.
The customized configurations are then in effect.
Start of Application Server
When Application Server starts, it prompts for the administrator password, the master password (if necessary), and the token password. In the example in this section, the administrator has the following login credentials:
- User name:
admin - Password:
adminadmin - Shared master password:
admin123 - Token password:
mysecret
Note: If a configured PKCS#11 token does not require a login, Application Server does not prompt for a token password.
To start Application Server with asadmin, which is located at $AS_INSTALL/bin, type:
% asadmin start-domain --user admin domain1
The standard output is as follows:
Starting Domain domain1, please wait.
Log redirected to /var/opt/SUNWappserver/domains/domain1/logs/server.log.
Please enter password>
Please enter master password>
Please enter password for NSS slot mytoken>
Warning:not
% asadmin start-domain --user admin --passwordfile pwdfile domain1
The content of the pwdfile file is as follows:
AS_ADMIN_PASSWORD=adminadmin
AS_ADMIN_MASTERPASSWORD=admin123
AS_ADMIN_mytoken=mysecret
--passwordfile pwdfilepassword.confpassword.conf$AS_DOMAIN_CONFIG--passwordfile
Also, the formats of the password.conf file and the pwdfile file specified by the --passwordfile option are different. In Application Server 7, the password.conf file reads like this:
internal:admin123
mytoken:mysecret
Conclusion
J2SE 5.0 PKCS#11 providers are seamlessly integrated with the Application Server runtime. Through those providers, you can use hardware accelerators and other PKCS#11 tokens in Application Server to achieve fast performance and to protect the private key inherent in SSL or TLS communications.
Future releases of Application Server may contain enhancements in the administration of PKCS#11 providers from the Administration Console.
Appendix: Migration Between J2SE KeyStore and NSS
In Sun Java System Application Server Platform Edition 8.1 (Application Server 8.1 PE) and other Java environments, the default J2SE KeyStore type, JKS, stores keys and certificates. This appendix describes how to migrate keys and certificates between JKS KeyStores and NSS.
Figure 2 illustrates the scenario.
Figure 2 Migration of Keys and Certificates Between JKS KeyStores and NSS
Importing and Exporting Certificates
For details on importing and exporting certificates from NSS to DER-encoded files, see the section, " Key Management." To import or export certificates between a JKS KeyStore and DER-encoded certificate files, use the J2SE keytool utility, as follows:
% keytool -import -trustcacerts -alias aliasname -keystore keystoreLocation -file certfile
% keytool -export -alias aliasname -keystore keystoreLocation -file certfile
Importing and Exporting Private Keys
For details on importing and exporting private keys from NSS to PKCS#12 files, see the section, " Key Management." Because you cannot use keytool to import or export PKCS#12 files into a JKS KeyStore, you must perform this conversion programmatically with the java.security.KeyStore API. The sample program, JKS2NSS.java, as described below, demonstrates how to use this API.
Before running the sample program in a UNIX environment, define the NSS library directory in the LD_LIBRARY_PATH variable, as discussed in " Overview of Architecture and Environment Variable Settings." A sample pkc11.cfg file reads like this:
name=internal
library=/usr/lib/mps/libsoftokn3.so
nssArgs="configdir='/var/opt/SUNWappserver/domains/domain1/config'
certPrefix='' keyPrefix='' secmod='secmod.db'"
slot=2
Similarly, for the Microsoft Windows environment, the NSS library directory must be in the PATH variable. In that environment, the library file to be set in the pkcs11.cfg file is softokn3.dll.
You can run the sample program JKS2NSS.java in a J2SE 5.0 environment with the PKCS#11 provider configured to export private keys and certificates from a JKS KeyStore into NSS. Furthermore, you can easily modify this program to do the conversion in the opposite direction.
After creating JKS2NSS.java, execute it, as follows:
% java JKS2NSS keystore.jks myjkspwd pkcs11.cfg mysecret
The code reads as follows:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Enumeration;
import sun.security.pkcs11.SunPKCS11;
/**
* Sample program to convert JKS to NSS.
* @Author Shing Wai Chan
*/
public class JKS2NSS {
public static void main(String args[]) throws Exception {
if (args.length != 4) {
System.out.println("java JKS2NSS <ksloc> <kspwd> <pkcs11.cfg> <pk11pwd>");
System.exit(1);
}
String ksloc = args[0];
char[] kspwd = args[1].toCharArray();
String pkcs11cfg = args[2];
char[] pk11pwd = args[3].toCharArray();
BufferedInputStream bin = null;
try {
loadNSSLibrary();
Provider p = new SunPKCS11(pkcs11cfg);
Security.addProvider(p);
KeyStore toKS = KeyStore.getInstance("PKCS11");
toKS.load(null, pk11pwd);
KeyStore fromKS = KeyStore.getInstance("JKS");
bin = new BufferedInputStream(new FileInputStream(ksloc));
fromKS.load(bin, kspwd);
Enumeration e = fromKS.aliases();
while (e.hasMoreElements()) {
String alias = (String)e.nextElement();
System.out.println("Processing alias: " + alias);
if (fromKS.isKeyEntry(alias)) {
Key key = fromKS.getKey(alias, kspwd);
Certificate[] chain = fromKS.getCertificateChain(alias);
toKS.setKeyEntry(alias, key, pk11pwd, chain);
} else {
Certificate cert = fromKS.getCertificate(alias);
toKS.setCertificateEntry(alias, cert);
}
}
} finally {
if (bin != null) {
bin.close();
}
}
}
private static void loadNSSLibrary() {
if (File.separatorChar == '\\') {
// Window env
System.loadLibrary("libnspr4");
System.loadLibrary("libplc4");
System.loadLibrary("libplds4");
} else {
System.loadLibrary("nspr4");
System.loadLibrary("plc4");
System.loadLibrary("plds4");
}
}
}
References
- Sun Java System Application Server
Acknowledgment
Thanks to two of my Sun colleagues: Charlie Lai from the J2SE development team for his valuable comments regarding PKCS#11 and Debbie Carson for her suggestions for improving the article.
About the Author
Shing Wai Chan, a member of the Sun Java System Application Server and J2EE SDK development teams, has been with Sun for over six years. He has been focusing on development projects that relate to security, J2EE deployment, CMP, B2B, and B2C.