Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Security

How do I Password Encrypt Data?


Dr. Dobb's Journal August 1998: Java Q&A

Cliff is vice president and chief technology officer for Digital Focus. He is also the author of Advanced Java Development for Enterprise Applications (Prentice Hall, 1998). He can be contacted at [email protected]. To submit questions, check out the Java Developer FAQ web site at http://www.digitalfocus.com/faq/.


A friend of mine keeps a daily journal of his activities. Being rather self-conscious, he doesn't want anyone else to peruse the journal if they use his computer. Therefore, he uses a program called "Global Diary" (http://ayecor.com/html/gd.html) to automatically encrypt the data it stores, which can then only be decrypted by using the correct password.

There are many important uses for encryption of persistent data. For example, e-mail in a computer workstation shared by many people can be appropriated and read by a moderately savvy hacker if it is not protected. Or a hospital information system that caches patient data on a local workstation during use can leave sensitive patient data vulnerable to theft. It is not hard to come up with scenarios in which sensitive data could be accessed by those not authorized to use the information.

In these examples, the sensitive data is on a client machine, but server-resident data also may need to be encrypted for security. For example, the Java-based backup program BackOnline (http://www.divya.com/) uses encryption to protect data backed up to a server. Applications that store sensitive data centrally on behalf of users (loan or grant applications, for instance) need to protect the data from unauthorized access. Encrypting cached or stored data protects against such violations, since there is no way to use the data without knowing the associated key or password.

Encryption is also used in secure communication protocols, such as SSL, which handle the entire process of negotiating a suitable encryption method agreeable to both a client and server, and exchanging proof of identity in the form of digital certificates and challenge responses. This is appropriate for applications that need to communicate securely across an otherwise insecure network such as the Internet. In such uses, the encryption is transient, serving only to protect the data in transit. In my February 1998 column, I showed how to use SSL to create a secure communication connection. This month, I will show how to use encryption to protect data at its point of origin or destination.

Password-Based Encryption

If you've used UNIX, you're probably familiar with the crypt program, which takes a string of text and a password and encrypts the text. The password serves as a parameter for generating a key to use in the encryption. The same password can later be used to decrypt the encrypted text. The crypt program is often used by webmasters to implement simple password-based security for web applications; such an application employs a CGI script to encrypt a password entered by users, then compares that with a stored encrypted password (that way, the clear-text value of the password is not actually stored anywhere).

The crypt program requires two additional parameters, known as the "salt value" and "iteration count." The salt value is a string chosen by the programmer to further obfuscate the value to be encrypted, which helps thwart so-called "dictionary" searches. In dictionary searches, a would-be codebreaker uses a set of strings commonly used by people for passwords -- "mom," "cafebabe," "mypassword," and the like -- to narrow the search for the password.

The iteration count is a value chosen by the programmer, representing the number of times the crypt program should apply its encryption algorithm. A robust application of crypt would vary this parameter between uses, as long as the scheme for varying it is remembered so it can be reapplied correctly when decrypting the text. The password, salt value, and iteration count collectively represent the key used to encrypt the text, and the same values must be used to decrypt it.

A well-known algorithm for implementing password-based encryption is PKCS#5, the RSA Data Security Password-Based Encryption Standard. The PKCS#5 standard uses the Data Encryption Standard (DES) algorithm, combined with either MD2 (RFC 1422) or MD5 (RFC 1321) hash-code generation. You don't have to worry about the details of these, since those details are embedded in any PKCS#5 implementation.

The JCE and MemoirEncrypter

The package javax.crypto is distributed separately from the JDK because it is subject to export restrictions imposed by the U.S. Department of Commerce Bureau of Export Administration regulations, which prohibit the unlicensed export of any software that implements encryption technology. To obtain package javax.crypto, you must go to Javasoft's web site (http://java.sun.com/products/jdk/1.2/jce/) and answer questions confirming that you are within the U.S. and do not plan to sell the software to anyone to whom the U.S. State Department would not extend warm welcomes. Once you have downloaded package javax.crypto (also known as the "Java Cryptography Extension, or JCE"), you have an implementation of several encryption algorithms, including PKCS#5.

To demonstrate the use of the JCE in implementing password-based encryption, I present a program called "MemoirEncrypter," which provides a text editor, and lets you save text files in encrypted form. MemoirEncrypter prompts for a password when you first try to either open or save a file after starting the program. Once you have done one of these operations, it continues to use the same password until the next time you run the program.

Since MemoirEncrypter uses the PKCS#5 password-based encryption technique, I specify a salt value and iteration count. PKCS#5 requires the salt value to consist of eight arbitrary octets. The iteration count may be any positive integer. For MemoirEncrypter, I have chosen the values in Listing One. MemoirEncrypter lets users enter a password of up to 10 characters, although PKCS#5 permits a password of arbitrary length (including zero).

To perform encryption or decryption with JCE, you must construct a Cipher object for the required encryption algorithm. JCE supports several encryption algorithms, and the name of the password-based encryption algorithm is "PBEWithMD5AndDES" -- private final String cipherName = "PBEWithMD5AndDES";.

A cipher can be initialized either to encrypt or decrypt, by specifying its mode, which may have the value of ENCRYPT_MODE or DECRYPT_MODE. To encapsulate the construction and initialization of a password-based cipher, Listing Two takes a password, salt, iteration count, cipher name, and mode as parameters, and returns an initialized Cipher object.

The cipher is independent of the parameters, and the parameters are independent of the password. The cipher can be reinitialized multiple times, so it can be reused. Cipher initialization must occur before you start to encrypt or decrypt any sequence of text. Once the text is fully processed, you must reinitialize the cipher before you use it again.

To create a password-based encryption cipher using the parameters defined earlier, simply make the call in Listing Three.

For the Java cryptographic mechanism to find the JCE's PBEWithMD5AndDES algorithm, you must register the JCE as a cryptographic provider package. This step is necessary because Java uses a plug-in architecture for cryptographic algorithms, thereby allowing algorithms to be added from multiple independent sources. You can register a provider package by making an entry in the java.security file located in the lib/security directory of the Java installation. Simply add the last line in Listing Four to this file. When searching for an algorithm implementation, Java will use the precedence order specified by the numeric rank given in this file. You must also make sure that the JCE JAR file is in the classpath of the program.

Now that you have a cipher, you can construct a stream to which to write data, and then construct a cipher stream from that, as shown in Listing Five. A ciphered input stream can be constructed in an analogous manner.

The MemoirEncrypter program is shown in Figure 1. The complete source code for MemoirEncrypter is available electronically from DDJ (see "Resource Center," page 3) and at the Digital Focus web site (http://www.digitalfocus.com/).

Conclusion

Adding encryption to an application can address data privacy concerns, while allowing the application to distribute data to where it is used for maximum efficiency. Password protection is a scheme that most users are familiar with, and which, as implemented here, provides whatever level of protection is required. Applications with more stringent needs can use a cryptographic provider with even stronger encryption.

DDJ

Listing One

private final byte[] salt = {     (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd,
    (byte)0x22, (byte)0x44, (byte)0xab, (byte)0x12 };
private final int iterations = 10;


</p>

Back to Article

Listing Two

protected static Cipher computePBECipher(String password,         byte[] salt, int iterations, String cipherName, int mode)
throws Exception
{
    // Compute the key
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, iterations);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(cipherName);
    SecretKey key = keyFac.generateSecret(pbeKeySpec);
                    
    // Construct the cipher
    Cipher cipher = Cipher.getInstance(cipherName);
    cipher.init(mode, key, pbeParamSpec);
    return cipher;
}


</p>

Back to Article

Listing Three

Cipher cipher = computePBECipher(
    password,            // the user's chosen password
    salt,                // the "salt" - gets added to the password
    iterations,          // number of times to apply the encryption
    cipherName,          // "PBEWithMD5AndDES"
    Cipher.ENCRYPT_MODE  // use "DECRYPT" to reverse the process
);


</p>

Back to Article

Listing Four

## List of providers and their preference orders 
#
security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.crypto.provider.SunJCE   


</p>

Back to Article

Listing Five

FileOutputStream fos = null;fos = new FileOutputStream(path);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);

Back to Article


Copyright © 1998, Dr. Dobb's Journal

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.