The package includes cryptography-based classes, but it does not contain classes for actual encryption and decryption. That is the job of the javax.crypto package. This package supports symmetric-key cryptography, in which the same key is used for both encryption and decryption and must be known by both the sender and the receiver of encrypted data.

Secret Keys

The SecretKey interface represents an encryption key; the first step of any cryptographic operation is to obtain an appropriate SecretKey. Unfortunately, the keytool program supplied with the JDK cannot generate and store secret keys, so a program must handle these tasks itself. Here is some code that shows various ways to work with SecretKey objects:

import javax.crypto.*; import javax.crypto.spec.*; // Generate encryption keys with a KeyGenerator object KeyGenerator desGen = KeyGenerator.getInstance("DES"); // DES algorithm SecretKey desKey = desGen.generateKey(); // Generate a key KeyGenerator desEdeGen = KeyGenerator.getInstance("DESede"); // Triple DES SecretKey desEdeKey = desEdeGen.generateKey(); // Generate a key // SecretKey is an opaque representation of a key. Use SecretKeyFactory to // convert to a transparent representation that can be manipulated: saved // to a file, securely transmitted to a receiving party, etc. SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec desSpec = (DESKeySpec) desFactory.getKeySpec(desKey, javax.crypto.spec.DESKeySpec.class); ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.