1
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 KeyGenerator kg = KeyGenerator.getInstance("DES");
47 kg.init(keysize); 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}