1 /*
2  * @(#) $Id: SymmetricCipherTest.java,v 1.2 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10import javax.crypto.KeyGenerator;
11import javax.crypto.SecretKey;
12import javax.crypto.spec.IvParameterSpec;
13import javax.crypto.Cipher;
14import javax.crypto.IllegalBlockSizeException;
15import javax.crypto.NoSuchPaddingException;
16import javax.crypto.BadPaddingException;
17import java.security.SignatureException;
18import java.security.NoSuchAlgorithmException;
19import java.security.InvalidKeyException;
20import java.security.InvalidAlgorithmParameterException;
21
22public class SymmetricCipherTest {
23    private static byte[] iv = { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
24
25    private static byte[] encrypt(byte[] inpBytes, SecretKey key, String xform) throws
26            NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException,
27            NoSuchPaddingException, BadPaddingException, InvalidAlgorithmParameterException {
28        Cipher cipher = Cipher.getInstance(xform);
29        IvParameterSpec ips = new IvParameterSpec(iv);
30        cipher.init(Cipher.ENCRYPT_MODE, key, ips);
31        return cipher.doFinal(inpBytes);
32    }
33    private static byte[] decrypt(byte[] inpBytes, SecretKey key, String xform) throws
34            NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException,
35            NoSuchPaddingException, BadPaddingException, InvalidAlgorithmParameterException{
36        Cipher cipher = Cipher.getInstance(xform);
37        IvParameterSpec ips = new IvParameterSpec(iv);
38        cipher.init(Cipher.DECRYPT_MODE, key, ips);
39        return cipher.doFinal(inpBytes);
40    }
41
42    public static void main(String[] unused) throws Exception {
43        String xform = "DES/ECB/PKCS5Padding";
44        int keysize = 56;
45        // Generate a secret key
46        KeyGenerator kg = KeyGenerator.getInstance("DES");
47        kg.init(keysize); // 56 is the keysize. Fixed for DES
48        SecretKey key = kg.generateKey();
49
50        byte[] dataBytes = "J2EE Security for Servlets, EJBs and Web Services".getBytes();
51
52        byte[] encBytes = encrypt(dataBytes, key, xform);
53        byte[] decBytes = decrypt(encBytes, key, xform);
54        boolean expected = java.util.Arrays.equals(dataBytes, decBytes);
55        System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!"));
56    }
57}