· 7 years ago · May 05, 2018, 03:14 PM
1import javax.crypto.BadPaddingException;
2import javax.crypto.IllegalBlockSizeException;
3import java.security.InvalidAlgorithmParameterException;
4import java.security.InvalidKeyException;
5import java.security.NoSuchAlgorithmException;
6import javax.crypto.NoSuchPaddingException;
7import javax.crypto.SecretKey;
8import javax.crypto.KeyGenerator;
9import javax.crypto.Cipher;
10import javax.crypto.spec.IvParameterSpec;
11
12public class TestSymCypher {
13
14 /**
15 * Test the symmetric cypher on a string
16 * @param the string to cypher
17 */
18 public void testSymCypher(SecretKey k, String str)
19 throws BadPaddingException, IllegalBlockSizeException,
20 InvalidAlgorithmParameterException, InvalidKeyException,
21 NoSuchAlgorithmException, NoSuchPaddingException
22 {
23 Cipher cip = Cipher.getInstance("DES/CBC/PKCS5Padding");
24 cip.init(Cipher.ENCRYPT_MODE,k);
25 byte[] ciphered = cip.doFinal(str.getBytes());
26 byte iv[] = cip.getIV();
27
28 System.out.println("Original String: " + str);
29 System.out.print("Ciphered: ");
30 printHexadecimal(ciphered);
31 System.out.print("\n");
32
33 IvParameterSpec dps = new IvParameterSpec(iv);
34 cip.init(Cipher.DECRYPT_MODE,k,dps);
35 byte[] deciphered = cip.doFinal(ciphered);
36
37 System.out.println("Deciphered String: " + new String(deciphered));
38 }
39
40 /**
41 * Print a byte array in hexadecimal form
42 * @param the byte array
43 */
44 public void printHexadecimal(byte[] bytes)
45 {
46 for(int i=0; i<bytes.length; i++)
47 System.out.printf("%X",bytes[i]);
48 }
49
50 public static void main(String args[]) throws Exception
51 {
52 String stringTest = "How can I believe in God when just last week I " +
53 "got my tongue caught in the roller of an electric typewriter?";
54
55 TestSymCypher tsc = new TestSymCypher();
56
57 // Generate a symetric AES secret key
58 KeyGenerator generatorDes = KeyGenerator.getInstance("DES");
59 SecretKey skaes = generatorDes.generateKey();
60
61 // Cypher and Decypher a string with the AES key
62 tsc.testSymCypher(skaes, stringTest);
63 }
64}