1 package org.eparapher.core.crypto;
2
3 import java.security.InvalidKeyException;
4 import java.util.Hashtable;
5
6 import javax.crypto.Cipher;
7 import javax.crypto.KeyGenerator;
8 import javax.crypto.SecretKey;
9
10 import org.apache.log4j.Logger;
11 import org.eparapher.core.tools.JVMSettings;
12
13 public class JCEPolicyTest {
14
15 private static Logger log = Logger.getLogger(JCEPolicyTest.class);
16 private static final byte[] hw4test = "Hello World!".getBytes();
17
18 public JCEPolicyTest() {
19
20 }
21
22
23
24
25
26 public static boolean QuickJCEPolicyTest() {
27 long start = System.currentTimeMillis();
28 Cipher aesCipher;
29 try {
30 KeyGenerator keygen = KeyGenerator.getInstance("AES");
31 keygen.init(256);
32
33 SecretKey aesKey = keygen.generateKey();
34
35
36 aesCipher = Cipher.getInstance("AES");
37 aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
38
39 byte[] clearText = "This is an example!".getBytes();
40 log.debug("ClearText: "+new String(clearText));
41
42
43
44
45
46
47
48
49
50
51
52
53
54 } catch (InvalidKeyException e) {
55 if (e.getMessage().toLowerCase().indexOf("illegal key size")>=0) {
56 log.warn("Warning : JCE Unlimited strength not detected on this JVM! ("+ JVMSettings.getJavaHome() +")");
57 } else {
58 log.warn("Warning : could be a JCE Policy problem!", e );
59 }
60 return false;
61 } catch (Exception e) {
62 log.warn("Unknown problem while doing AES-256", e );
63 return false;
64 }
65
66 long stop = System.currentTimeMillis();
67 log.info("JCE Policy test is OK (take "+(stop-start)+"ms)");
68 return true;
69
70 }
71
72 private static Hashtable<String, Boolean> testPolicyRestrictionsForAllAlgorithms() {
73
74 log.info("---- Testing Policy Restrictions ----");
75
76 Hashtable<String, Boolean> results = new Hashtable<String, Boolean>();
77
78 int[] kl = {56,112,168};
79 testAlgorithm(results,"DES", kl);
80 testAlgorithm(results,"DESede", kl);
81
82 int[] klbf = {128,192,256,448};
83 testAlgorithm(results,"Blowfish", klbf);
84
85 int[] klrc4 = {128,192,256,512};
86 testAlgorithm(results,"RC4", klrc4);
87
88 int[] klaes = {128,192,256};
89 testAlgorithm(results,"AES", klaes);
90
91
92
93
94
95
96
97
98
99 log.info("-------------------------");
100 return results ;
101
102 }
103 private static void testAlgorithm(Hashtable<String, Boolean> results, String alg, int[] kl) {
104 for (int i = 0; i < kl.length; i++) {
105 try {
106 SecretKey sk = EPKeyManager.genSymetricKey(alg, kl[i]);
107 byte[] ciphered = EPKeyManager.encryptWithSymetricKey(sk, hw4test);
108 results.put(alg + " " + kl[i], new Boolean(true));
109 } catch (Exception e) {
110 results.put(alg + " " + kl[i], new Boolean(false));
111 }
112 }
113
114 }
115 }