대칭키를 이용한 암호화와 복호화

지난글 에서는 서로 다른 키를 사용하는 암호화와 복호화, 즉 비대칭 암호화(asymmetric encryption)에 관해 설명했다. 하지만 암호화와 복호화는 대칭적으로 작업할 수도 있다. 이 글에서 데이터를 암호화하고 복호화하는데 같은 키를 사용하고 있는 예를 볼 수 있다. 양쪽 다 동일한 키를 사용하기 때문에 복호화는 암호화 과정의 일부를 역으로 적용하면 된다. Blowfish 알고리즘이 대칭 키의 한 예이다. Blowfish 알고리즘은 Java Cryptography Extension (JCE)에 의해 지원되고 javax.crypto.* packages에서 적절한 APIs를 찾을 수가 있다. 현재 JCE에 의해 지원되는 암호 알고리즘(cipher algorithm)은 Blowfish뿐만 아니라, Digital Encryption Standard (DES), Triple DES Encryption (DESede), Password-based encryption algorithm (PBEWithMD5AndDES)이 있다.

대칭 키 알고리즘은 비대칭 키 알고리즘보다 훨씬 빠른 경향이 있다. 게다가 첫번째 글에서 본 것과 같이 암호화될 수 있는 텍스트의 사이즈가 공개 키와 비밀 키를 생성할 때 사용되었던 두개의 소인수 곱의 크기에 의해 좌우된다. 하지만 대칭 키 알고리즘을 사용하면 암호화하고자 하는 대상의 전체 크기에 전혀 제한을 받지 않는다. 대칭 암호 알고리즘(symmetric cipher algorithms)의 종류에 따라 다르지만, 전제 입력 사이즈는 블록 사이즈의 배수여야하고 패딩(padding)이 요구될 수도 있다. 대칭 키와 관련한 문제는 이 키들이 암호화나 복호화에 관련된 파티내에서는 공유되어야만 한다는 데에 있다. 그렇기 때문에 차단이 되거나 공인되지 않은 사용자가 공유하는 등의 문제가 생길 수 있다.

대칭 키를 생성하는 것은 키 쌍을 생성했던 것과 매우 흡사하다. KeyGenerator 클래스의 factory 메소드를 사용하고 스트링값을 알고리즘에 대입하자. generateKey() 메소드를 호출하면 KeyPair 인터페이스 대신 Key 인터페이스를 구현하는 객체를 되받을 수 있다.

  SecretKey key =
         KeyGenerator.getInstance("DES").generateKey();

다음으로 Cipher를 생성하는데, 이는 JCE를 이용할 때 편리하다. 애플리케이션을 바꿀 필요 없이 서로 다른 제공자의 이점을 취하기 위해서 Cipher 클래스의 factory 메소드를 재사용하자. 이하의 방법으로 Cipher를 생성한다.

   Cipher cipher = Cipher.getInstance("DES");

Cipher
는 바이트 어레이 형태로 넘겨진 데이터를 암호화 혹은 복호화하는데 사용된다. 어떤 동작이 호출될지를 지정하는 init()과 그 연산을 실행하는 doFinal() 메소드가 꼭 사용해야만 하는 필수 메소드들이다. 가령, 다음 2줄의 코딩은 바이트 어레이를 암호화하기 위해 생성한 textBytes라고 불리는 cipherkey 인스턴스를 사용하고 있다. 결과는 encryptedBytes라고 불리는 바이트 어레이 내에 저장된다.

   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] encryptedBytes =
      cipher.doFinal( textBytes );

다음 프로그램은 위의 값을 모으면서 입력 스트링을 받은 후에 그것을 암호화한다. 그리고나서 암호화된 스트링은 다시 복호화된다.

  1.    import javax.crypto.Cipher;
  2.    import javax.crypto.BadPaddingException;
  3.    import javax.crypto.IllegalBlockSizeException;
  4.    import javax.crypto.KeyGenerator;
  5.    import java.security.Key;
  6.    import java.security.InvalidKeyException;
  7.  
  8.    public class LocalEncrypter {
  9.  
  10.         private static String algorithm = "DESede";
  11.         private static Key key = null;
  12.         private static Cipher cipher = null;
  13.  
  14.         private static void setUp() throws Exception {
  15.             key = KeyGenerator.getInstance(algorithm).generateKey();
  16.             cipher = Cipher.getInstance(algorithm);
  17.         }
  18.  
  19.         public static void main(String[] args)
  20.            throws Exception {
  21.             setUp();
  22.             if (args.length !=1) {
  23.                 System.out.println(
  24.                   "USAGE: java LocalEncrypter " +
  25.                                          "[String]");
  26.                 System.exit(1);
  27.             }
  28.             byte[] encryptionBytes = null;
  29.             String input = args[0];
  30.             System.out.println("Entered: " + input);
  31.             encryptionBytes = encrypt(input);
  32.             System.out.println(
  33.               "Recovered: " + decrypt(encryptionBytes));
  34.         }
  35.  
  36.         private static byte[] encrypt(String input)
  37.             throws InvalidKeyException,
  38.                    BadPaddingException,
  39.                    IllegalBlockSizeException {
  40.             cipher.init(Cipher.ENCRYPT_MODE, key);
  41.             byte[] inputBytes = input.getBytes();
  42.             return cipher.doFinal(inputBytes);
  43.         }
  44.  
  45.         private static String decrypt(byte[] encryptionBytes)
  46.             throws InvalidKeyException,
  47.                    BadPaddingException,
  48.                    IllegalBlockSizeException {
  49.             cipher.init(Cipher.DECRYPT_MODE, key);
  50.             byte[] recoveredBytes =
  51.               cipher.doFinal(encryptionBytes);
  52.             String recovered =
  53.               new String(recoveredBytes);
  54.             return recovered;
  55.           }
  56.    }

커맨드 라인의 파라미터로 어떤 텍스트나 입력할 수 있다. 가령, 커맨드 라인에 다음을 입력하면,

   java LocalEncrypter "Whatever phrase we would like to
    input at this point"

이하의 출력값을 보게 된다.

   Entered: Whatever phrase we would like to
    input at this point
   Recovered: Whatever phrase we would like to
    input at this point

위의 예에서 암호화와 복호화 모두 동일한 Key 객체를 사용해서 이뤄졌다. 암호화와 복호화는 대게 서로 다른 버츄얼 머신에서 발생하기 때문에 안전하게 키를 전송할 수 있는 메소드가 필요하다.

첫번째 글에서 비대칭 암호 알고리즘을 위한 키 쌍을 생성하는 방법을 공부했고, 두번째 글에서는 대칭 키를 사용하는 방법을 살펴보았다. 하지만 비대칭 키와 대칭 키를 결합해서 사용하는 또 다른 테크닉이 있다. 이 기법은 임의대로 대칭 키를 선택해서 데이터를 암호화하는데 사용한다. 그리고는 다른 파티의 공개 키를 이용해서 대칭 키 그 자체가 암호화된다. 그러면 받는 사람은 대칭 키를 암호화하기 위해서 그들의 비밀 키를 이용하고 메시지를 복호화하기 위해 복호화된 키를 이용한다. 비대칭 기법에서 사용되는 모듈러스는 대칭 키를 암호화할 정도의 크기만 되면 된다. 대칭 키는 단일 전송을 위해서 사용된 후 제거된다. 이러한 방법으로 각각의 타입의 단점이 보완된다. 각 주제에 대한 자세한 정보는 다음을 참고하기 바란다.

DES Encryption

from http://kr.sun.com/developers/techtips/c2004_01_16.htm

2007/05/24 01:58 2007/05/24 01:58
Trackback Address:이 글에는 트랙백을 보낼 수 없습니다

KEYPAIRGENERATOR를 이용해서 비대칭 암호 키 구하기

공개 키 암호화(public key encryption)는 사용자가 암호화(encrypt)한 메시지를 복호화(decrypt)하거나 복호화만이 가능한 메시지를 암호화하는데 사용되는 공개 키(public key)를 제공할 수 있도록 해준다. Dr. Ronald L. Rivest, Dr. Adi Shamir, 그리고 Dr. Leonard M. Adleman가 RSA 암호화 코드의 R, S, A에 해당한다. 이들은 공개 키 암호기법(cryptography)으로 ACM's 2002 Turing Award Winners를 수상하였고, ACM Turing Award Winners웹페이지에서 "Early Days of RSA", "Cryptology: A Status Report", "Pre-RSA."에 관한 이들의 프리젠테이션을 볼 수 있다.

RSA 암호화 알고리즘(RSA encryption algorithm)은 임의적이고 상호 독립적인, 가령 p=11, q=31과 같은 크기가 큰 두 개의 소인수를 선택하는 것으로부터 시작한다. 다음으로 N=(p)(q)를 계산하는데, p=11, q=31인 경우에는 N=(11)(31)=341이다. 그리고는 정수 e를 하나 선택하는데 (p-1)(q-1)와 공통인수가 없는 3과 N-1 사이의 범위에서 선택한다. 수 300은 (2)(2)(3)(5)(5)으로 소인수분해 되기 때문에 2, 3, 혹은 5의 배수는 정수 e의 선택범위에서 제외된다. 이 알고리즘에 대입하는 수는 꼭 소인수가 아니어도 되기 때문에 49나 77과 같은 수도 가능하다. 간단하게 e= 7을 대입해보자.

다음으로 (d)(e)=1 (mod(p-1)(q-1))을 성립하는 정수 d가 필요하다. 여기서 mod는 나머지 연산이다. 위의 예제에서 e = 7 이고 (p -1)(q-1) = 300이기 때문에 d는 7d % 300 = 1을 통해 구한다. 연산의 방법은 300의 배수를 하나 이상 찾고 이 중, 7로 나누어 떨어지는 첫번째 숫자를 찾아내면 된다. 다시 말하면, 301, 601, 901 등이 가능한 값들이다. 이중 301은 7로 나누어 떨어지기 때문에(43*7은 301이다.) d는 43이다.

여기서 2쌍의 숫자들이 중요한데, RSA 모듈에 따르면 N = (p)(q)이고, 이 두 쌍의 숫자들이 이 식의 컴포넌트들이다. 첫번째 숫자쌍이 RSA 비밀 키(private key)인 (N,d)이고, 두 번째 숫자쌍이 RSA 공개키(public key)인 (N,e)이다. D는 RSA 비밀 지수(private exponent) (d=7)이고 e는 RSA 공개 지수(public exponent) (e=43)이다. 이미 알고 있는 공개 키는 공개하자. 그렇지만 비밀 키(특히 d)와 최초의 소인수들(p와 q)은 비밀로 유지해야 한다.

그렇다면 자바 프로그래밍 랭귀지가 RSA 구성의 어느 부분에서 쓰여지는 것일까? 이는 java.security 패키지를 통해 쓰여진다. 이 패키지를 이용하면 위에서 설명한 RSA 알고리즘에 필요한 쌍으로 이뤄진 키를 생성할 수 있다. 먼저 KeyPairGenerator의 인스턴스를 생성하고 그것을 비트형식의 원하는 키 사이즈로 초기화한다. 그리고 generateKeyPair()메소드를 호출하면 한 쌍의 RSA 키를 생성할 수 있다.

   KeyPairGenerator generator =
                   KeyPairGenerator.getInstance("RSA");
   generator.initialize(1024);
   KeyPair keyPair = generator.generateKeyPair();

이 알고리즘에서는 factory getInstance() 메소드에 스트링을 입력한다. 알고리즘이 인스톨된 제공자(provider)에 의해 지원되지 않으면 NoSuchAlgorithmException이 발생한다.

각각의 제공자는 반드시 디폴트 초기화를 공급하고 이를 문서화해야한다. 제공자 디폴트(provider default)가 사용자의 요구와 맞아 떨어지면, 중간 KeyPairGenerator 객체 (intermediate KeyPairGenerator object)를 저장할 필요가 없다. 한 줄의 코드로 키 쌍을 간단하게 생성할 수는 있지만 하나 이상의 키 쌍을 생성해야 한다면, KeyPairGenerator 객체를 재사용하는 것이 낫다. 왜냐하면 이는 새로운 KeyPairGenerator 객체를 매번 생성하는 것보다 훨씬 나은 퍼포먼스를 주기 때문이다.

  1.    import java.security.KeyPairGenerator;
  2.    import java.security.NoSuchAlgorithmException;
  3.    import java.security.KeyPair;
  4.  
  5.    public class AsymmetricKeyMaker {
  6.  
  7.       public static void main(String[] args) {
  8.         String algorithm = "";
  9.         if (args.length == 1) algorithm = args[0];
  10.  
  11.         try {
  12.           KeyPair keyPair = KeyPairGenerator
  13.                                .getInstance(algorithm)
  14.                                .generateKeyPair();
  15.  
  16.           System.out.println(keyPair.getPublic());
  17.           System.out.println(keyPair.getPrivate());
  18.  
  19.         } catch (NoSuchAlgorithmException e) {
  20.           System.err.println(
  21.             "usage: java AsymmetricKeyMaker <RSA | DSA>");
  22.         }
  23.  
  24.       }
  25.    }
  26.  


스트링 RSA는 rsa, Rsa 혹은 어떤 형태이든지 상관이 없다. 다음과 같은 프로그램을 실행하면

   java AsymmetricKeyMaker RSA

출력값은 이하와 같다.

   SunJSSE RSA public key:
      public exponent:
        010001
      modulus:
        b24a9b5b ba01c0cd 65096370 0b5a1b92 08f8555e
        7c1b5017 ec444c58 422b4109
        59f2e15d 43714d92 031db66c 7f5d48cd 17ecd74c
        39b17be2 bf9677be d0a0f02d
        6b24aa14 ba827910 9b166847 8154a2fa 919e0a2a
        53a6e79e 7d2933d8 05fc023f
        bdc76eed aa306c5f 52ed3565 4b0ec8a7 12105637
        af11fa21 0e99fffa 8c658e6d

   SunJSSE RSA private CRT key:
      private exponent:
        78417240 9059965d f3843d99 d94e51c2 52628dd2
        490b731e 6fb2317c 66451e7c
        dc3ac25f 519a1ea4 198df4f9 817ebe17 f7c73c00
        a1f96082 348f9cfd 0b63421b
        7f45f131 c363475c c1b25f57 ee029f5e 0848ba74
        ba81b730 ac4c0135 ce46478c
        e462361a 650e3356 f9b7a0c4 b682557d 3655c052
        5e3554bd 970100bf 10dc1b51
      modulus:
        b24a9b5b ba01c0cd 65096370 0b5a1b92 08f8555e
        7c1b5017 ec444c58 422b4109
        59f2e15d 43714d92 031db66c 7f5d48cd 17ecd74c
        39b17be2 bf9677be d0a0f02d
        6b24aa14 ba827910 9b166847 8154a2fa 919e0a2a
        53a6e79e 7d2933d8 05fc023f
        bdc76eed aa306c5f 52ed3565 4b0ec8a7 12105637
        af11fa21 0e99fffa 8c658e6d
      public exponent:
        010001
      prime p:
        e768033e 21646824 7bd031a0 a2d9876d 79818f8f
        2d7a952e 559fd786 2993bd04
        7e4fdb56 f175d04b 003ae026 f6ab9e0b 2af4a8d7
        ffbe01eb 9b81c75f 0273e12b
      prime q:
        c53d78ab e6ab3e29 fd98d0a4 3e58ee48 45a366ac
        e94dbd60 ea24ffed 0c67c5fd
        3628ea74 88d1d1ad 58d7f067 20c1e3b3 db52adf3
        c421d88c 4c4127db d03592c7
      prime exponent p:
        e09942b4 76029755 f9da3ba0 d70edcf4 337fbdcf
        d0eb6e89 f74f5a07 7ca94947
        6835a805 3dfd047b 17310dc8 a39834a0 504400f1
        0ce6e5c4 413df83d 4e0b1cdb
      prime exponent q:
        829b8afd a1984168 c2d1df4e f32e2653 5b31b17a
        cc5ebb09 a2e26f4a 040def90
        15be104a ac92ebda 72db4308 b72b4ce1 bb58cb71
        80adbcdc 625e3ecb 92daf6df
      crt coefficient:
        4d8190c5 7730b729 00a8f1b4 ae526300 b22d3e7d
        d64df98a c1b19889 5240141b
        0e618ff4 be597979 95195c51 0866c142 30b37a86
        9f3ef519 a3ae6469 14075097

자바 프로그래밍이 처음이라면 위에서 적절하게 오버로딩된 toString() 메소드의 출력값을 주목할 필요가 있다. "SunJSSE RSA public key:"으로 시작하는 텍스트가 RSAPublicKey 클래스 내의 toString() 메소드를 호출한 결과값이다. 이는 e라고 불리는 공개 지수(public exponent)와 모듈러스(modulus) N으로 구성되어 있다. "SunJSSE RSA private key:"로 시작하는 텍스트는 RSAPrivateKey 클래스 내의 동일한 메소드를 호출한 결과이다. 이는 비밀 지수 d, 모듈러스 N, 공개 지수 e 뿐만 아니라 생성되는 소인수들에 대한 정보도 포함하고 있다. 만약 데이터를 암호화하고 있는 중이라면, 공개 키 값을 전송할 때 주의해야 한다. 하지만, 이 값들이 전송을 인증하는데 사용되는 중이라면, 다른 사람들이 파일을 조회 혹은 검증할 수 있도록 이를 공개로 해 놓아야 한다.

코드를 재실행하고 스트링 DSA 를 입력하면 공개 키와 비밀 키 모두에서 p, q 와g의 값을 찾을 수가 있다. y 값은 공개 키에서, x값은 비밀 키에서 제공된다. 하지만 알고리즘이 다르기 때문에 이러한 정보는 다른 방법으로 계산되고 공유되어야 한다.

그렇다면 암호화에서 이 키 쌍을 어떻게 사용할 것인가? RSA의 경우를 먼저 살펴보면, 암호화하고 싶은 텍스트를 정하고 그것을 모듈러스보다 작은 수 m으로 바꾼다. 이에 관해서는 후에 더 언급하도록 하겠다. 여기에서 크기가 큰 소인수를 선택하는 이유를 알 수 있는데, 이는 소인수의 곱이 암호화 될 수 있는 것들의 사이즈를 결정하기 때문이다. 예를 들면 m=2라고 가정하자. 그러면 사용자는 c=m^e (mod N)를 계산해서 암호화하기 시작한다. 바꾸어 말하자면, 암호화하는 수를 공개 지수의 거듭제곱까지 증가시키고 이를 모듈러스로 나눈 나머지를 구한다. 이 예에서 2^43 는 341의 배수보다 8이 더 크기 때문에 c = 8이라는 암호화된 메시지를 전송해야 한다.

복호화(decryption)는 비밀 키를 이용해서 프로세스를 반복함으로써 이뤄진다. c^d(mod N)를 이용하자. 예를 통해 살펴보면, 먼저 8^7 을 계산하고 이를 341으로 나눈다. 나머지를 구해보면 2라는 메시지를 받게 된다. 이것은 우연히 나온 값이 아니다. 이는 m^(e d) = m (mod N)를 나타내는 Fermat의 정리 애플리케이션을 따른 것이다. 보안을 위해서 각각의 파티는 다른 파티의 공개 키를 이용해서 암호화하게 된다.

RSA 알고리즘에 대한 정보는 RSA, DSA 알고리즘에 대한 정보는 DSA를 참고하기 바란다.

from http://kr.sun.com/developers/techtips/c2004_01_16.htm

2007/05/24 01:56 2007/05/24 01:56
Trackback Address:이 글에는 트랙백을 보낼 수 없습니다

JavaTM Cryptography Extension (JCE) Reference Guide


JavaTM Cryptography Extension (JCE)

Reference Guide

for the JavaTM 2 Platform Standard Edition Development Kit (JDK) 5.0



Introduction


What's New in JCE in the JDK 5.0


Cryptographic Concepts

Encryption and Decryption

Password-Based Encryption

Cipher

Key Agreement

Message Authentication Code


Core Classes

The Cipher Class

The Cipher Stream Classes

The CipherInputStream Class

The CipherOutputStream Class

The KeyGenerator Class

The SecretKeyFactory Class

The SealedObject Class

The KeyAgreement Class

The Mac Class


How to Make Applications "Exempt" from Cryptographic Restrictions


Installing JCE Providers for the JDK 5.0


JCE Keystore


Code Examples

Using Encryption

Using Password-Based Encryption

Using Key Agreement



Appendix A: Standard Names


Appendix B: SunJCE Default Keysizes


Appendix C: SunJCE Keysize Restrictions


Appendix D: Jurisdiction Policy File Format


Appendix E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files


Appendix F: Sample Programs

Diffie-Hellman Key Exchange between 2 Parties

Diffie-Hellman Key Exchange between 3 Parties

Blowfish Example

HMAC-MD5 Example

Introduction

This document is intended as a companion to the JavaTM Cryptography Architecture (JCA) API Specification & Reference. References to chapters not present in this document are to chapters in the JCA Specification.

The JavaTM Cryptography Extension (JCE) provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has been integrated into the Java 2 SDK since the 1.4 release.

JCE is based on the same design principles found elsewhere in the JCA: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture. Providers signed by a trusted entity can be plugged into the JCE framework, and new algorithms can be added seamlessly.

The JCE API covers:

  • Symmetric bulk encryption, such as DES, RC2, and IDEA
  • Symmetric stream encryption, such as RC4
  • Asymmetric encryption, such as RSA
  • Password-based encryption (PBE)
  • Key Agreement
  • Message Authentication Codes (MAC)

The JDK 5.0 release comes standard with a JCE provider named "SunJCE", which comes pre-installed and registered and which supplies the following cryptographic services:

  • An implementation of the DES (FIPS PUB 46-1), Triple DES, and Blowfish encryption algorithms in the Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB), and Propagating Cipher Block Chaining (PCBC) modes. (Note: Throughout this document, the terms "Triple DES" and "DES-EDE" will be used interchangeably.)
  • Key generators for generating keys suitable for the DES, Triple DES, Blowfish, HMAC-MD5, and HMAC-SHA1 algorithms.
  • An implementation of the MD5 with DES-CBC password-based encryption (PBE) algorithm defined in PKCS #5.
  • "Secret-key factories" providing bi-directional conversions between opaque DES, Triple DES and PBE key objects and transparent representations of their underlying key material.
  • An implementation of the Diffie-Hellman key agreement algorithm between two or more parties.
  • A Diffie-Hellman key pair generator for generating a pair of public and private values suitable for the Diffie-Hellman algorithm.
  • A Diffie-Hellman algorithm parameter generator.
  • A Diffie-Hellman "key factory" providing bi-directional conversions between opaque Diffie-Hellman key objects and transparent representations of their underlying key material.
  • Algorithm parameter managers for Diffie-Hellman, DES, Triple DES, Blowfish, and PBE parameters.
  • An implementation of the HMAC-MD5 and HMAC-SHA1 keyed-hashing algorithms defined in RFC 2104.
  • An implementation of the padding scheme described in PKCS #5.
  • A keystore implementation for the proprietary keystore type named "JCEKS".

A Note on Terminology

The JCE within the JDK 5.0 includes two software components:

  • the framework that defines and supports cryptographic services that providers can supply implementations for. This framework includes everything in the javax.crypto package.
  • a provider named "SunJCE"
Throughout this document, the term "JCE" by itself refers to the JCE framework in the JDK 5.0. Whenever the JCE provider supplied with the JDK 5.0 is mentioned, it will be referred to explicitly as the "SunJCE" provider.

What's New in JCE in the JDK 5.0

Here are the differences in JCE between v1.4 and 5.0:

Support for PKCS #11 Based Crypto Provider

In JDK 5.0, a JCA/JCE provider, SunPKCS11 that acts as a generic gateway to the native PKCS#11 API has been implemented. PKCS#11 is the de-facto standard for crypto accelerators and also widely used to access cryptographic smartcards. The administrator/user can configure this provider to talk any PKCS#11 v2.x compliant token.

Here's an example of the configuration file format.

Integration with Solaris Cryptographic Framework

On Solaris 10, the default Java security provider configuration has been changed in JDK 5.0 to include an instance of the SunPKCS11 provider that uses the Solaris Cryptographic Framework. It is the provider with the highest precedence thereby allowing all existing applications to take advantage of the improved performance on Solaris 10. There is no change in behavior on Solaris 8 and Solaris 9 systems.

As a result of this change, many cryptographic operations will execute several times as fast as before on all Solaris 10 systems. On systems with cryptographic hardware acceleration, the performance improvements may be two orders of magnitude.

Support for ECC Algorithm

Prior to JDK 5.0 the JCA/JCE framework did not include support classes for ECC-related crypto algorithms. Users who wanted to use ECC had to depend on a 3rd party library that implemented ECC. However, this did not integrate well with existing JCA/JCE framework.

Starting in JDK 5.0, full support for ECC classes to facilitate providers that support ECC have been included.

The following interfaces have been added:

The following classes have been added:

Added ByteBuffer API Support

Methods that take ByteBuffer arguments have been added to the JCE API and SPI classes that are used to process bulk data. Providers can override the engine* methods if they can process ByteBuffers more efficiently than byte[].

The following JCE methods have been added to support ByteBuffers:

    javax.crypto.Mac.update(ByteBuffer input)
javax.crypto.MacSpi.engineUpdate(ByteBuffer input)
javax.crypto.Cipher.update(ByteBuffer input, ByteBuffer output)
javax.crypto.Cipher.doFinal(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineUpdate(ByteBuffer input, ByteBuffer output)
javax.crypto.CipherSpi.engineDoFinal(ByteBuffer input, ByteBuffer output)
The following JCA methods have been added to support ByteBuffers:
    java.security.MessageDigest.update(ByteBuffer input)
java.security.Signature.update(ByteBuffer data)
java.security.SignatureSpi.engineUpdate(ByteBuffer data)
java.security.MessageDigestSpi.engineUpdate(ByteBuffer input)

Support for RC2ParameterSpec

The RC2 algorithm implementation has been enhanced in JDK 5.0 to support effective key size that is distinct from the length of the input key.

Full support for XML Encryption RSA-OAEP Algorithm

Prior to JDK 5.0, JCE did not define any parameter class for specifying the non-default values used in OAEP and PSS padding as defined in PKCS#1 v2.1 and the RSA-OAEP Key Transport algorithm in the W3C Recommendation for XML Encryption. Therefore, there was no generic way for applications to specify non-default values used in OAEP and PSS padding.

In JDK 5.0, new parameter classes have been added to fully support OAEP padding and the existing PSS parameter class was enhanced with APIs to fully support RSA PSS signature implementations. Also, SunJCE provider has been enhanced to accept OAEPParameterSpec when OAEPPadding is used.

The following classes have been added:

The following methods and fields have been added to java.security.spec.PSSParameterSpec:

    public static final PSSParameterSpec DEFAULT
public PSSParameterSpec(String mdName, String mgfName,
AlgorithmParameterSpec mgfSpec,
int saltLen, int trailerField)
public String getDigestAlgorithm()
public String getMGFAlgorithm()
public AlgorithmParameterSpec getMGFParameters()
public int getTrailerField()

Simplified Retrieval of PKCS8EncodedKeySpec from javax.crypto.EncryptedPrivateKeyInfo

In JDK 5.0, javax.crypto.EncryptedPrivateKeyInfo only has one method, getKeySpec(Cipher) for retrieving the PKCS8EncodedKeySpec from the encrypted data. This limitation requires users to specify a cipher which is initialized with the decryption key and parameters. When users only have the decryption key, they would have to first retrieve the parameters out of this EncryptedPrivateKeyInfo object, get hold of matching Cipher implementation, initialize it, and then call the getKeySpec(Cipher) method.

To make EncyptedPrivateKeyInfo easier to use and to make its API consistent with javax.crypto.SealedObject, the following methods have been added to javax.crypto.EncryptedPrivateKeyInfo:

    getKeySpec(Key decryptKey)
getKeySpec(Key decryptKey, String provider)

Ability to Dynamically Determine Maximum Allowable Key Length

In 1.4.2, the crypto jurisdiction policy files bundled in J2SE limits the maximum key length (and parameter value for some crypto algorithms) that can be used for encryption/decryption. Users who desire unlimited version of crypto jurisdiction files must download them separately.

Also, an exception is thrown when the Cipher instance is initialized with keys (or parameters for certain crypto algorithms) exceeds the maximum values allowed by the crypto jurisdiction files.

In JDK 5.0, the Cipher class has been updated to provide the maximum values for key length and parameters configured in the jurisdiction policy files, so that applications can use a shorter key length when the default (limited strength) jurisdiction policy files are installed.

The following methods have been added to javax.crypto.Cipher:

    public static final int getMaxAllowedKeyLength(String transformation)
throws NoSuchAlgorithmException

public static final AlgorithmParameterSpec
getMaxAllowedParameterSpec(String transformation)
throws NoSuchAlgorithmException;

Support for HmacSHA256, HmacSHA384, HmacSHA512

Support for HmacSHA-256, HmacSHA-384, and HmacSHA-512 algorithms have been added to JDK 5.0.

Support for RSA Encryption to SunJCE Provider

A publicly accessible RSA encryption implementation has been added to the SunJCE provider.

Support for RC2 and ARCFOUR Ciphers to SunJCE Provider

The SunJCE provider now implements the RC2 (RFC 2268) and ARCFOUR (an RC4TM-compatible algorithm) ciphers.

Support for "PBEWithSHA1AndDESede" and "PBEWithSHA1AndRC2_40" Ciphers

Added support for PBEWithSHA1AndDESede and PBEWithSHA1AndRC2_40 ciphers in SunJCE provider.

Support for XML Encryption Padding Algorithm in JCE Block Encryption Ciphers

W3C XML Encryption defines a new padding algorithm, "ISO10126Padding," for block ciphers. See 5.2 Block Encryption Algorithms for more information.

To allow Sun's provider to be used by XML Encryption implementations and JSR 106 providers, we have added support for this padding in JDK 5.0.

Cryptographic Concepts

This section provides a high-level description of the concepts implemented by the API, and the exact meaning of the technical terms used in the API specification.

Encryption and Decryption

Encryption is the process of taking data (called cleartext) and a short string (a key), and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a short key string, and producing cleartext.

Password-Based Encryption

Password-Based Encryption (PBE) derives an encryption key from a password. In order to make the task of getting from password to key very time-consuming for an attacker, most PBE implementations will mix in a random number, known as a salt, to create the key.

Cipher

Encryption and decryption are done using a cipher. A cipher is an object capable of carrying out encryption and decryption according to an encryption scheme (algorithm).

Key Agreement

Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.

Message Authentication Code

A Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, based on a secret key. Typically, message authentication codes are used between two parties that share a secret key in order to validate information transmitted between these parties.

A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.


Core Classes

  • The Cipher Class

    The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption. It forms the core of the JCE framework.

    Creating a Cipher Object

    Like other engine classes in the API, Cipher objects are created using the getInstance factory methods of the Cipher class. A factory method is a static method that returns an instance of a class, in this case, an instance of Cipher, which implements a requested transformation.

    To create a Cipher object, you must specify the transformation name. You may also specify which provider you want to supply the implementation of the requested transformation:

        
    public static Cipher getInstance(String transformation);

    public static Cipher getInstance(String transformation,
    String provider);

    If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, if there is a preferred one.

    If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not.

    A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a mode and padding scheme.

    A transformation is of the form:

    For example, the following are valid transformations:

        "DES/CBC/PKCS5Padding"

    "DES"

    If no mode or padding is specified, provider-specific default values for the mode and padding scheme are used. For example, the SunJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES, DES-EDE and Blowfish ciphers. This means that in the case of the SunJCE provider,

        Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");

    and

        Cipher c1 = Cipher.getInstance("DES");

    are equivalent statements.

    When requesting a block cipher in stream cipher mode (e.g., DES in CFB or OFB mode), you may optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits.)

    Appendix A of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation.

    The objects returned by factory methods are uninitialized, and must be initialized before they become usable.

    Initializing a Cipher Object

    A Cipher object obtained via getInstance must be initialized for one of four modes, which are defined as final integer constants in the Cipher class. The modes can be referenced by their symbolic names, which are shown below along with a description of the purpose of each mode:

    • ENCRYPT_MODE
      Encryption of data.
    • DECRYPT_MODE
      Decryption of data.
    • WRAP_MODE
      Wrapping a Key into bytes so that the key can be securely transported.
    • UNWRAP_MODE
      Unwrapping of a previously wrapped key into a java.security.Key object.

    Each of the Cipher initialization methods takes a mode parameter (opmode), and initializes the Cipher object for that mode. Other parameters include the key (key) or certificate containing the key (certificate), algorithm parameters (params), and a source of randomness (random).

    To initialize a Cipher object, call one of the following init methods:

        public void init(int opmode, Key key);

    public void init(int opmode, Certificate certificate)

    public void init(int opmode, Key key,
    SecureRandom random);

    public void init(int opmode, Certificate certificate,
    SecureRandom random)

    public void init(int opmode, Key key,
    AlgorithmParameterSpec params);

    public void init(int opmode, Key key,
    AlgorithmParameterSpec params,
    SecureRandom random);

    public void init(int opmode, Key key,
    AlgorithmParameters params)

    public void init(int opmode, Key key,
    AlgorithmParameters params,
    SecureRandom random)

    If a Cipher object that requires parameters (e.g., an initialization vector) is initialized for encryption, and no parameters are supplied to the init method, the underlying cipher implementation is supposed to supply the required parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters.

    However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the init method, an InvalidKeyException or InvalidAlgorithmParameterException exception will be raised, depending on the init method that has been used.

    See the section about Managing Algorithm Parameters for more details.

    The same parameters that were used for encryption must be used for decryption.

    Note that when a Cipher object is initialized, it loses all previously-acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state acquired while in decryption mode.

    Encrypting and Decrypting Data

    Data can be encrypted or decrypted in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

    To encrypt or decrypt data in a single step, call one of the doFinal methods:

        public byte[] doFinal(byte[] input);

    public byte[] doFinal(byte[] input, int inputOffset,
    int inputLen);

    public int doFinal(byte[] input, int inputOffset,
    int inputLen, byte[] output);

    public int doFinal(byte[] input, int inputOffset,
    int inputLen, byte[] output, int outputOffset)

    To encrypt or decrypt data in multiple steps, call one of the update methods:

        public byte[] update(byte[] input);

    public byte[] update(byte[] input, int inputOffset, int inputLen);

    public int update(byte[] input, int inputOffset, int inputLen,
    byte[] output);

    public int update(byte[] input, int inputOffset, int inputLen,
    byte[] output, int outputOffset)

    A multiple-part operation must be terminated by one of the above doFinal methods (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

        public byte[] doFinal();

    public int doFinal(byte[] output, int outputOffset);

    All the doFinal methods take care of any necessary padding (or unpadding), if padding (or unpadding) has been requested as part of the specified transformation.

    A call to doFinal resets the Cipher object to the state it was in when initialized via a call to init. That is, the Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call to init) more data.

    Wrapping and Unwrapping Keys

    Wrapping a key enables secure transfer of the key from one place to another.

    The wrap/unwrap API makes it more convenient to write code since it works with key objects directly. These methods also enable the possibility of secure transfer of hardware-based keys.

    To wrap a Key, first initialize the Cipher object for WRAP_MODE, and then call the following:

        public final byte[] wrap(Key key);

    If you are supplying the wrapped key bytes (the result of calling wrap) to someone else who will unwrap them, be sure to also send additional information the recipient will need in order to do the unwrap:

    1. the name of the key algorithm, and
    2. the type of the wrapped key (one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY).

    The key algorithm name can be determined by calling the getAlgorithm method from the Key interface:

        public String getAlgorithm();

    To unwrap the bytes returned by a previous call to wrap, first initialize a Cipher object for UNWRAP_MODE, then call the following:

        public final Key unwrap(byte[] wrappedKey,
    String wrappedKeyAlgorithm,
    int wrappedKeyType));

    Here, wrappedKey is the bytes returned from the previous call to wrap, wrappedKeyAlgorithm is the algorithm associated with the wrapped key, and wrappedKeyType is the type of the wrapped key. This must be one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY.

    Managing Algorithm Parameters

    The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the init method by the application or generated by the underlying implementation itself, can be retrieved from the Cipher object by calling its getParameters method, which returns the parameters as a java.security.AlgorithmParameters object (or null if no parameters are being used). If the parameter is an initialization vector (IV), it can also be retrieved by calling the getIV method.

    In the following example, a Cipher object implementing password-based encryption is initialized with just a key and no parameters. However, the selected algorithm for password-based encryption requires two parameters - a salt and an iteration count. Those will be generated by the underlying algorithm implementation itself. The application can retrieve the generated parameters from the Cipher object as follows:

        import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for encryption, without supplying
    // any parameters. Here, "myKey" is assumed to refer
    // to an already-generated key.
    c.init(Cipher.ENCRYPT_MODE, myKey);

    // encrypt some data and store away ciphertext
    // for later decryption
    byte[] cipherText = c.doFinal("This is just an example".getBytes());

    // retrieve parameters generated by underlying cipher
    // implementation
    AlgorithmParameters algParams = c.getParameters();

    // get parameter encoding and store it away
    byte[] encodedAlgParams = algParams.getEncoded();

    The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption, as follows:

        import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get parameter object for password-based encryption
    AlgorithmParameters algParams;
    algParams =
    AlgorithmParameters.getInstance("PBEWithMD5AndDES");

    // initialize with parameter encoding from above
    algParams.init(encodedAlgParams);

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for decryption, using one of the
    // init() methods that takes an AlgorithmParameters
    // object, and pass it the algParams object from above
    c.init(Cipher.DECRYPT_MODE, myKey, algParams);

    If you did not specify any parameters when you initialized a Cipher object, and you are not sure whether or not the underlying implementation uses any parameters, you can find out by simply calling the getParameters method of your Cipher object and checking the value returned. A return value of null indicates that no parameters were used.

    The following cipher algorithms implemented by the SunJCE provider use parameters:

    • DES, DES-EDE, and Blowfish, when used in feedback (i.e., CBC, CFB, OFB, or PCBC) mode, use an initialization vector (IV). The javax.crypto.spec.IvParameterSpec class can be used to initialize a Cipher object with a given IV.
    • PBEWithMD5AndDES uses a set of parameters, comprising a salt and an iteration count. The javax.crypto.spec.PBEParameterSpec class can be used to initialize a Cipher object implementing PBEWithMD5AndDES with a given salt and iteration count.

    Note that you do not have to worry about storing or transferring any algorithm parameters for use by the decryption operation if you use the SealedObject class. This class attaches the parameters used for sealing (encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).

    Cipher Output Considerations

    Some of the update and doFinal methods of Cipher allow the caller to specify the output buffer into which to encrypt or decrypt the data. In these cases, it is important to pass a buffer that is large enough to hold the result of the encryption or decryption operation.

    The following method in Cipher can be used to determine how big the output buffer should be:

        public int getOutputSize(int inputLen)
  • The Cipher Stream Classes

    JCE introduces the concept of secure streams, which combine an InputStream or OutputStream with a Cipher object. Secure streams are provided by the CipherInputStream and CipherOutputStream classes.

    • The CipherInputStream Class

      This class is a FilterInputStream that encrypts or decrypts the data passing through it. It is composed of an InputStream, or one of its subclasses, and a Cipher. CipherInputStream represents a secure input stream into which a Cipher object has been interposed. The read methods of CipherInputStream return data that are read from the underlying InputStream but have additionally been processed by the embedded Cipher object. The Cipher object must be fully initialized before being used by a CipherInputStream.

      For example, if the embedded Cipher has been initialized for decryption, the CipherInputStream will attempt to decrypt the data it reads from the underlying InputStream before returning them to the application.

      This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.FilterInputStream and java.io.InputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that the data are additonally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, the skip(long) method skips only data that has been processed by the Cipher.

      It is crucial for a programmer using this class not to use methods that are not defined or overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherInputStream.

      As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherInputStream containing that cipher and a FileInputStream in order to encrypt input stream data:

          FileInputStream fis;
      FileOutputStream fos;
      CipherInputStream cis;

      fis = new FileInputStream("/tmp/a.txt");
      cis = new CipherInputStream(fis, cipher1);
      fos = new FileOutputStream("/tmp/b.txt");
      byte[] b = new byte[8];
      int i = cis.read(b);
      while (i != -1) {
      fos.write(b, 0, i);
      i = cis.read(b);
      }

      The above program reads and encrypts the content from the file /tmp/a.txt and then stores the result (the encrypted bytes) in /tmp/b.txt.

      The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that cipher1 and cipher2 have been initialized for encryption and decryption (with corresponding keys), respectively.

          FileInputStream fis;
      FileOutputStream fos;
      CipherInputStream cis1, cis2;

      fis = new FileInputStream("/tmp/a.txt");
      cis1 = new CipherInputStream(fis, cipher1);
      cis2 = new CipherInputStream(cis1, cipher2);
      fos = new FileOutputStream("/tmp/b.txt");
      byte[] b = new byte[8];
      int i = cis2.read(b);
      while (i != -1) {
      fos.write(b, 0, i);
      i = cis2.read(b);
      }

      The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back when it is read from /tmp/a.txt. Of course since this program simply encrypts text and decrypts it back right away, it's actually not very useful except as a simple way of illustrating chaining of CipherInputStreams.

    • The CipherOutputStream Class

      This class is a FilterOutputStream that encrypts or decrypts the data passing through it. It is composed of an OutputStream, or one of its subclasses, and a Cipher. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. The write methods of CipherOutputStream first process the data with the embedded Cipher object before writing them out to the underlying OutputStream. The Cipher object must be fully initialized before being used by a CipherOutputStream.

      For example, if the embedded Cipher has been initialized for encryption, the CipherOutputStream will encrypt its data, before writing them out to the underlying output stream.

      This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.OutputStream and java.io.FilterOutputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that all data are additionally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes.

      It is crucial for a programmer using this class not to use methods that are not defined or overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherOutputStream.

      As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherOutputStream containing that cipher and a FileOutputStream in order to encrypt data to be written to an output stream:

          FileInputStream fis;
      FileOutputStream fos;
      CipherOutputStream cos;

      fis = new FileInputStream("/tmp/a.txt");
      fos = new FileOutputStream("/tmp/b.txt");
      cos = new CipherOutputStream(fos, cipher1);
      byte[] b = new byte[8];
      int i = fis.read(b);
      while (i != -1) {
      cos.write(b, 0, i);
      i = fis.read(b);
      }
      cos.flush();

      The above program reads the content from the file /tmp/a.txt, then encrypts and stores the result (the encrypted bytes) in /tmp/b.txt.

      The following example demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that cipher1 and cipher2 have been initialized for decryption and encryption (with corresponding keys), respectively:

          FileInputStream fis;
      FileOutputStream fos;
      CipherOutputStream cos1, cos2;

      fis = new FileInputStream("/tmp/a.txt");
      fos = new FileOutputStream("/tmp/b.txt");
      cos1 = new CipherOutputStream(fos, cipher1);
      cos2 = new CipherOutputStream(cos1, cipher2);
      byte[] b = new byte[8];
      int i = fis.read(b);
      while (i != -1) {
      cos2.write(b, 0, i);
      i = fis.read(b);
      }
      cos2.flush();

      The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back before it is written to /tmp/b.txt.

      There is one important difference between the flush and close methods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:

      flush flushes the underlying OutputStream by forcing any buffered output bytes that have already been processed by the encapsulated Cipher object to be written out. Any bytes buffered by the encapsulated Cipher object and waiting to be processed by it will not be written out.

      close closes the underlying OutputStream and releases any system resources associated with it. It invokes the doFinal method of the encapsulated Cipher object, causing any bytes buffered by it to be processed and written out to the underlying stream by calling its flush method.

  • The KeyGenerator Class

    A key generator is used to generate secret keys for symmetric algorithms.

    Creating a Key Generator

    Like other engine classes in the API, KeyGenerator objects are created using the getInstance factory methods of the KeyGenerator class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyGenerator which provides an implementation of the requested key generator.

    getInstance takes as its argument the name of a symmetric algorithm for which a secret key is to be generated. Optionally, a package provider name may be specified:

        public static KeyGenerator getInstance(String algorithm);

    public static KeyGenerator getInstance(String algorithm,
    String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested key generator available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key generator in the package requested, and throw an exception if there is not.

    Initializing a KeyGenerator Object

    A key generator for a particular symmetric-key algorithm creates a symmetric key that can be used with that algorithm. It also associates algorithm-specific parameters (if any) with the generated key.

    There are two ways to generate a key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object:

    • Algorithm-Independent Initialization

      All key generators share the concepts of a keysize and a source of randomness. There is an init method that takes these two universally shared types of arguments. There is also one that takes just a keysize argument, and uses a system-provided source of randomness, and one that takes just a source of randomness:

          public void init(SecureRandom random);

      public void init(int keysize);

      public void init(int keysize, SecureRandom random);

      Since no other parameters are specified when you call the above algorithm-independent init methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with the generated key.

    • Algorithm-Specific Initialization

      For situations where a set of algorithm-specific parameters already exists, there are two init methods that have an AlgorithmParameterSpec argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:

          public void init(AlgorithmParameterSpec params);

      public void init(AlgorithmParameterSpec params,
      SecureRandom random);

    In case the client does not explicitly initialize the KeyGenerator (via a call to an init method), each provider must supply (and document) a default initialization.

    Creating a Key

    The following method generates a secret key:
        public SecretKey generateKey();
  • The SecretKeyFactory Class

    This class represents a factory for secret keys.

    Key factories are used to convert keys (opaque cryptographic keys of type java.security.Key) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.

    A javax.crypto.SecretKeyFactory object operates only on secret (symmetric) keys, whereas a java.security.KeyFactory object processes the public and private key components of a key pair.

    Objects of type java.security.Key, of which java.security.PublicKey, java.security.PrivateKey, and javax.crypto.SecretKey are subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and may be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.

    For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value y, the prime modulus p, and the base g, and you feed the same specification to Diffie-Hellman key factories from different providers, the resulting PublicKey objects will most likely have different underlying implementations.

    A provider should document the key specifications supported by its secret key factory. For example, the SecretKeyFactory for DES keys supplied by the "SunJCE" provider supports DESKeySpec as a transparent representation of DES keys, the SecretKeyFactory for DES-EDE keys supports DESedeKeySpec as a transparent representation of DES-EDE keys, and the SecretKeyFactory for PBE supports PBEKeySpec as a transparent representation of the underlying password.

    The following is an example of how to use a SecretKeyFactory to convert secret key data into a SecretKey object, which can be used for a subsequent Cipher operation:

        // Note the following bytes are not realistic secret key data 
    // bytes but are simply supplied as an illustration of using data
    // bytes (key material) you already have to build a DESKeySpec.
    byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03,
    (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };
    DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    In this case, the underlying implementation of secretKey is based on the provider of keyFactory.

    An alternative, provider-independent way of creating a functionally equivalent SecretKey object from the same key material is to use the javax.crypto.spec.SecretKeySpec class, which implements the javax.crypto.SecretKey interface:

        byte[] desKeyData = { (byte)0x01, (byte)0x02, ...};
    SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");
  • The SealedObject Class

    This class enables a programmer to create an object and protect its confidentiality with a cryptographic algorithm.

    Given any object that implements the java.io.Serializable interface, one can create a SealedObject that encapsulates the original object, in serialized format (i.e., a "deep copy"), and seals (encrypts) its serialized contents, using a cryptographic algorithm such as DES, to protect its confidentiality. The encrypted content can later be decrypted (with the corresponding algorithm using the correct decryption key) and de-serialized, yielding the original object.

    A typical usage is illustrated in the following code segment: In order to seal an object, you create a SealedObject from the object to be sealed and a fully initialized Cipher object that will encrypt the serialized object contents. In this example, the String "This is a secret" is sealed using the DES algorithm. Note that any algorithm parameters that may be used in the sealing operation are stored inside of SealedObject:

        // create Cipher object
    // Note: sKey is assumed to refer to an already-generated
    // secret DES key.
    Cipher c = Cipher.getInstance("DES");
    c.init(Cipher.ENCRYPT_MODE, sKey);

    // do the sealing
    SealedObject so = new SealedObject("This is a secret", c);

    The original object that was sealed can be recovered in two different ways:

    • by using a Cipher object that has been initialized with the exact same algorithm, key, padding scheme, etc., that were used to seal the object:
          c.init(Cipher.DECRYPT_MODE, sKey);
      try {
      String s = (String)so.getObject(c);
      } catch (Exception e) {
      // do something
      };

      This approach has the advantage that the party who unseals the sealed object does not require knowledge of the decryption key. For example, after one party has initialized the cipher object with the required decryption key, it could hand over the cipher object to another party who then unseals the sealed object.

    • by using the appropriate decryption key (since DES is a symmetric encryption algorithm, we use the same key for sealing and unsealing):
          try {
      String s = (String)so.getObject(sKey);
      } catch (Exception e) {
      // do something
      };

      In this approach, the getObject method creates a cipher object for the appropriate decryption algorithm and initializes it with the given decryption key and the algorithm parameters (if any) that were stored in the sealed object. This approach has the advantage that the party who unseals the object does not need to keep track of the parameters (e.g., the IV) that were used to seal the object.

  • The KeyAgreement Class

    The KeyAgreement class provides the functionality of a key agreement protocol. The keys involved in establishing a shared secret are created by one of the key generators (KeyPairGenerator or KeyGenerator), a KeyFactory, or as a result from an intermediate phase of the key agreement protocol.

    Creating a KeyAgreement Object

    Each party involved in the key agreement has to create a KeyAgreement object. Like other engine classes in the API, KeyAgreement objects are created using the getInstance factory methods of the KeyAgreement class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyAgreement which provides the requested key agreement algorithm.

    getInstance takes as its argument the name of a key agreement algorithm. Optionally, a package provider name may be specified:

        public static KeyAgreement getInstance(String algorithm);

    public static KeyAgreement getInstance(String algorithm,
    String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested key agreement available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key agreement in the package requested, and throw an exception if there is not.

    Initializing a KeyAgreement Object

    You initialize a KeyAgreement object with your private information. In the case of Diffie-Hellman, you initialize it with your Diffie-Hellman private key. Additional initialization information may contain a source of randomness and/or a set of algorithm parameters. Note that if the requested key agreement algorithm requires the specification of algorithm parameters, and only a key, but no parameters are provided to initialize the KeyAgreement object, the key must contain the required algorithm parameters. (For example, the Diffie-Hellman algorithm uses a prime modulus p and a base generator g as its parameters.)

    To initialize a KeyAgreement object, call one of its init methods:

        public void init(Key key);

    public void init(Key key, SecureRandom random);

    public void init(Key key, AlgorithmParameterSpec params);

    public void init(Key key, AlgorithmParameterSpec params,
    SecureRandom random);

    Executing a KeyAgreement Phase

    Every key agreement protocol consists of a number of phases that need to be executed by each party involved in the key agreement.

    To execute the next phase in the key agreement, call the doPhase method:

        public Key doPhase(Key key, boolean lastPhase);

    The key parameter contains the key to be processed by that phase. In most cases, this is the public key of one of the other parties involved in the key agreement, or an intermediate key that was generated by a previous phase. doPhase may return an intermediate key that you may have to send to the other parties of this key agreement, so they can process it in a subsequent phase.

    The lastPhase parameter specifies whether or not the phase to be executed is the last one in the key agreeement: A value of FALSE indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value of TRUE indicates that this is the last phase of the key agreement and the key agreement is completed, i.e., generateSecret can be called next.

    In the example of Diffie-Hellman between two parties (see Appendix F), you call doPhase once, with lastPhase set to TRUE. In the example of Diffie-Hellman between three parties, you call doPhase twice: the first time with lastPhase set to FALSE, the 2nd time with lastPhase set to TRUE.

    Generating the Shared Secret

    After each party has executed all the required key agreement phases, it can compute the shared secret by calling one of the generateSecret methods:

        public byte[] generateSecret();

    public int generateSecret(byte[] sharedSecret, int offset);

    public SecretKey generateSecret(String algorithm);
  • The Mac Class

    The Mac class provides the functionality of a Message Authentication Code (MAC). Please refer to the code example in Appendix F.

    Creating a Mac Object

    Like other engine classes in the API, Mac objects are created using the getInstance factory methods of the Mac class. A factory method is a static method that returns an instance of a class, in this case, an instance of Mac which provides the requested MAC algorithm.

    getInstance takes as its argument the name of a MAC algorithm. Optionally, a package provider name may be specified:

        public static Mac getInstance(String algorithm);

    public static Mac getInstance(String algorithm,
    String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested MAC algorithm available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested MAC algorithm in the package requested, and throw an exception if there is not.

    Initializing a Mac Object

    A Mac object is always initialized with a (secret) key and may optionally be initialized with a set of parameters, depending on the underlying MAC algorithm.

    To initialize a Mac object, call one of its init methods:

        public void init(Key key);

    public void init(Key key, AlgorithmParameterSpec params);

    You can initialize your Mac object with any (secret-)key object that implements the javax.crypto.SecretKey interface. This could be an object returned by javax.crypto.KeyGenerator.generateKey(), or one that is the result of a key agreement protocol, as returned by javax.crypto.KeyAgreement.generateSecret(), or an instance of javax.crypto.spec.SecretKeySpec.

    With some MAC algorithms, the (secret-)key algorithm associated with the (secret-)key object used to initialize the Mac object does not matter (this is the case with the HMAC-MD5 and HMAC-SHA1 implementations of the SunJCE provider). With others, however, the (secret-)key algorithm does matter, and an InvalidKeyException is thrown if a (secret-)key object with an inappropriate (secret-)key algorithm is used.

    Computing a MAC

    A MAC can be computed in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

    To compute the MAC of some data in a single step, call the following doFinal method:

        public byte[] doFinal(byte[] input);

    To compute the MAC of some data in multiple steps, call one of the update methods:

        public void update(byte input);

    public void update(byte[] input);

    public void update(byte[] input, int inputOffset, int inputLen);

    A multiple-part operation must be terminated by the above doFinal method (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

        public byte[] doFinal();

    public void doFinal(byte[] output, int outOffset);

How to Make Applications "Exempt" from Cryptographic Restrictions

[Note 1: This section should be ignored by most application developers. It is only for people whose applications may be exported to those few countries whose governments mandate cryptographic restrictions, if it desired that such applications have fewer cryptographic restrictions than those mandated. If you want to skip this section, you can go on to Installing JCE Providers for JDK 5.0.]
[Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

The JCE framework within JDK 5.0 includes an ability to enforce restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different jurisdiction contexts (locations). Any such restrictions are specified in "jurisdiction policy files".

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK 5.0 from Sun Microsystems specify that "strong" but limited cryptography may be used. An "unlimited strength" version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the "strong" version can be imported into those countries whose governments mandate restrictions. The JCE framework will enforce the restrictions specified in the installed jurisdiction policy files.

It is possible that the governments of some or all such countries may allow certain applications to become exempt from some or all cryptographic restrictions. For example, they may consider certain types of applications as "special" and thus exempt. Or they may exempt any application that utilizes an "exemption mechanism," such as key recovery. Applications deemed to be exempt could get access to stronger cryptography than that allowed for non-exempt applications in such countries.

In order for an application to be recognized as "exempt" at runtime, it must meet the following conditions:

  • It must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).
  • The JAR file containing the application and the permission policy file must have been signed using a code-signing certificate issued after the application was accepted as exempt.

Below are sample steps required in order to make an application exempt from some or all cryptographic restrictions. This is a basic outline that includes information about what is required by JCE in order to recognize and treat applications as being exempt. You will need to know the exemption requirements of the particular country or countries in which you would like your application to be able to be run but whose governments require cryptographic restrictions. You will also need to know the requirements of a JCE framework vendor that has a process in place for handling exempt applications. Consult such a vendor for further information. (Note: The SunJCE provider does not supply an implementation of the ExemptionMechanismSpi class.)

  • Step 1: Write and Compile Your Application Code
  • Step 2: Create a Permission Policy File Granting Appropriate Cryptographic Permissions
  • Step 3: Prepare for Testing
  • Step 3a: Apply for Government Approval From the Government Mandating Restrictions.
  • Step 3b: Get a Code-Signing Certificate
  • Step 3c: Bundle the Application and Permission Policy File into a JAR file
  • Step 3d: Sign the JAR file
  • Step 3e: Set Up Your Environment Like That of a User in a Restricted Country
  • Step 3f: (only for apps using exemption mechanisms) Install a Provider Implementing the Exemption Mechanism Specified in the Permission Policy File
  • Step 4: Test Your Application
  • Step 5: Apply for U.S. Government Export Approval If Required
  • Step 6: Deploy Your Application

Special Code Requirements for Applications that Use Exemption Mechanisms

When an application has a permission policy file associated with it (in the same JAR file) and that permission policy file specifies an exemption mechanism, then when the Cipher getInstance method is called to instantiate a Cipher, the JCE code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCE instantiates an ExemptionMechanism API object associated with the provider's implementation, and then associates the ExemptionMechanism object with the Cipher returned by getInstance.

After instantiating a Cipher, and prior to initializing it (via a call to the Cipher init method), your code must call the following Cipher method:

    public ExemptionMechanism getExemptionMechanism()

This call returns the ExemptionMechanism object associated with the Cipher. You must then initialize the exemption mechanism implementation by calling the following method on the returned ExemptionMechanism:

     public final void init(Key key)

The argument you supply should be the same as the argument of the same types that you will subsequently supply to a Cipher init method.

Once you have initialized the ExemptionMechanism, you can proceed as usual to initialize and use the Cipher.

Permission Policy Files

In order for an application to be recognized at runtime as being "exempt" from some or all cryptographic restrictions, it must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).

Note: The permission policy file bundled with an application must be named cryptoPerms.

The format of a permission entry in a permission policy file that accompanies an exempt application is the same as the format for a jurisdiction policy file downloaded with the JDK 5.0, which is:

permission <crypto permission class name>[ <alg_name>
[[, <exemption mechanism name>][, <maxKeySize>
[, <AlgorithmParameterSpec class name>,
<parameters for constructing an AlgorithmParameterSpec object>]]]];

See Appendix D for more information about the jurisdiction policy file format.

Permission Policy Files for Exempt Applications

Some applications may be allowed to be completely unrestricted. Thus, the permission policy file that accompanies such an application usually just needs to contain the following:

grant {
// There are no restrictions to any algorithms.
permission javax.crypto.CryptoAllPermission;
};

If an application just uses a single algorithm (or several specific algorithms), then the permission policy file could simply mention that algorithm (or algorithms) explicitly, rather than granting CryptoAllPermission. For example, if an application just uses the Blowfish algorithm, the permission policy file doesn't have to grant CryptoAllPermission to all algorithms. It could just specify that there is no cryptographic restriction if the Blowfish algorithm is used. In order to do this, the permission policy file would look like the following:

grant {
permission javax.crypto.CryptoPermission "Blowfish";
};

Permission Policy Files for Applications Exempt Due to Exemption Mechanisms

If an application is considered "exempt" if an exemption mechanism is enforced, then the permission policy file that accompanies the application must specify one or more exemption mechanisms. At runtime, the application will be considered exempt if any of those exemption mechanisms is enforced. Each exemption mechanism must be specified in a permission entry that looks like the following:

    // No algorithm restrictions if specified
// exemption mechanism is enforced.
permission javax.crypto.CryptoPermission *,
"<ExemptionMechanismName>";

where <ExemptionMechanismName> specifies the name of an exemption mechanism. The list of possible exemption mechanism names includes:

  • KeyRecovery
  • KeyEscrow
  • KeyWeakening
As an example, suppose your application is exempt if either key recovery or key escrow is enforced. Then your permission policy file should contain the following:
grant {
// No algorithm restrictions if KeyRecovery is enforced.
permission javax.crypto.CryptoPermission *,
"KeyRecovery";
// No algorithm restrictions if KeyEscrow is enforced.
permission javax.crypto.CryptoPermission *,
"KeyEscrow";
};

Note: Permission entries that specify exemption mechanisms should not also specify maximum key sizes. The allowed key sizes are actually determined from the installed exempt jurisdiction policy files, as described in the next section.

How Bundled Permission Policy Files Affect Cryptographic Permissions

At runtime, when an application instantiates a Cipher (via a call to its getInstance method) and that application has an associated permission policy file, JCE checks to see whether the permission policy file has an entry that applies to the algorithm specified in the getInstance call. If it does, and the entry grants CryptoAllPermission or does not specify that an exemption mechanism must be enforced, it means there is no cryptographic restriction for this particular algorithm.

If the permission policy file has an entry that applies to the algorithm specified in the getInstance call and the entry does specify that an exemption mechanism must be enforced, then the exempt jurisdiction policy file(s) are examined. If the exempt permissions include an entry for the relevant algorithm and exemption mechanism, and that entry is implied by the permissions in the permission policy file bundled with the application, and if there is an implementation of the specified exemption mechanism available from one of the registered providers, then the maximum key size and algorithm parameter values for the Cipher are determined from the exempt permission entry.

If there is no exempt permission entry implied by the relevant entry in the permission policy file bundled with the application, or if there is no implementation of the specified exemption mechanism available from any of the registered providers, then the application is only allowed the standard default cryptographic permissions.


Installing JCE Providers for JDK 5.0

In order to be used, a cryptographic provider must be installed and registered, either statically or dynamically. Cryptographic providers for JCE in JDK 5.0 are installed and configured the same way as all other providers for the JavaTM 2 platform. More information about installing and configuring providers can be found in the Installing Providers section of the JavaTM Cryptography Architecture API Specification & Reference document.

You do not need to register the "SunJCE" provider because it is pre-registered. If you want to use other providers, read the following sections to see how to register them.

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider. In some situations you will also need to set permissions for the provider prior to using it.

Installing the Provider Classes

The first thing you must do is make the provider classes available so that they can be found when requested. Provider classes are shipped as a signed JAR (Java ARchive) file.

There are two possible ways to install the provider classes:

  • Install the JAR file containing the provider classes as an "installed" or "bundled" extension.
  • Place the JAR file containing the provider classes in your class path.

The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:

<java-home>/lib/ext         [Solaris]
<java-home>\lib\ext [Windows]

Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. For example, if you have JDK 5.0 installed on Solaris in a directory named /home/user1/JDK1.5.0, or on Microsoft Windows in a directory named C:\Java DK1.5.0, then you need to install the JAR file in the following directory:

/home/user1/JDK1.5.0/jre/lib/ext    [Solaris]
C:\JDK1.5.0\jre\lib\ext [Windows]

Similarly, if you have the JRE 5.0 installed on Solaris in a directory named /home/user1/jre1.5.0, or on Microsoft Windows in a directory named C:\jre1.5.0, you need to install the JAR file in the following directory:

/home/user1/jre1.5.0/lib/ext         [Solaris]
C:\jre1.5.0\lib\ext [Windows]

For more information, refer to these sections in the "Extension Mechanism Architecture" specification: Installed Extensions and Bundled Extensions.

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file

<java-home>/lib/security/java.security     [Solaris]
<java-home>\lib\security\java.security [Windows]

Here <java-home> refers to the directory where the JRE was installed. For example, if you have JDK 5.0 installed on Solaris in a directory named /home/user1/JDK1.5.0, or on Microsoft Windows in a directory named C:\JDK1.5.0, then you need to edit the following file:

/home/user1/JDK1.5.0/jre/lib/security/java.security  [Solaris]
C:\JDK1.5.0\jre\lib\security\java.security [Windows]

Similarly, if you have the Java 2 Runtime Environment, v 1.4 installed on Solaris in a directory named /home/user1/jre1.5.0, or on Microsoft Windows in a directory named C:\jre1.5.0, then you need to edit this file:

/home/user1/jre1.5.0/lib/security/java.security       [Solaris]
C:\jre1.5.0\lib\security\java.security [Windows]

For each provider, this file should have a statement of the following form:

    security.provider.n=masterClassName
    

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of the provider's "master class". The provider vendor should supply you this name.

JDK 5.0 comes standard with a provider named "SUN", which is automatically configured as a static provider in the java.security properties file, as follows:

security.provider.1=sun.security.provider.Sun

(The "SUN" provider's master class is the Sun class in the sun.security.provider package.)

The JCE provider "SunJCE" and other security-related providers shipped with the Java 2 platform are also automatically configured as static providers.

To utilize another JCE provider, add a line registering the alternate provider, giving it whatever preference order you prefer (and making corresponding adjustments to the other providers' orders, if needed).

Suppose that the master class of a provider you want to register is the CryptoX class in the com.cryptox.provider package, and that you would like to make this provider the second preferred provider. To do so, add the following line to the java.security file below the line for the "SUN" provider, and increment the preference order numbers for all other providers whose numbers were greater than or equal to 2 before your addition:

    security.provider.2=com.cryptox.provider.CryptoX
Note: Providers may also be registered dynamically. To do so, a program can call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by code which is granted the following permission:
java.security.SecurityPermission "insertProvider.{name}"
where {name} is replaced by the actual provider name. For example, if the provider name is "MyJCE" and if your code that dynamically registers this provider is in the MyApp.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:
grant codeBase "file:/localWork/MyApp.jar" {
permission java.security.SecurityPermission
"insertProvider.MyJCE";
};

Setting Provider Permissions

Whenever JCE providers are not installed extensions, permissions must be granted for when applets or applications using JCE are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy configuration file grants all permissions to installed extensions.

The documentation from the vendor of each provider you will be using should include information as to which permissions it requires, and how to grant such permissions. For example, the following permissions may be needed by a provider if it is not an installed extension and a security manager is installed:

  • java.lang.RuntimePermission to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
  • java.security.SecurityPermission "putProviderProperty.{name}" to set provider properties, where {name} is replaced by the actual provider name.

For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar file is assumed to be in the /localWork directory.

grant codeBase "file:/localWork/myjce_provider.jar" {
permission java.lang.RuntimePermission "getProtectionDomain";
permission java.security.SecurityPermission
"putProviderProperty.MyJCE";
};

JCE Keystore

The "SunJCE" provider supplies its own implementation of the java.security.KeyStore class in the JDK 5.0. Its implementation employs a much stronger protection of private keys (using password-based encryption with Triple DES) than the keystore implementation supplied by the "SUN" provider in the JDK 5.0 (Note that because the JDK 5.0 is distributed world-wide in binary and source format, it cannot employ any strong encryption mechanisms.)

In order to take advantage of the keystore implementation of the "SunJCE" provider, you specify "JCEKS" as the keystore type.

You may upgrade your keystore of type "JKS" - this is the name of the keystore type implemented by the "SUN" provider in the Java 2 SDK - to a JCE keystore of type "JCEKS" by changing the password of a private-key entry in your keystore.

To apply the cryptographically strong(er) key protection supplied by "SunJCE" to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords:

    keytool -keypasswd -alias signkey -storetype jceks

You may want to change the password back to its old value, using the same command.

See Security Tools for more information about keytool and about keystores and how they are managed.


Code Examples

This section is a short tutorial on how to use some of the major features of the JCE APIs in the JDK 5.0 Complete sample programs that exercise the APIs can be found in Appendix F of this document.

Using Encryption

This section takes the user through the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. Throughout this example, we use the Data Encryption Standard (DES).

Generating a Key

To create a DES key, we have to instantiate a KeyGenerator for DES. We do not specify a provider, because we do not care about a particular DES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness will be used to create the DES key:

    KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecretKey desKey = keygen.generateKey();

After the key has been generated, the same KeyGenerator object can be re-used to create further keys.

Creating a Cipher

The next step is to create a Cipher instance. To do this, we use one of the getInstance factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/):

  • the algorithm name
  • the mode (optional)
  • the padding scheme (optional)

In this example, we create a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS #5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation.

The standard algorithm name for DES is "DES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS #5-style padding is "PKCS5Padding":

    Cipher desCipher;

// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

We use the generated desKey from above to initialize the Cipher object for encryption:

    // Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, desKey);

// Our cleartext
byte[] cleartext = "This is just an example".getBytes();

// Encrypt the cleartext
byte[] ciphertext = desCipher.doFinal(cleartext);

// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, desKey);

// Decrypt the ciphertext
byte[] cleartext1 = desCipher.doFinal(ciphertext);

cleartext and cleartext1 are identical.

Using Password-Based Encryption

In this example, we prompt the user for a password from which we derive an encryption key.

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.

The following method is an example of how to collect a user password as a char array:

    /**
* Reads user password from given input stream.
*/
public char[] readPasswd(InputStream in) throws IOException {
char[] lineBuffer;
char[] buf;
int i;

buf = lineBuffer = new char[128];

int room = buf.length;
int offset = 0;
int c;

loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;

case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) {
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
} else
break loop;

default:
if (--room < 0) {
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}

if (offset == 0) {
return null;
}

char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');

return ret;
}

In order to use Password-Based Encryption (PBE) as defined in PKCS #5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption:

    PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;

// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};

// Iteration count
int count = 20;

// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);

// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPasswd" method from above), and convert
// it into a SecretKey object, using a PBE key
// factory.
System.out.print("Enter encryption password: ");
System.out.flush();
pbeKeySpec = new PBEKeySpec(readPasswd(System.in));
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

// Our cleartext
byte[] cleartext = "This is another example".getBytes();

// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);

Using Key Agreement

Please refer to Appendix F for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties, respectively.


Appendix A: Standard Names

The JCE API requires and utilizes a set of standard names for algorithms, algorithm modes, and padding schemes. This specification establishes the following names as standard names. It supplements the list of standard names defined in Appendix A in the JavaTM Cryptography Architecture API Specification & Reference. Note that algorithm names are treated case-insensitively.

In some cases naming conventions are suggested for forming names that are not explicitly listed, to facilitate name consistency across provider implementations. Such suggestions use items in angle brackets (such as <digest> and <encryption>) as placeholders to be replaced by specific message digest, encryption algorithm, and other names.

Cipher

Algorithm

The following names can be specified as the algorithm component in a transformation when requesting an instance of Cipher:

  • AES: Advanced Encryption Standard as specified by NIST in a draft FIPS. Based on the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits.
  • ARCFOUR/RC4: A stream cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt.
  • Blowfish: The block cipher designed by Bruce Schneier.
  • DES: The Digital Encryption Standard as described in FIPS PUB 46-2.
  • DESede: Triple DES Encryption (DES-EDE).
  • ECIES (Elliptic Curve Integrated Encryption Scheme)
  • PBEWith<digest>And<encryption> or PBEWith<prf>And<encryption>: The password-based encryption algorithm (PKCS #5), using the specified message digest (<digest>) or pseudo-random function (<prf>) and encryption algorithm (<encryption>). Examples:
    • PBEWithMD5AndDES: The password-based encryption algorithm as defined in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993. Note that this algorithm implies CBC as the cipher mode and PKCS5Padding as the padding scheme and cannot be used with any other cipher modes or padding schemes.
    • PBEWithHmacSHA1AndDESede: The password-based encryption algorithm as defined in: RSA Laboratories, "PKCS #5: Password-Based Cryptography Standard," version 2.0, March 1999.
  • RC2, RC4, and RC5: Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.
  • RSA: The RSA encryption algorithm as defined in PKCS #1.

Mode

The following names can be specified as the mode component in a transformation when requesting an instance of Cipher:

  • NONE: No mode.
  • CBC: Cipher Block Chaining Mode, as defined in FIPS PUB 81.
  • CFB: Cipher Feedback Mode, as defined in FIPS PUB 81.
  • ECB: Electronic Codebook Mode, as defined in: The National Institute of Standards and Technology (NIST) Federal Information Processing Standard (FIPS) PUB 81, "DES Modes of Operation," U.S. Department of Commerce, Dec 1980.
  • OFB: Output Feedback Mode, as defined in FIPS PUB 81.
  • PCBC: Propagating Cipher Block Chaining, as defined by Kerberos V4.

Padding

The following names can be specified as the padding component in a transformation when requesting an instance of Cipher:

  • ISO10126Padding. This padding for block ciphers is described in 5.2 Block Encryption Algorithms in the W3C's "XML Encryption Syntax and Processing" document.
  • NoPadding: No padding.
  • OAEPWith<digest>And<mgf>Padding: Optimal Asymmetric Encryption Padding scheme defined in PKCS #1, where <digest> should be replaced by the message digest and <mgf> by the mask generation function. Example: OAEPWithMD5AndMGF1Padding.
  • PKCS5Padding: The padding scheme described in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, November 1993.
  • SSL3Padding: The padding scheme defined in the SSL Protocol Version 3.0, November 18, 1996, section 5.2.3.2 (CBC block cipher):
        block-ciphered struct {
    opaque content[SSLCompressed.length];
    opaque MAC[CipherSpec.hash_size];
    uint8 padding[GenericBlockCipher.padding_length];
    uint8 padding_length;
    } GenericBlockCipher;

    The size of an instance of a GenericBlockCipher must be a multiple of the block cipher's block length.

    The padding length, which is always present, contributes to the padding, which implies that if:

        sizeof(content) + sizeof(MAC) % block_length = 0,
    padding has to be (block_length - 1) bytes long, because of the existence of padding_length.

    This make the padding scheme similar (but not quite) to PKCS5Padding, where the padding length is encoded in the padding (and ranges from 1 to block_length). With the SSL scheme, the sizeof(padding) is encoded in the always present padding_length and therefore ranges from 0 to block_length-1.

    Note that this padding mechanism is not supported by the "SunJCE" provider.

KeyAgreement

The following algorithm names can be specified when requesting an instance of KeyAgreement:

  • DiffieHellman: Diffie-Hellman Key Agreement as defined in PKCS #3: Diffie-Hellman Key-Agreement Standard, RSA Laboratories, version 1.4, November 1993.
  • ECDH (Elliptic Curve Diffie-Hellman) as described in RFC 3278: "Use of Elliptic Curve Cryptography (ECC) Algorithms in Cryptographic Message Syntax (CMS)."
  • ECMQV (Elliptic Curve Menezes-Qu-Vanstone) as described in ECC Cipher Suites For TLS (January 2004 draft).

KeyGenerator

The following algorithm names can be specified when requesting an instance of KeyGenerator:

  • AES
  • ARCFOUR/RC4
  • Blowfish
  • DES
  • DESede
  • HmacMD5
  • HmacSHA1
  • HmacSHA256
  • HmacSHA384
  • HmacSHA512
  • RC2

KeyPairGenerator

The following algorithm names can be specified when requesting an instance of KeyPairGenerator:

  • DiffieHellman

SecretKeyFactory

The following algorithm names can be specified when requesting an instance of SecretKeyFactory:

  • DES
  • DESede
  • PBEWith<digest>And<encryption> or PBEWith<prf>And<encryption>: Secret-key factory for use with PKCS #5 password-based encryption, where <digest> is a message digest, <prf> is a pseudo-random function, and <encryption> is an encryption algorithm. Examples: PBEWithMD5AndDES (PKCS #5, v 1.5) and PBEWithHmacSHA1AndDESede (PKCS #5, v 2.0). Note: These both use only the low order 8 bits of each password character.

KeyFactory

The following algorithm names can be specified when requesting an instance of KeyFactory:

  • DiffieHellman

AlgorithmParameterGenerator

The following algorithm names can be specified when requesting an instance of AlgorithmParameterGenerator:

  • DiffieHellman

AlgorithmParameters

The following algorithm names can be specified when requesting an instance of AlgorithmParameters:

  • AES
  • Blowfish
  • DES
  • DESede
  • DiffieHellman
  • OAEP
  • PBE
  • PBEWith<digest>And<encryption>
  • RC2

MAC

The following algorithm names can be specified when requesting an instance of Mac:

  • HmacMD5: The HMAC-MD5 keyed-hashing algorithm as defined in RFC 2104: "HMAC: Keyed-Hashing for Message Authentication" (February 1997).
  • HmacSHA1: The HMAC-SHA1 keyed-hashing algorithm as defined in RFC 2104: "HMAC: Keyed-Hashing for Message Authentication" (February 1997).
  • HmacSHA256: The HmacSHA256 algorithm as defined in RFC 2104 "HMAC: Keyed-Hashing for Message Authentication" (February 1997) with SHA-256 as the message digest algorithm.
  • HmacSHA384: The HmacSHA384 algorithm as defined in RFC 2104 "HMAC: Keyed-Hashing for Message Authentication" (February 1997) with SHA-384 as the message digest algorithm.
  • HmacSHA512: The HmacSHA512 algorithm as defined in RFC 2104 "HMAC: Keyed-Hashing for Message Authentication" (February 1997) with SHA-512 as the message digest algorithm.
  • PBEWith<mac>: MAC for use with PKCS #5 v 2.0 password-based message authentication standard, where <mac> is a Message Authentication Code algorithm name. Example: PBEWithHmacSHA1.

Keystore Types

The following types can be specified when requesting an instance of KeyStore:

Exemption Mechanisms

The following exemption mechanism names can be specified in the permission policy file that accompanies an application considered "exempt" from cryptographic restrictions:

  • KeyEscrow: An encryption system with a backup decryption capability that allows authorized persons (users, officers of an organization, and government officials), under certain prescribed conditions, to decrypt ciphertext with the help of information supplied by one or more trusted parties who hold special data recovery keys.
  • KeyRecovery: A method of obtaining the secret key used to lock encrypted data. One use is as a means of providing fail-safe access to a corporation's own encrypted information in times of disaster.
  • KeyWeakening: A method in which a part of the key can be escrowed or recovered.

Appendix B: SunJCE Default Keysizes

The SunJCE provider uses the following default keysizes:

  • KeyGenerator
    • DES: 56 bits
    • Triple DES: 112 bits
    • Blowfish: 56 bits
    • HmacMD5: 64 bytes
    • HmacSHA1: 64 bytes
  • KeyPairGenerator
    • Diffie-Hellman: 1024 bits
  • AlgorithmParameterGenerator
    • Diffie-Hellman: 1024 bits

Appendix C: SunJCE Keysize Restrictions

The SunJCE provider enforces the following restrictions on the keysize passed to the initialization methods of the following classes:

  • KeyGenerator

    Restrictions (by algorithm):

    • DES: keysize must be equal to 56
    • Triple DES: keysize must be equal to 112 or 168

      Note: A keysize of 112 will generate a Triple DES key with 2 intermediate keys, and a keysize of 168 will generate a Triple DES key with 3 intermediate keys.

    • Blowfish: keysize must be a multiple of 8, and can only range from 32 to 448, inclusive
  • KeyPairGenerator

    Restrictions (by algorithm):

    • Diffie-Hellman: keysize must be a multiple of 64, and can only range from 512 to 1024, inclusive
  • AlgorithmParameterGenerator

    Restrictions (by algorithm):

    • Diffie-Hellman: keysize must be a multiple of 64, and can only range from 512 to 1024, inclusive

Appendix D: Jurisdiction Policy File Format

JCE represents its jurisdiction policy files as J2SE-style policy files with corresponding permission statements. As described in Default Policy Implementation and Policy File Syntax, a J2SE policy file specifies what permissions are allowed for code from specified code sources. A permission represents access to a system resource. In the case of JCE, the "resources" are cryptography algorithms, and code sources do not need to be specified, because the cryptographic restrictions apply to all code.

A jurisdiction policy file consists of a very basic "grant entry" containing one or more "permission entries."

grant {
<permission entries>;
};

The format of a permission entry in a jurisdiction policy file is:

permission <crypto permission class name>[ <alg_name>
[[, <exemption mechanism name>][, <maxKeySize>
[, <AlgorithmParameterSpec class name>,
<parameters for constructing an
AlgorithmParameterSpec object>]]]];

A sample jurisdiction policy file that includes restricting the "Blowfish" algorithm to maximum key sizes of 64 bits is:

grant {
permission javax.crypto.CryptoPermission "Blowfish", 64;
. . .;
};

A permission entry must begin with the word permission. The <crypto permission class name> in the template above would actually be a specific permission class name, such as javax.crypto.CryptoPermission. A crypto permission class reflects the ability of an application/applet to use certain algorithms with certain key sizes in certain environments. There are two crypto permission classes: CryptoPermission and CryptoAllPermission. The special CryptoAllPermission class implies all cryptography-related permissions, that is, it specifies that there are no cryptography-related restrictions.

The <alg_name>, when utilized, is a quoted string specifying the standard name (see Appendix A) of a cryptography algorithm, such as "DES" or "RSA".

The <exemption mechanism name>, when specified, is a quoted string indicating an exemption mechanism which, if enforced, enables a reduction in cryptographic restrictions. Exemption mechanism names that can be used include "KeyRecovery" "KeyEscrow", and "KeyWeakening".

<maxKeySize> is an integer specifying the maximum key size (in bits) allowed for the specified algorithm.

For some algorithms it may not be sufficient to specify the algorithm strength in terms of just a key size. For example, in the case of the "RC5" algorithm, the number of rounds must also be considered. For algorithms whose strength needs to be expressed as more than a key size, the permission entry should also specify an AlgorithmParameterSpec class name (such as javax.crypto.spec.RC5ParameterSpec) and a list of parameters for constructing the specified AlgorithmParameterSpec object.

Items that appear in a permission entry must appear in the specified order. An entry is terminated with a semicolon.

Case is unimportant for the identifiers (grant, permission) but is significant for the <crypto permission class name> or for any string that is passed in as a value.

Note: An "*" can be used as a wildcard for any permission entry option. For example, an "*" (without the quotes) for an <alg_name> option means "all algorithms."


Appendix E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Due to import control restrictions, the jurisdiction policy files shipped with JDK 5.0 allow "strong" but limited cryptography to be used. Here are the maximum key sizes allowed by this "strong" version of the jurisdiction policy files:

Algorithm

Maximum Key Size

DES

64

DESede

*

RC2

128

RC4

128

RC5

128

RSA

2048

* (all others)

128


Appendix F: Sample Programs

  • Diffie-Hellman Key Exchange between 2 Parties

    /*
    * Copyright 1997-2001 by Sun Microsystems, Inc.,
    * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
    * All rights reserved.
    *
    * This software is the confidential and proprietary information
    * of Sun Microsystems, Inc. ("Confidential Information"). You
    * shall not disclose such Confidential Information and shall use
    * it only in accordance with the terms of the license agreement
    * you entered into with Sun.
    */

    import java.io.*;
    import java.math.BigInteger;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import javax.crypto.interfaces.*;
    import com.sun.crypto.provider.SunJCE;

    /**
    * This program executes the Diffie-Hellman key agreement protocol
    * between 2 parties: Alice and Bob.
    *
    * By default, preconfigured parameters (1024-bit prime modulus and base
    * generator used by SKIP) are used.
    * If this program is called with the "-gen" option, a new set of
    * parameters is created.
    */

    public class DHKeyAgreement2 {

    private DHKeyAgreement2() {}

    public static void main(String argv[]) {
    try {
    String mode = "USE_SKIP_DH_PARAMS";

    DHKeyAgreement2 keyAgree = new DHKeyAgreement2();

    if (argv.length > 1) {
    keyAgree.usage();
    throw new Exception("Wrong number of command options");
    } else if (argv.length == 1) {
    if (!(argv[0].equals("-gen"))) {
    keyAgree.usage();
    throw new Exception("Unrecognized flag: " + argv[0]);
    }
    mode = "GENERATE_DH_PARAMS";
    }

    keyAgree.run(mode);
    } catch (Exception e) {
    System.err.println("Error: " + e);
    System.exit(1);
    }
    }

    private void run(String mode) throws Exception {

    DHParameterSpec dhSkipParamSpec;

    if (mode.equals("GENERATE_DH_PARAMS")) {
    // Some central authority creates new DH parameters
    System.out.println
    ("Creating Diffie-Hellman parameters (takes VERY long) ...");
    AlgorithmParameterGenerator paramGen
    = AlgorithmParameterGenerator.getInstance("DH");
    paramGen.init(512);
    AlgorithmParameters params = paramGen.generateParameters();
    dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
    (DHParameterSpec.class);
    } else {
    // use some pre-generated, default DH parameters
    System.out.println("Using SKIP Diffie-Hellman parameters");
    dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
    skip1024Base);
    }

    /*
    * Alice creates her own DH key pair, using the DH parameters from
    * above
    */
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

    // Alice creates and initializes her DH KeyAgreement object
    System.out.println("ALICE: Initialization ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());

    // Alice encodes her public key, and sends it over to Bob.
    byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();

    /*
    * Let's turn over to Bob. Bob has received Alice's public key
    * in encoded format.
    * He instantiates a DH public key from the encoded key material.
    */
    KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
    (alicePubKeyEnc);
    PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);

    /*
    * Bob gets the DH parameters associated with Alice's public key.
    * He must use the same parameters when he generates his own key
    * pair.
    */
    DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();

    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();

    // Bob creates and initializes his DH KeyAgreement object
    System.out.println("BOB: Initialization ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());

    // Bob encodes his public key, and sends it over to Alice.
    byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();

    /*
    * Alice uses Bob's public key for the first (and only) phase
    * of her version of the DH
    * protocol.
    * Before she can do so, she has to instanticate a DH public key
    * from Bob's encoded key material.
    */
    KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
    x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
    PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
    System.out.println("ALICE: Execute PHASE1 ...");
    aliceKeyAgree.doPhase(bobPubKey, true);

    /*
    * Bob uses Alice's public key for the first (and only) phase
    * of his version of the DH
    * protocol.
    */
    System.out.println("BOB: Execute PHASE1 ...");
    bobKeyAgree.doPhase(alicePubKey, true);

    /*
    * At this stage, both Alice and Bob have completed the DH key
    * agreement protocol.
    * Both generate the (same) shared secret.
    */
    byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
    int aliceLen = aliceSharedSecret.length;

    byte[] bobSharedSecret = new byte[aliceLen];
    int bobLen;
    try {
    // show example of what happens if you
    // provide an output buffer that is too short
    bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
    } catch (ShortBufferException e) {
    System.out.println(e.getMessage());
    }
    // provide output buffer of required size
    bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);

    System.out.println("Alice secret: " +
    toHexString(aliceSharedSecret));
    System.out.println("Bob secret: " +
    toHexString(bobSharedSecret));

    if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
    throw new Exception("Shared secrets differ");
    System.out.println("Shared secrets are the same");

    /*
    * Now let's return the shared secret as a SecretKey object
    * and use it for encryption. First, we generate SecretKeys for the
    * "DES" algorithm (based on the raw shared secret data) and
    * then we use DES in ECB mode
    * as the encryption algorithm. DES in ECB mode does not require any
    * parameters.
    *
    * Then we use DES in CBC mode, which requires an initialization
    * vector (IV) parameter. In CBC mode, you need to initialize the
    * Cipher object with an IV, which can be supplied using the
    * javax.crypto.spec.IvParameterSpec class. Note that you have to use
    * the same IV for encryption and decryption: If you use a different
    * IV for decryption than you used for encryption, decryption will
    * fail.
    *
    * Note: If you do not specify an IV when you initialize the
    * Cipher object for encryption, the underlying implementation
    * will generate a random one, which you have to retrieve using the
    * javax.crypto.Cipher.getParameters() method, which returns an
    * instance of java.security.AlgorithmParameters. You need to transfer
    * the contents of that object (e.g., in encoded format, obtained via
    * the AlgorithmParameters.getEncoded() method) to the party who will
    * do the decryption. When initializing the Cipher for decryption,
    * the (reinstantiated) AlgorithmParameters object must be passed to
    * the Cipher.init() method.
    */
    System.out.println("Return shared secret as SecretKey object ...");
    // Bob
    // Note: The call to bobKeyAgree.generateSecret above reset the key
    // agreement object, so we call doPhase again prior to another
    // generateSecret call
    bobKeyAgree.doPhase(alicePubKey, true);
    SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");

    // Alice
    // Note: The call to aliceKeyAgree.generateSecret above reset the key
    // agreement object, so we call doPhase again prior to another
    // generateSecret call
    aliceKeyAgree.doPhase(bobPubKey, true);
    SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");

    /*
    * Bob encrypts, using DES in ECB mode
    */
    Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

    byte[] cleartext = "This is just an example".getBytes();
    byte[] ciphertext = bobCipher.doFinal(cleartext);

    /*
    * Alice decrypts, using DES in ECB mode
    */
    Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
    byte[] recovered = aliceCipher.doFinal(ciphertext);

    if (!java.util.Arrays.equals(cleartext, recovered))
    throw new Exception("DES in CBC mode recovered text is " +
    "different from cleartext");
    System.out.println("DES in ECB mode recovered text is " +
    "same as cleartext");

    /*
    * Bob encrypts, using DES in CBC mode
    */
    bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

    cleartext = "This is just an example".getBytes();
    ciphertext = bobCipher.doFinal(cleartext);
    // Retrieve the parameter that was used, and transfer it to Alice in
    // encoded format
    byte[] encodedParams = bobCipher.getParameters().getEncoded();

    /*
    * Alice decrypts, using DES in CBC mode
    */
    // Instantiate AlgorithmParameters object from parameter encoding
    // obtained from Bob
    AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
    params.init(encodedParams);
    aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
    recovered = aliceCipher.doFinal(ciphertext);

    if (!java.util.Arrays.equals(cleartext, recovered))
    throw new Exception("DES in CBC mode recovered text is " +
    "different from cleartext");
    System.out.println("DES in CBC mode recovered text is " +
    "same as cleartext");
    }

    /*
    * Converts a byte to hex digit and writes to the supplied buffer
    */
    private void byte2hex(byte b, StringBuffer buf) {
    char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
    '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int high = ((b & 0xf0) >> 4);
    int low = (b & 0x0f);
    buf.append(hexChars[high]);
    buf.append(hexChars[low]);
    }

    /*
    * Converts a byte array to hex string
    */
    private String toHexString(byte[] block) {
    StringBuffer buf = new StringBuffer();

    int len = block.length;

    for (int i = 0; i < len; i++) {
    byte2hex(block[i], buf);
    if (i < len-1) {
    buf.append(":");
    }
    }
    return buf.toString();
    }

    /*
    * Prints the usage of this test.
    */
    private void usage() {
    System.err.print("DHKeyAgreement usage: ");
    System.err.println("[-gen]");
    }

    // The 1024 bit Diffie-Hellman modulus values used by SKIP
    private static final byte skip1024ModulusBytes[] = {
    (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
    (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
    (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
    (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
    (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
    (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
    (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
    (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
    (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
    (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
    (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
    (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
    (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
    (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
    (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
    (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
    (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
    (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
    (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
    (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
    (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
    (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
    (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
    (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
    (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
    (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
    (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
    (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
    (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
    (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
    (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
    (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
    };

    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
    = new BigInteger(1, skip1024ModulusBytes);

    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
    }

  • Diffie-Hellman Key Exchange between 3 Parties

    /*
    * Copyright 1997-2001 by Sun Microsystems, Inc.,
    * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
    * All rights reserved.
    *
    * This software is the confidential and proprietary information
    * of Sun Microsystems, Inc. ("Confidential Information"). You
    * shall not disclose such Confidential Information and shall use
    * it only in accordance with the terms of the license agreement
    * you entered into with Sun.
    */

    import java.io.*;
    import java.math.BigInteger;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import javax.crypto.interfaces.*;
    import com.sun.crypto.provider.SunJCE;

    /**
    * This program executes the Diffie-Hellman key agreement protocol
    * between 3 parties: Alice, Bob, and Carol.
    *
    * We use the same 1024-bit prime modulus and base generator that are
    * used by SKIP.
    */

    public class DHKeyAgreement3 {

    private DHKeyAgreement3() {}

    public static void main(String argv[]) {
    try {
    DHKeyAgreement3 keyAgree = new DHKeyAgreement3();
    keyAgree.run();
    } catch (Exception e) {
    System.err.println("Error: " + e);
    System.exit(1);
    }
    }

    private void run() throws Exception {

    DHParameterSpec dhSkipParamSpec;

    System.out.println("Using SKIP Diffie-Hellman parameters");
    dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);

    // Alice creates her own DH key pair
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhSkipParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();

    // Carol creates her own DH key pair
    System.out.println("CAROL: Generate DH keypair ...");
    KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH");
    carolKpairGen.initialize(dhSkipParamSpec);
    KeyPair carolKpair = carolKpairGen.generateKeyPair();


    // Alice initialize
    System.out.println("ALICE: Initialize ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());

    // Bob initialize
    System.out.println("BOB: Initialize ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());

    // Carol initialize
    System.out.println("CAROL: Initialize ...");
    KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH");
    carolKeyAgree.init(carolKpair.getPrivate());


    // Alice uses Carol's public key
    Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false);

    // Bob uses Alice's public key
    Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false);

    // Carol uses Bob's public key
    Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false);


    // Alice uses Carol's result from above
    aliceKeyAgree.doPhase(cb, true);

    // Bob uses Alice's result from above
    bobKeyAgree.doPhase(ac, true);

    // Carol uses Bob's result from above
    carolKeyAgree.doPhase(ba, true);


    // Alice, Bob and Carol compute their secrets
    byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
    System.out.println("Alice secret: " + toHexString(aliceSharedSecret));

    byte[] bobSharedSecret = bobKeyAgree.generateSecret();
    System.out.println("Bob secret: " + toHexString(bobSharedSecret));

    byte[] carolSharedSecret = carolKeyAgree.generateSecret();
    System.out.println("Carol secret: " + toHexString(carolSharedSecret));


    // Compare Alice and Bob
    if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
    throw new Exception("Alice and Bob differ");
    System.out.println("Alice and Bob are the same");

    // Compare Bob and Carol
    if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret))
    throw new Exception("Bob and Carol differ");
    System.out.println("Bob and Carol are the same");
    }


    /*
    * Converts a byte to hex digit and writes to the supplied buffer
    */
    private void byte2hex(byte b, StringBuffer buf) {
    char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
    '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int high = ((b & 0xf0) >> 4);
    int low = (b & 0x0f);
    buf.append(hexChars[high]);
    buf.append(hexChars[low]);
    }

    /*
    * Converts a byte array to hex string
    */
    private String toHexString(byte[] block) {
    StringBuffer buf = new StringBuffer();

    int len = block.length;

    for (int i = 0; i < len; i++) {
    byte2hex(block[i], buf);
    if (i < len-1) {
    buf.append(":");
    }
    }
    return buf.toString();
    }

    /*
    * Prints the usage of this test.
    */
    private void usage() {
    System.err.print("DHKeyAgreement usage: ");
    System.err.println("[-gen]");
    }

    // The 1024 bit Diffie-Hellman modulus values used by SKIP
    private static final byte skip1024ModulusBytes[] = {
    (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
    (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
    (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
    (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
    (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
    (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
    (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
    (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
    (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
    (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
    (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
    (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
    (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
    (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
    (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
    (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
    (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
    (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
    (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
    (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
    (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
    (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
    (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
    (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
    (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
    (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
    (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
    (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
    (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
    (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
    (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
    (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
    };

    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
    = new BigInteger(1, skip1024ModulusBytes);

    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
    }

  • Blowfish Example

    /*
    * Copyright 1997-2001 by Sun Microsystems, Inc.,
    * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
    * All rights reserved.
    *
    * This software is the confidential and proprietary information
    * of Sun Microsystems, Inc. ("Confidential Information"). You
    * shall not disclose such Confidential Information and shall use
    * it only in accordance with the terms of the license agreement
    * you entered into with Sun.
    */

    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;

    /**
    * This program generates a Blowfish key, retrieves its raw bytes, and
    * then reinstantiates a Blowfish key from the key bytes.
    * The reinstantiated key is used to initialize a Blowfish cipher for
    * encryption.
    */

    public class BlowfishKey {

    public static void main(String[] args) throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted =
    cipher.doFinal("This is just an example".getBytes());
    }
    }

  • HMAC-MD5 Example

    /*
    * Copyright 1997-2001 by Sun Microsystems, Inc.,
    * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
    * All rights reserved.
    *
    * This software is the confidential and proprietary information
    * of Sun Microsystems, Inc. ("Confidential Information"). You
    * shall not disclose such Confidential Information and shall use
    * it only in accordance with the terms of the license agreement
    * you entered into with Sun.
    */

    import java.security.*;
    import javax.crypto.*;

    /**
    * This program demonstrates how to generate a secret-key object for
    * HMAC-MD5, and initialize an HMAC-MD5 object with it.
    */

    public class initMac {

    public static void main(String[] args) throws Exception {

    // Generate secret key for HMAC-MD5
    KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
    SecretKey sk = kg.generateKey();

    // Get instance of Mac object implementing HMAC-MD5, and
    // initialize it with the above secret key
    Mac mac = Mac.getInstance("HmacMD5");
    mac.init(sk);
    byte[] result = mac.doFinal("Hi There".getBytes());
    }
    }

Copyright ¨ 1996-2004 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@java.sun.com.


@http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html
2007/03/06 18:59 2007/03/06 18:59
Trackback Address:이 글에는 트랙백을 보낼 수 없습니다