PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/projects/derby-10.9.1.0/db-derby-10.9.1.0-src/java/testing/org/apache/derbyTesting/unitTests/crypto/T_Cipher.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 629 lines | 180 code | 65 blank | 384 comment | 24 complexity | 940a1a2ccdab945051120a44a7bec4f6 MD5 | raw file
  1. /*
  2. Derby - Class org.apache.derbyTesting.unitTests.crypto.T_Cipher
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. */
  16. package org.apache.derbyTesting.unitTests.crypto;
  17. import org.apache.derbyTesting.unitTests.harness.T_Generic;
  18. import org.apache.derbyTesting.unitTests.harness.T_Fail;
  19. import org.apache.derby.iapi.services.crypto.*;
  20. import org.apache.derby.iapi.services.monitor.Monitor;
  21. import org.apache.derby.iapi.db.PropertyInfo;
  22. import org.apache.derby.iapi.error.StandardException;
  23. import java.security.AccessController;
  24. import java.security.Key;
  25. import java.security.PrivilegedAction;
  26. import java.security.PrivilegedExceptionAction;
  27. import java.io.File;
  28. import java.io.FileNotFoundException;
  29. import java.io.InputStream;
  30. import java.io.OutputStream;
  31. import java.io.FileInputStream;
  32. import java.io.FileOutputStream;
  33. import java.io.RandomAccessFile;
  34. import java.io.IOException;
  35. import java.util.Properties;
  36. /*
  37. // PT
  38. import javax.crypto.Cipher;
  39. import javax.crypto.spec.SecretKeySpec;
  40. import java.security.spec.KeySpec;
  41. import java.security.AlgorithmParameters;
  42. // import java.security.spec.AlgorithmParameterSpec;
  43. import javax.crypto.spec.IvParameterSpec;
  44. import java.security.GeneralSecurityException;
  45. import java.security.MessageDigest;
  46. import java.lang.reflect.*;
  47. */
  48. /*
  49. To run, put the following line in derby.properties
  50. derby.module.test.T_Cipher=org.apache.derbyTesting.unitTests.crypto.T_Cipher
  51. and run java org.apache.derbyTesting.unitTests.harness.UnitTestMain
  52. */
  53. public class T_Cipher extends T_Generic
  54. {
  55. private static final String testService = "CipherText";
  56. CipherProvider enEngine;
  57. CipherProvider deEngine;
  58. Key secretKey;
  59. byte[] IV;
  60. CipherFactory factory;
  61. public T_Cipher()
  62. {
  63. super();
  64. }
  65. /*
  66. ** Methods required by T_Generic
  67. */
  68. public String getModuleToTestProtocolName() {
  69. return org.apache.derby.iapi.reference.Module.CipherFactoryBuilder;
  70. }
  71. protected String getAlgorithm()
  72. {
  73. return "DES/CBC/NoPadding";
  74. }
  75. protected String getProvider()
  76. {
  77. // allow for alternate providers
  78. String testProvider =
  79. (String) AccessController.doPrivileged(new PrivilegedAction() {
  80. public Object run() {
  81. return System.getProperty("testEncryptionProvider");
  82. }
  83. });
  84. if (testProvider != null)
  85. return testProvider;
  86. else
  87. return null;
  88. }
  89. public void runTests() throws T_Fail {
  90. File testFile = new File("extinout/T_Cipher.data");
  91. deleteFile(testFile);
  92. String bootPassword = "a secret, don't tell anyone";
  93. try
  94. {
  95. RandomAccessFile file = new RandomAccessFile(testFile, "rw");
  96. setupCiphers(bootPassword);
  97. // run thru some in patterns
  98. int patternLength = 8192;
  99. byte[] pattern = new byte[patternLength];
  100. for (int i = 0; i < patternLength; i++)
  101. pattern[i] = (byte)(i & 0xFF);
  102. test(pattern, 0, 8, file); // test short patterns
  103. test(pattern, 8, 8, file);
  104. test(pattern, 1, 16, file);
  105. test(pattern, 0, patternLength, file); // test long pattern
  106. test(pattern, 0, patternLength/2, file);
  107. test(pattern, 1, patternLength/2, file);
  108. test(pattern, 2, patternLength/2, file);
  109. test(pattern, 3, patternLength/2, file);
  110. file.seek(0);
  111. check(pattern, 0, 8, file); // file offset 0
  112. check(pattern, 8, 8, file); // file offset 8
  113. check(pattern, 1, 16, file); // file offset 16
  114. check(pattern, 0, patternLength, file); // file offset 32
  115. check(pattern, 0, patternLength/2, file);// file offset 32+patternLength
  116. check(pattern, 1, patternLength/2, file);// file offset 32+patternLength+(patternLength/2)
  117. check(pattern, 2, patternLength/2, file);// file offset 32+(2*patternLength)
  118. check(pattern, 3, patternLength/2, file);// file offset 32+(2*patternLength)+(patternLength/2);
  119. REPORT("starting random test");
  120. // now do some random testing from file
  121. file.seek(32+patternLength);
  122. check(pattern, 0, patternLength/2, file);
  123. file.seek(32);
  124. check(pattern, 0, patternLength, file);
  125. file.seek(32+(2*patternLength));
  126. check(pattern, 2, patternLength/2, file);
  127. file.seek(0);
  128. check(pattern, 0, 8, file);
  129. file.seek(16);
  130. check(pattern, 1, 16, file);
  131. file.seek(32+(2*patternLength)+(patternLength/2));
  132. check(pattern, 3, patternLength/2, file);
  133. file.seek(8);
  134. check(pattern, 8, 8, file);
  135. file.seek(32+patternLength+(patternLength/2));
  136. check(pattern, 1, patternLength/2, file);
  137. file.close();
  138. }
  139. catch (StandardException se)
  140. {
  141. se.printStackTrace(System.out);
  142. throw T_Fail.exceptionFail(se);
  143. }
  144. catch (IOException ioe)
  145. {
  146. throw T_Fail.exceptionFail(ioe);
  147. }
  148. PASS("T_Cipher");
  149. }
  150. protected void setupCiphers(String bootPassword) throws T_Fail, StandardException
  151. {
  152. // set properties for testing
  153. Properties props = new Properties();
  154. props.put("encryptionAlgorithm",getAlgorithm());
  155. String provider = getProvider();
  156. if (provider != null)
  157. props.put("encryptionProvider",getProvider());
  158. props.put("bootPassword", bootPassword);
  159. REPORT("encryption algorithm used : " + getAlgorithm());
  160. REPORT("encryption provider used : " + provider);
  161. CipherFactoryBuilder cb = (CipherFactoryBuilder)
  162. Monitor.startSystemModule(org.apache.derby.iapi.reference.Module.CipherFactoryBuilder);
  163. factory = cb.createCipherFactory(true, props, false);
  164. if (factory == null)
  165. throw T_Fail.testFailMsg("cannot find Cipher factory ");
  166. enEngine = factory.createNewCipher(CipherFactory.ENCRYPT);
  167. deEngine = factory.createNewCipher(CipherFactory.DECRYPT);
  168. if (enEngine == null)
  169. throw T_Fail.testFailMsg("cannot create encryption engine");
  170. if (deEngine == null)
  171. throw T_Fail.testFailMsg("cannot create decryption engine");
  172. }
  173. protected void test(byte[] cleartext, int offset, int length,
  174. RandomAccessFile outfile)
  175. throws T_Fail, StandardException, IOException
  176. {
  177. byte[] ciphertext = new byte[length];
  178. System.arraycopy(cleartext, offset, ciphertext, 0, length);
  179. if (enEngine.encrypt(ciphertext, 0, length, ciphertext, 0) != length)
  180. throw T_Fail.testFailMsg("encrypted text length != length");
  181. if (byteArrayIdentical(ciphertext, cleartext, offset, length))
  182. throw T_Fail.testFailMsg("encryption just made a copy of the clear text");
  183. outfile.write(ciphertext);
  184. // now decrypt it and check
  185. deEngine.decrypt(ciphertext, 0, length, ciphertext, 0);
  186. if (byteArrayIdentical(ciphertext, cleartext, offset, length) == false)
  187. throw T_Fail.testFailMsg("decryption did not yield the same clear text");
  188. }
  189. protected void check(byte[] cleartext, int offset, int length,
  190. RandomAccessFile infile)
  191. throws IOException, T_Fail, StandardException
  192. {
  193. byte[] ciphertext = new byte[length];
  194. infile.read(ciphertext);
  195. if (deEngine.decrypt(ciphertext, 0, length, ciphertext, 0) != length)
  196. throw T_Fail.testFailMsg("decrypted text length != length");
  197. if (byteArrayIdentical(ciphertext, cleartext, offset, length) == false)
  198. throw T_Fail.testFailMsg("decryption did not yield the same clear text");
  199. }
  200. // see if 2 byte arrays are identical
  201. protected boolean byteArrayIdentical(byte[] compare, byte[] original,
  202. int offset, int length)
  203. {
  204. for (int i = 0; i < length; i++)
  205. {
  206. if (compare[i] != original[offset+i])
  207. return false;
  208. }
  209. return true;
  210. }
  211. /*
  212. private void testBlowfish()
  213. {
  214. System.out.println("Running testBlowfish");
  215. try
  216. {
  217. // set up the provider
  218. java.security.Provider sunJce = new com.sun.crypto.provider.SunJCE();
  219. java.security.Security.addProvider(sunJce);
  220. // String key = "Paula bla la da trish123 sdkfs;ldkg;sa'jlskjgklad";
  221. String key = "Paulabla123456789012345";
  222. byte[] buf = key.getBytes();
  223. System.out.println("key length is " + buf.length);
  224. SecretKeySpec sKeySpec = new SecretKeySpec(buf,"Blowfish");
  225. // SecretKeySpec sKeySpec = new SecretKeySpec(buf,"DESede");
  226. Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
  227. // Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
  228. // Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
  229. cipher.init(Cipher.ENCRYPT_MODE,sKeySpec);
  230. // only works with NoPadding if size is a multiple of 8 bytes
  231. // with PKCS5Padding, works for all sizes
  232. byte[] original = "This is what should get encrypte".getBytes();
  233. System.out.println("original length is " + original.length);
  234. byte[] encrypted = cipher.doFinal(original);
  235. // works
  236. // AlgorithmParameters algParam = cipher.getParameters();
  237. byte[] iv = cipher.getIV();
  238. System.out.println("length of iv is " + iv.length);
  239. Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/NoPadding");
  240. // Cipher cipher2 = Cipher.getInstance("DESede/CBC/NoPadding");
  241. // Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
  242. // works
  243. // cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,algParam);
  244. IvParameterSpec ivClass = new IvParameterSpec(iv);
  245. cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,ivClass);
  246. byte[] decrypted = cipher2.doFinal(encrypted);
  247. if (byteArrayIdentical(original,decrypted,0,original.length))
  248. System.out.println("PASSED");
  249. else
  250. System.out.println("FAILED");
  251. System.out.println("original length is " + original.length);
  252. System.out.println("encrypted length is " + encrypted.length);
  253. System.out.println("decrypted length is " + decrypted.length);
  254. }
  255. catch (Throwable t)
  256. {
  257. System.out.println("got an exception");
  258. t.printStackTrace();
  259. }
  260. System.out.println("Finished testBlowfish");
  261. }
  262. private void testCryptix()
  263. {
  264. System.out.println("Running testCryptix");
  265. try
  266. {
  267. // set up the provider
  268. Class jceClass = Class.forName("cryptix.jce.provider.Cryptix");
  269. java.security.Provider cryptixProvider = (java.security.Provider) jceClass.newInstance();
  270. java.security.Security.addProvider(cryptixProvider);
  271. byte[] userkey = "a secret".getBytes();
  272. System.out.println("userkey length is " + userkey.length);
  273. Key secretKey = (Key) (new SecretKeySpec(userkey, "DES"));
  274. byte[] IV = "anivspec".getBytes();
  275. Cipher enCipher = Cipher.getInstance("DES/CBC/NoPadding","Cryptix");
  276. Cipher deCipher = Cipher.getInstance("DES/CBC/NoPadding","Cryptix");
  277. IvParameterSpec ivspec = new IvParameterSpec(IV);
  278. enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
  279. deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
  280. int patternLength = 8;
  281. byte[] pattern = new byte[patternLength];
  282. for (int i = 0; i < patternLength; i++)
  283. pattern[i] = (byte)(i & 0xFF);
  284. byte[] cipherOutput1 = new byte[patternLength];
  285. byte[] cipherOutput2 = new byte[patternLength];
  286. int retval = 0;
  287. retval = enCipher.doFinal(pattern, 0, 8, cipherOutput1, 0);
  288. retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
  289. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  290. System.out.println("PASSED TEST 1");
  291. else
  292. System.out.println("FAILED TEST 1");
  293. retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
  294. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  295. System.out.println("PASSED TEST 2");
  296. else
  297. System.out.println("FAILED TEST 2");
  298. }
  299. catch (Throwable t)
  300. {
  301. System.out.println("got an exception");
  302. t.printStackTrace();
  303. }
  304. System.out.println("Finished testCryptix");
  305. }
  306. private void testMessageDigest()
  307. {
  308. // No provider needs to be installed for this to work.
  309. try
  310. {
  311. MessageDigest md = MessageDigest.getInstance("MD5");
  312. byte[] data = "Paulas digest".getBytes();
  313. byte[] digest = md.digest(data);
  314. byte[] digest2 = md.digest(data);
  315. if (byteArrayIdentical(digest,digest2,0,digest.length))
  316. System.out.println("PASSED");
  317. else
  318. System.out.println("FAILED");
  319. System.out.println("data length is " + data.length);
  320. System.out.println("digest length is " + digest.length);
  321. System.out.println("digest2 length is " + digest2.length);
  322. }
  323. catch (Throwable t)
  324. {
  325. System.out.println("got an exception");
  326. t.printStackTrace();
  327. }
  328. System.out.println("Finished testBlowfish");
  329. }
  330. // PT
  331. private void testPCBC()
  332. {
  333. System.out.println("Running testPCBC");
  334. try
  335. {
  336. // set up the provider
  337. Class jceClass = Class.forName("com.sun.crypto.provider.SunJCE");
  338. java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
  339. java.security.Security.addProvider(myProvider);
  340. // java.security.Provider sunJce = new com.sun.crypto.provider.SunJCE();
  341. // java.security.Security.addProvider(sunJce);
  342. // String key = "Paula bla la da trish123 sdkfs;ldkg;sa'jlskjgklad";
  343. String key = "PaulablaPaulablaPaulabla";
  344. byte[] buf = key.getBytes();
  345. System.out.println("key length is " + buf.length);
  346. SecretKeySpec sKeySpec = new SecretKeySpec(buf,"DESede");
  347. Cipher cipher = Cipher.getInstance("DESede/PCBC/NoPadding");
  348. // Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
  349. // Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
  350. cipher.init(Cipher.ENCRYPT_MODE,sKeySpec);
  351. // only works with NoPadding if size is a multiple of 8 bytes
  352. // with PKCS5Padding, works for all sizes
  353. byte[] original = "This is what should get encrypte".getBytes();
  354. System.out.println("original length is " + original.length);
  355. byte[] encrypted = cipher.doFinal(original);
  356. // works
  357. // AlgorithmParameters algParam = cipher.getParameters();
  358. byte[] iv = cipher.getIV();
  359. System.out.println("length of iv is " + iv.length);
  360. Cipher cipher2 = Cipher.getInstance("DESede/PCBC/NoPadding");
  361. // Cipher cipher2 = Cipher.getInstance("DESede/CBC/NoPadding");
  362. // Cipher cipher2 = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
  363. // works
  364. // cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,algParam);
  365. IvParameterSpec ivClass = new IvParameterSpec(iv);
  366. cipher2.init(Cipher.DECRYPT_MODE,sKeySpec,ivClass);
  367. byte[] decrypted = cipher2.doFinal(encrypted);
  368. if (byteArrayIdentical(original,decrypted,0,original.length))
  369. System.out.println("PASSED");
  370. else
  371. System.out.println("FAILED");
  372. System.out.println("original length is " + original.length);
  373. System.out.println("encrypted length is " + encrypted.length);
  374. System.out.println("decrypted length is " + decrypted.length);
  375. }
  376. catch (Throwable t)
  377. {
  378. System.out.println("got an exception");
  379. t.printStackTrace();
  380. }
  381. System.out.println("Finished testPCBC");
  382. }
  383. private void testPCBC2()
  384. {
  385. System.out.println("Running testPCBC2");
  386. try
  387. {
  388. // set up the provider
  389. Class jceClass = Class.forName("com.sun.crypto.provider.SunJCE");
  390. java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
  391. java.security.Security.addProvider(myProvider);
  392. byte[] userkey = "a secreta secreta secret".getBytes();
  393. System.out.println("userkey length is " + userkey.length);
  394. Key secretKey = (Key) (new SecretKeySpec(userkey, "DESede"));
  395. byte[] IV = "anivspec".getBytes();
  396. Cipher enCipher = Cipher.getInstance("DESede/PCBC/NoPadding","SunJCE");
  397. Cipher deCipher = Cipher.getInstance("DESede/PCBC/NoPadding","SunJCE");
  398. IvParameterSpec ivspec = new IvParameterSpec(IV);
  399. enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
  400. deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
  401. int patternLength = 24;
  402. byte[] pattern = new byte[patternLength];
  403. for (int i = 0; i < patternLength; i++)
  404. pattern[i] = (byte)(i & 0xFF);
  405. byte[] cipherOutput1 = new byte[patternLength];
  406. byte[] cipherOutput2 = new byte[patternLength];
  407. int retval = 0;
  408. retval = enCipher.doFinal(pattern, 0, 24, cipherOutput1, 0);
  409. retval = deCipher.doFinal(cipherOutput1, 0, 24, cipherOutput2, 0);
  410. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  411. System.out.println("PASSED TEST 1");
  412. else
  413. System.out.println("FAILED TEST 1");
  414. retval = deCipher.doFinal(cipherOutput1, 0, 24, cipherOutput2, 0);
  415. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  416. System.out.println("PASSED TEST 2");
  417. else
  418. System.out.println("FAILED TEST 2");
  419. }
  420. catch (Throwable t)
  421. {
  422. System.out.println("got an exception");
  423. t.printStackTrace();
  424. }
  425. System.out.println("Finished testPCBC2");
  426. }
  427. private void testIAIK()
  428. {
  429. System.out.println("Running testIAIK");
  430. try
  431. {
  432. // set up the provider
  433. Class jceClass = Class.forName("iaik.security.provider.IAIK");
  434. java.security.Provider myProvider = (java.security.Provider) jceClass.newInstance();
  435. java.security.Security.addProvider(myProvider);
  436. // iaik.security.provider.IAIK.addAsProvider(true);
  437. // iaik.utils.Util.loadClass("iaik.security.provider.IAIK",true);
  438. // IAIK p=new IAIK();
  439. // iaik.security.provider.IAIK.getMd5();
  440. byte[] userkey = "a secret".getBytes();
  441. System.out.println("userkey length is " + userkey.length);
  442. Key secretKey = (Key) (new SecretKeySpec(userkey, "DES"));
  443. byte[] IV = "anivspec".getBytes();
  444. Cipher enCipher = Cipher.getInstance("DES/CBC/NoPadding","IAIK");
  445. Cipher deCipher = Cipher.getInstance("DES/CBC/NoPadding","IAIK");
  446. IvParameterSpec ivspec = new IvParameterSpec(IV);
  447. enCipher.init(Cipher.ENCRYPT_MODE,secretKey,ivspec);
  448. deCipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
  449. int patternLength = 8;
  450. byte[] pattern = new byte[patternLength];
  451. for (int i = 0; i < patternLength; i++)
  452. pattern[i] = (byte)(i & 0xFF);
  453. byte[] cipherOutput1 = new byte[patternLength];
  454. byte[] cipherOutput2 = new byte[patternLength];
  455. int retval = 0;
  456. retval = enCipher.doFinal(pattern, 0, 8, cipherOutput1, 0);
  457. retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
  458. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  459. System.out.println("PASSED TEST 1");
  460. else
  461. System.out.println("FAILED TEST 1");
  462. retval = deCipher.doFinal(cipherOutput1, 0, 8, cipherOutput2, 0);
  463. if (byteArrayIdentical(cipherOutput2,pattern,0,patternLength))
  464. System.out.println("PASSED TEST 2");
  465. else
  466. System.out.println("FAILED TEST 2");
  467. }
  468. catch (Throwable t)
  469. {
  470. System.out.println("got an exception");
  471. t.printStackTrace();
  472. }
  473. System.out.println("Finished testIAIK");
  474. }
  475. private void printByteArray(String name, byte[] array)
  476. {
  477. System.out.println("printing array " + name);
  478. for (int i = 0; i < array.length; i++)
  479. System.out.println("index " + i + " : " + array[i]);
  480. }
  481. */
  482. /**
  483. * Delete a file in a Privileged block as these tests are
  484. * run under the embedded engine code.
  485. */
  486. private void deleteFile(final File f)
  487. {
  488. AccessController.doPrivileged(new PrivilegedAction() {
  489. public Object run() {
  490. if (f.exists())
  491. f.delete();
  492. return null;
  493. }
  494. });
  495. }
  496. }