JDK Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.32, 2006

JCE - Cipher for Encryption and Decryption

Part:   1   2  3 

JDK Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Internationalization

Character Set and Encoding

Socket Communication

Document Object Model (DOM)

XSD Validation in Java

XSL - Transformer in Java

JCA - Private and Public Key Pairs

JCE - Secret Key

SSL (Secure Socket Layer)

SSL - Client Authentication

... Table of Contents

This chapter describes some parts of the JCE (Java Cryptography Extension) which has been introduced in JDK since 1.1:

  • The Cipher class.
  • How to use cipher with secret keys for encryption and decryption.
  • How to use cipher with private and public key pairs for encryption and decryption.

The Cipher Class

javax.crypto.Cipher is a class that provides functionality of a cryptographic cipher for encryption and decryption. It has the following major methods.

getInstance() - Returns a Cipher object of the specified transformation (algorithm plus options) from the implementation of the specified provider. If provider is not specified, the default implementation is used. This is a static method.

init() - Initializes this cipher for the specified operation mode with the specified key or public key certificate. Two important operation modes are Cipher.ENCRYPT_MODE and Cipher.DECRYPT_MODE.

update() - Feeds additional input data to this cipher and generates partial output data.

doFinal() - Feeds the last part of the input data to this cipher and generates the last part of the output data.

getBlockSize() - Returns the block size of this cipher.

getAlgorithm() - Returns the algorithm name of this cipher.

getProvider() - Returns the provider as a Provider object of this cipher.

JceSecretCipher.java - Cipher with Secret Key

The following sample program shows you how to do encryption and decryption with a secret key:

/**
 * JceSecretCipher.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
import java.io.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class JceSecretCipher {
   public static void main(String[] a) {
      if (a.length<5) {
         System.out.println("Usage:");
         System.out.println("java JceSecretCipher algorithm mode keyFile"
            +" input output");
         return;
      }
      String algorithm = a[0];
      String mode = a[1];
      String keyFile = a[2];
      String input = a[3];
      String output = a[4];
      try {
         SecretKey ky = readKey(keyFile,algorithm);
         secretCipher(algorithm, mode, ky, input, output);
      } catch (Exception e) {
         System.out.println("Exception: "+e);
         return;
      }
   }

(Continued on next part...)

Part:   1   2  3 

Dr. Herong Yang, updated in 2006
JDK Tutorials - Herong's Tutorial Notes - JCE - Cipher for Encryption and Decryption