KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > unitTests > crypto > T_Cipher


1 /*
2
3    Derby - Class org.apache.derbyTesting.unitTests.crypto.T_Cipher
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derbyTesting.unitTests.crypto;
23
24 import org.apache.derbyTesting.unitTests.harness.T_Generic;
25 import org.apache.derbyTesting.unitTests.harness.T_Fail;
26
27 import org.apache.derby.iapi.services.crypto.*;
28
29 import org.apache.derby.iapi.services.monitor.Monitor;
30
31 import org.apache.derby.iapi.db.PropertyInfo;
32
33 import org.apache.derby.iapi.error.StandardException;
34
35 import java.security.AccessController JavaDoc;
36 import java.security.Key JavaDoc;
37 import java.security.PrivilegedAction JavaDoc;
38 import java.security.PrivilegedExceptionAction JavaDoc;
39
40 import java.io.File JavaDoc;
41 import java.io.FileNotFoundException JavaDoc;
42 import java.io.InputStream JavaDoc;
43 import java.io.OutputStream JavaDoc;
44 import java.io.FileInputStream JavaDoc;
45 import java.io.FileOutputStream JavaDoc;
46 import java.io.RandomAccessFile JavaDoc;
47 import java.io.IOException JavaDoc;
48
49 import java.util.Properties JavaDoc;
50
51
52 /*
53 // PT
54 import javax.crypto.Cipher;
55 import javax.crypto.spec.SecretKeySpec;
56 import java.security.spec.KeySpec;
57 import java.security.AlgorithmParameters;
58 // import java.security.spec.AlgorithmParameterSpec;
59 import javax.crypto.spec.IvParameterSpec;
60 import java.security.GeneralSecurityException;
61 import java.security.MessageDigest;
62 import java.lang.reflect.*;
63 */

64
65
66 /*
67     To run, put the following line in derby.properties
68     derby.module.test.T_Cipher=org.apache.derbyTesting.unitTests.crypto.T_Cipher
69
70     and run java org.apache.derbyTesting.unitTests.harness.UnitTestMain
71
72 */

73 public class T_Cipher extends T_Generic
74 {
75     private static final String JavaDoc testService = "CipherText";
76
77     CipherProvider enEngine;
78     CipherProvider deEngine;
79     Key JavaDoc secretKey;
80     byte[] IV;
81
82     CipherFactory factory;
83     
84     public T_Cipher()
85     {
86         super();
87     }
88
89     /*
90     ** Methods required by T_Generic
91     */

92
93     public String JavaDoc getModuleToTestProtocolName() {
94         return org.apache.derby.iapi.reference.Module.CipherFactoryBuilder;
95     }
96
97     protected String JavaDoc getAlgorithm()
98     {
99         return "DES/CBC/NoPadding";
100     }
101
102     protected String JavaDoc getProvider()
103     {
104     // allow for alternate providers
105
String JavaDoc testProvider =
106         
107         (String JavaDoc) AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
108             public Object JavaDoc run() {
109                 return System.getProperty("testEncryptionProvider");
110             }
111         });
112     
113     if (testProvider != null)
114         return testProvider;
115     else
116         return null;
117
118     }
119
120     public void runTests() throws T_Fail {
121
122         File JavaDoc testFile = new File JavaDoc("extinout/T_Cipher.data");
123         deleteFile(testFile);
124
125         String JavaDoc bootPassword = "a secret, don't tell anyone";
126
127         try
128         {
129             RandomAccessFile JavaDoc file = new RandomAccessFile JavaDoc(testFile, "rw");
130
131             setupCiphers(bootPassword);
132
133             // run thru some in patterns
134
int patternLength = 8192;
135             byte[] pattern = new byte[patternLength];
136             for (int i = 0; i < patternLength; i++)
137                 pattern[i] = (byte)(i & 0xFF);
138
139             test(pattern, 0, 8, file); // test short patterns
140
test(pattern, 8, 8, file);
141             test(pattern, 1, 16, file);
142
143             test(pattern, 0, patternLength, file); // test long pattern
144
test(pattern, 0, patternLength/2, file);
145             test(pattern, 1, patternLength/2, file);
146             test(pattern, 2, patternLength/2, file);
147             test(pattern, 3, patternLength/2, file);
148
149             file.seek(0);
150             check(pattern, 0, 8, file); // file offset 0
151
check(pattern, 8, 8, file); // file offset 8
152
check(pattern, 1, 16, file); // file offset 16
153
check(pattern, 0, patternLength, file); // file offset 32
154
check(pattern, 0, patternLength/2, file);// file offset 32+patternLength
155
check(pattern, 1, patternLength/2, file);// file offset 32+patternLength+(patternLength/2)
156
check(pattern, 2, patternLength/2, file);// file offset 32+(2*patternLength)
157
check(pattern, 3, patternLength/2, file);// file offset 32+(2*patternLength)+(patternLength/2);
158

159             REPORT("starting random test");
160
161             // now do some random testing from file
162
file.seek(32+patternLength);
163             check(pattern, 0, patternLength/2, file);
164
165             file.seek(32);
166             check(pattern, 0, patternLength, file);
167
168             file.seek(32+(2*patternLength));
169             check(pattern, 2, patternLength/2, file);
170
171             file.seek(0);
172             check(pattern, 0, 8, file);
173
174             file.seek(16);
175             check(pattern, 1, 16, file);
176
177             file.seek(32+(2*patternLength)+(patternLength/2));
178             check(pattern, 3, patternLength/2, file);
179
180             file.seek(8);
181             check(pattern, 8, 8, file);
182
183             file.seek(32+patternLength+(patternLength/2));
184             check(pattern, 1, patternLength/2, file);
185
186             file.close();
187         }
188         catch (StandardException se)
189         {
190             se.printStackTrace(System.out);
191             throw T_Fail.exceptionFail(se);
192         }
193         catch (IOException JavaDoc ioe)
194         {
195             throw T_Fail.exceptionFail(ioe);
196         }
197
198
199         PASS("T_Cipher");
200     }
201
202
203     protected void setupCiphers(String JavaDoc bootPassword) throws T_Fail, StandardException
204     {
205         // set properties for testing
206
Properties JavaDoc props = new Properties JavaDoc();
207         props.put("encryptionAlgorithm",getAlgorithm());
208         String JavaDoc provider = getProvider();
209         if (provider != null)
210             props.put("encryptionProvider",getProvider());
211         props.put("bootPassword", bootPassword);
212
213         REPORT("encryption algorithm used : " + getAlgorithm());
214         REPORT("encryption provider used : " + provider);
215
216         CipherFactoryBuilder cb = (CipherFactoryBuilder)
217             Monitor.startSystemModule(org.apache.derby.iapi.reference.Module.CipherFactoryBuilder);
218
219         factory = cb.createCipherFactory(true, props, false);
220
221         if (factory == null)
222             throw T_Fail.testFailMsg("cannot find Cipher factory ");
223
224         enEngine = factory.createNewCipher(CipherFactory.ENCRYPT);
225         deEngine = factory.createNewCipher(CipherFactory.DECRYPT);
226
227         if (enEngine == null)
228             throw T_Fail.testFailMsg("cannot create encryption engine");
229         if (deEngine == null)
230             throw T_Fail.testFailMsg("cannot create decryption engine");
231     }
232
233     protected void test(byte[] cleartext, int offset, int length,
234                       RandomAccessFile JavaDoc outfile)
235          throws T_Fail, StandardException, IOException JavaDoc
236     {
237         byte[] ciphertext = new byte[length];
238         System.arraycopy(cleartext, offset, ciphertext, 0, length);
239
240         if (enEngine.encrypt(ciphertext, 0, length, ciphertext, 0) != length)
241             throw T_Fail.testFailMsg("encrypted text length != length");
242
243         if (byteArrayIdentical(ciphertext, cleartext, offset, length))
244             throw T_Fail.testFailMsg("encryption just made a copy of the clear text");
245
246         outfile.write(ciphertext);
247
248         // now decrypt it and check
249
deEngine.decrypt(ciphertext, 0, length, ciphertext, 0);
250         if (byteArrayIdentical(ciphertext, cleartext, offset, length) == false)
251             throw T_Fail.testFailMsg("decryption did not yield the same clear text");
252     }
253
254     protected void check(byte[] cleartext, int offset, int length,
255                        RandomAccessFile JavaDoc infile)
256          throws IOException JavaDoc, T_Fail, StandardException
257     {
258         byte[] ciphertext = new byte[length];
259         infile.read(ciphertext);
260
261         if (deEngine.decrypt(ciphertext, 0, length, ciphertext, 0) != length)
262             throw T_Fail.testFailMsg("decrypted text length != length");
263
264         if (byteArrayIdentical(ciphertext, cleartext, offset, length) == false)
265             throw T_Fail.testFailMsg("decryption did not yield the same clear text");
266
267     }
268
269     // see if 2 byte arrays are identical
270
protected boolean byteArrayIdentical(byte[] compare, byte[] original,
271                                       int offset, int length)
272     {
273         for (int i = 0; i < length; i++)
274         {
275             if (compare[i] != original[offset+i])
276                 return false;
277         }
278         return true;
279     }
280
281
282     /*
283     private void testBlowfish()
284     {
285         System.out.println("Running testBlowfish");
286         try
287         {
288             // set up the provider
289             java.security.Provider sunJce = new com.sun.crypto.provider.SunJCE();
290             java.security.Security.addProvider(sunJce);
291
292             // String key = "Paula bla la da trish123 sdkfs;ldkg;sa'jlskjgklad";
293             String key = "Paulabla123456789012345";
294             byte[] buf = key.getBytes();
295             System.out.println("key length is " + buf.length);
296             SecretKeySpec sKeySpec = new SecretKeySpec(buf,"Blowfish");
297             // SecretKeySpec sKeySpec = new SecretKeySpec(buf,"DESede");
298
299             Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
300             // Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
301             // Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
302             cipher.init(Cipher.ENCRYPT_MODE,sKeySpec);
303             // only works with NoPadding if size is a multiple of 8 bytes
304             // with PKCS5Padding, works for all sizes
305             byte[] original = "This is what should get encrypte".getBytes();
306             System.out.println("original length is " + original.length);
307             byte[] encrypted = cipher.doFinal(original);
308             // works
309             // AlgorithmParameters algParam = cipher.getParameters();
310             byte[] iv = cipher.getIV();
311             System.out.println("length of iv is " + iv.length);
312
313             Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/NoPadding");
314             // Cipher cipher2 = Cipher.getInstance("DESede/CBC/NoPadding");
315             // Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
316
317             // works
318             // cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,algParam);
319             IvParameterSpec ivClass = new IvParameterSpec(iv);
320             cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,ivClass);
321             byte[] decrypted = cipher2.doFinal(encrypted);
322
323             if (byteArrayIdentical(original,decrypted,0,original.length))
324                 System.out.println("PASSED");
325             else
326                 System.out.println("FAILED");
327
328             System.out.println("original length is " + original.length);
329             System.out.println("encrypted length is " + encrypted.length);
330             System.out.println("decrypted length is " + decrypted.length);
331         }
332         catch (Throwable t)
333         {
334             System.out.println("got an exception");
335             t.printStackTrace();
336         }
337
338         System.out.println("Finished testBlowfish");
339     }
340
341
342     private void testCryptix()
343     {
344         System.out.println("Running testCryptix");
345         try
346         {
347             // set up the provider
348             Class jceClass = Class.forName("cryptix.jce.provider.Cryptix");
349             java.security.Provider cryptixProvider = (java.security.Provider) jceClass.newInstance();
350             java.security.Security.addProvider(cryptixProvider);
351
352             byte[] userkey = "a secret".getBytes();
353             System.out.println("userkey length is " + userkey.length);
354             Key secretKey = (Key) (new SecretKeySpec(userkey, "DES"));
355             byte[] IV = "anivspec".getBytes();
356
357             Cipher enCipher = Cipher.getInstance("DES/CBC/NoPadding","Cryptix");
358             Cipher deCipher = Cipher.getInstance("DES/CBC/NoPadding","Cryptix");
359             IvParameterSpec ivspec = new IvParameterSpec(IV);
360
361             enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
362             deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
363
364             int patternLength = 8;
365             byte[] pattern = new byte[patternLength];
366             for (int i = 0; i < patternLength; i++)
367                 pattern[i] = (byte)(i & 0xFF);
368
369             byte[] cipherOutput1 = new byte[patternLength];
370             byte[] cipherOutput2 = new byte[patternLength];
371
372             int retval = 0;
373             retval = enCipher.doFinal(pattern, 0, 8, cipherOutput1, 0);
374
375             retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
376
377             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
378                 System.out.println("PASSED TEST 1");
379             else
380                 System.out.println("FAILED TEST 1");
381
382             retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
383
384             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
385                 System.out.println("PASSED TEST 2");
386             else
387                 System.out.println("FAILED TEST 2");
388         }
389         catch (Throwable t)
390         {
391             System.out.println("got an exception");
392             t.printStackTrace();
393         }
394
395         System.out.println("Finished testCryptix");
396     }
397
398
399
400     private void testMessageDigest()
401     {
402         // No provider needs to be installed for this to work.
403         try
404         {
405             MessageDigest md = MessageDigest.getInstance("MD5");
406             byte[] data = "Paulas digest".getBytes();
407             byte[] digest = md.digest(data);
408             byte[] digest2 = md.digest(data);
409             if (byteArrayIdentical(digest,digest2,0,digest.length))
410                 System.out.println("PASSED");
411             else
412                 System.out.println("FAILED");
413
414             System.out.println("data length is " + data.length);
415             System.out.println("digest length is " + digest.length);
416             System.out.println("digest2 length is " + digest2.length);
417         }
418         catch (Throwable t)
419         {
420             System.out.println("got an exception");
421             t.printStackTrace();
422         }
423
424         System.out.println("Finished testBlowfish");
425     }
426
427     // PT
428     private void testPCBC()
429     {
430         System.out.println("Running testPCBC");
431         try
432         {
433             // set up the provider
434             Class jceClass = Class.forName("com.sun.crypto.provider.SunJCE");
435             java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
436             java.security.Security.addProvider(myProvider);
437             // java.security.Provider sunJce = new com.sun.crypto.provider.SunJCE();
438             // java.security.Security.addProvider(sunJce);
439
440             // String key = "Paula bla la da trish123 sdkfs;ldkg;sa'jlskjgklad";
441             String key = "PaulablaPaulablaPaulabla";
442             byte[] buf = key.getBytes();
443             System.out.println("key length is " + buf.length);
444             SecretKeySpec sKeySpec = new SecretKeySpec(buf,"DESede");
445
446             Cipher cipher = Cipher.getInstance("DESede/PCBC/NoPadding");
447             // Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
448             // Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
449             cipher.init(Cipher.ENCRYPT_MODE,sKeySpec);
450             // only works with NoPadding if size is a multiple of 8 bytes
451             // with PKCS5Padding, works for all sizes
452             byte[] original = "This is what should get encrypte".getBytes();
453             System.out.println("original length is " + original.length);
454             byte[] encrypted = cipher.doFinal(original);
455             // works
456             // AlgorithmParameters algParam = cipher.getParameters();
457             byte[] iv = cipher.getIV();
458             System.out.println("length of iv is " + iv.length);
459
460             Cipher cipher2 = Cipher.getInstance("DESede/PCBC/NoPadding");
461             // Cipher cipher2 = Cipher.getInstance("DESede/CBC/NoPadding");
462             // Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
463
464             // works
465             // cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,algParam);
466             IvParameterSpec ivClass = new IvParameterSpec(iv);
467             cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,ivClass);
468             byte[] decrypted = cipher2.doFinal(encrypted);
469
470             if (byteArrayIdentical(original,decrypted,0,original.length))
471                 System.out.println("PASSED");
472             else
473                 System.out.println("FAILED");
474
475             System.out.println("original length is " + original.length);
476             System.out.println("encrypted length is " + encrypted.length);
477             System.out.println("decrypted length is " + decrypted.length);
478         }
479         catch (Throwable t)
480         {
481             System.out.println("got an exception");
482             t.printStackTrace();
483         }
484
485         System.out.println("Finished testPCBC");
486     }
487
488
489     private void testPCBC2()
490     {
491         System.out.println("Running testPCBC2");
492         try
493         {
494             // set up the provider
495             Class jceClass = Class.forName("com.sun.crypto.provider.SunJCE");
496             java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
497             java.security.Security.addProvider(myProvider);
498
499             byte[] userkey = "a secreta secreta secret".getBytes();
500             System.out.println("userkey length is " + userkey.length);
501             Key secretKey = (Key) (new SecretKeySpec(userkey, "DESede"));
502             byte[] IV = "anivspec".getBytes();
503
504             Cipher enCipher = Cipher.getInstance("DESede/PCBC/NoPadding","SunJCE");
505             Cipher deCipher = Cipher.getInstance("DESede/PCBC/NoPadding","SunJCE");
506             IvParameterSpec ivspec = new IvParameterSpec(IV);
507
508             enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
509             deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
510
511             int patternLength = 24;
512             byte[] pattern = new byte[patternLength];
513             for (int i = 0; i < patternLength; i++)
514                 pattern[i] = (byte)(i & 0xFF);
515
516             byte[] cipherOutput1 = new byte[patternLength];
517             byte[] cipherOutput2 = new byte[patternLength];
518
519             int retval = 0;
520             retval = enCipher.doFinal(pattern, 0, 24, cipherOutput1, 0);
521
522             retval = deCipher.doFinal(cipherOutput1, 0, 24, cipherOutput2, 0);
523
524             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
525                 System.out.println("PASSED TEST 1");
526             else
527                 System.out.println("FAILED TEST 1");
528
529             retval = deCipher.doFinal(cipherOutput1, 0, 24, cipherOutput2, 0);
530
531             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
532                 System.out.println("PASSED TEST 2");
533             else
534                 System.out.println("FAILED TEST 2");
535         }
536         catch (Throwable t)
537         {
538             System.out.println("got an exception");
539             t.printStackTrace();
540         }
541
542         System.out.println("Finished testPCBC2");
543     }
544
545     private void testIAIK()
546     {
547         System.out.println("Running testIAIK");
548         try
549         {
550             // set up the provider
551             Class jceClass = Class.forName("iaik.security.provider.IAIK");
552             java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
553             java.security.Security.addProvider(myProvider);
554
555             // iaik.security.provider.IAIK.addAsProvider(true);
556
557             // iaik.utils.Util.loadClass("iaik.security.provider.IAIK",true);
558             // IAIK p=new IAIK();
559             // iaik.security.provider.IAIK.getMd5();
560
561             byte[] userkey = "a secret".getBytes();
562             System.out.println("userkey length is " + userkey.length);
563             Key secretKey = (Key) (new SecretKeySpec(userkey, "DES"));
564             byte[] IV = "anivspec".getBytes();
565
566             Cipher enCipher = Cipher.getInstance("DES/CBC/NoPadding","IAIK");
567             Cipher deCipher = Cipher.getInstance("DES/CBC/NoPadding","IAIK");
568             IvParameterSpec ivspec = new IvParameterSpec(IV);
569
570             enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
571             deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
572
573             int patternLength = 8;
574             byte[] pattern = new byte[patternLength];
575             for (int i = 0; i < patternLength; i++)
576                 pattern[i] = (byte)(i & 0xFF);
577
578             byte[] cipherOutput1 = new byte[patternLength];
579             byte[] cipherOutput2 = new byte[patternLength];
580
581             int retval = 0;
582             retval = enCipher.doFinal(pattern, 0, 8, cipherOutput1, 0);
583
584             retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
585
586             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
587                 System.out.println("PASSED TEST 1");
588             else
589                 System.out.println("FAILED TEST 1");
590
591             retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
592
593             if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
594                 System.out.println("PASSED TEST 2");
595             else
596                 System.out.println("FAILED TEST 2");
597         }
598         catch (Throwable t)
599         {
600             System.out.println("got an exception");
601             t.printStackTrace();
602         }
603
604         System.out.println("Finished testIAIK");
605     }
606
607     private void printByteArray(String name, byte[] array)
608     {
609         System.out.println("printing array " + name);
610         for (int i = 0; i < array.length; i++)
611             System.out.println("index " + i + " : " + array[i]);
612     }
613     */

614     
615     /**
616      * Delete a file in a Privileged block as these tests are
617      * run under the embedded engine code.
618      */

619     private void deleteFile(final File JavaDoc f)
620     {
621         AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
622             public Object JavaDoc run() {
623                 if (f.exists())
624                     f.delete();
625                 return null;
626             }
627         });
628     }
629 }
630
Popular Tags