PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/libcore/luni/src/test/java/org/apache/harmony/security/tests/java/security/SecureRandom2Test.java

https://gitlab.com/cde/debian_android-tools_android-framework-23
Java | 409 lines | 245 code | 65 blank | 99 comment | 7 complexity | 4142ce57271cb14070b1bed9ea57fe07 MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package org.apache.harmony.security.tests.java.security;
  18. import java.security.NoSuchAlgorithmException;
  19. import java.security.NoSuchProviderException;
  20. import java.security.Provider;
  21. import java.security.SecureRandom;
  22. import java.security.SecureRandomSpi;
  23. import java.security.Security;
  24. import junit.framework.TestCase;
  25. public class SecureRandom2Test extends TestCase {
  26. private static final byte[] SEED_BYTES = { (byte) 33, (byte) 15, (byte) -3,
  27. (byte) 22, (byte) 77, (byte) -16, (byte) -33, (byte) 56 };
  28. private static final int SEED_SIZE = 539;
  29. private static final long SEED_VALUE = 5335486759L;
  30. public void testGetProvider() {
  31. SecureRandom sr1 = new SecureRandom();
  32. assertNotNull(sr1.getProvider());
  33. SecureRandom sr2 = new SecureRandom(SEED_BYTES);
  34. assertNotNull(sr2.getProvider());
  35. MyProvider p = new MyProvider();
  36. MySecureRandom sr3 = new MySecureRandom(new MySecureRandomSpi(), p);
  37. assertEquals(p, sr3.getProvider());
  38. try {
  39. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  40. assertNotNull(random.getProvider());
  41. } catch (NoSuchAlgorithmException e) {
  42. fail("Unexpected NoSuchAlgorithmException");
  43. }
  44. }
  45. /**
  46. * java.security.SecureRandom#SecureRandom()
  47. */
  48. public void test_Constructor() {
  49. // Test for method java.security.SecureRandom()
  50. try {
  51. new SecureRandom();
  52. } catch (Exception e) {
  53. fail("Constructor threw exception : " + e);
  54. }
  55. }
  56. /**
  57. * java.security.SecureRandom#SecureRandom(byte[])
  58. */
  59. public void test_Constructor$B() {
  60. // Test for method java.security.SecureRandom(byte [])
  61. try {
  62. new SecureRandom(SEED_BYTES);
  63. } catch (Exception e) {
  64. fail("Constructor threw exception : " + e);
  65. }
  66. try {
  67. new SecureRandom(null);
  68. fail("NullPointerException was not thrown for NULL parameter");
  69. } catch (NullPointerException e) {
  70. //expected
  71. }
  72. }
  73. /**
  74. * java.security.SecureRandom#SecureRandom(java.security.SecureRandomSpi, java.security.Provider)
  75. */
  76. public void test_ConstructorLjava_security_SecureRandomSpi_java_security_Provider() {
  77. try {
  78. new MySecureRandom(null, null);
  79. } catch (Exception e) {
  80. fail("Constructor threw exception : " + e);
  81. }
  82. try {
  83. MyProvider p = new MyProvider();
  84. MySecureRandom sr = new MySecureRandom(new MySecureRandomSpi(), p);
  85. assertEquals("unknown", sr.getAlgorithm());
  86. assertEquals(p, sr.getProvider());
  87. sr = new MySecureRandom(new MySecureRandomSpi(), null);
  88. sr = new MySecureRandom(null, p);
  89. } catch (Exception e) {
  90. fail("Constructor threw exception : " + e);
  91. }
  92. }
  93. /**
  94. * java.security.SecureRandom#generateSeed(int)
  95. */
  96. public void test_generateSeedI() {
  97. // Test for method byte [] java.security.SecureRandom.generateSeed(int)
  98. byte[] seed = new SecureRandom().generateSeed(SEED_SIZE);
  99. assertEquals("seed has incorrect size", SEED_SIZE, seed.length);
  100. try {
  101. new SecureRandom().generateSeed(-42);
  102. fail("expected an exception");
  103. } catch (Exception e) {
  104. // ok
  105. }
  106. }
  107. /**
  108. * java.security.SecureRandom#getInstance(java.lang.String)
  109. */
  110. public void test_getInstanceLjava_lang_String() {
  111. // Test for method java.security.SecureRandom
  112. // java.security.SecureRandom.getInstance(java.lang.String)
  113. try {
  114. SecureRandom.getInstance("SHA1PRNG");
  115. } catch (NoSuchAlgorithmException e) {
  116. fail("getInstance did not find a SHA1PRNG algorithm");
  117. }
  118. try {
  119. SecureRandom.getInstance("MD2");
  120. fail("NoSuchAlgorithmException should be thrown for MD2 algorithm");
  121. } catch (NoSuchAlgorithmException e) {
  122. //expected
  123. }
  124. }
  125. /**
  126. * java.security.SecureRandom#getInstance(java.lang.String, java.lang.String)
  127. */
  128. public void test_getInstanceLjava_lang_StringLjava_lang_String() {
  129. // Test for method java.security.SecureRandom
  130. // java.security.SecureRandom.getInstance(java.lang.String,
  131. // java.lang.String)
  132. try {
  133. Provider[] providers = Security
  134. .getProviders("SecureRandom.SHA1PRNG");
  135. if (providers != null) {
  136. for (int i = 0; i < providers.length; i++) {
  137. SecureRandom
  138. .getInstance("SHA1PRNG", providers[i].getName());
  139. }// end for
  140. } else {
  141. fail("No providers support SHA1PRNG");
  142. }
  143. } catch (NoSuchAlgorithmException e) {
  144. fail("getInstance did not find a SHA1PRNG algorithm");
  145. } catch (NoSuchProviderException e) {
  146. fail("getInstance did not find the provider for SHA1PRNG");
  147. }
  148. }
  149. /**
  150. * java.security.SecureRandom#getSeed(int)
  151. */
  152. public void test_getSeedI() {
  153. // Test for method byte [] java.security.SecureRandom.getSeed(int)
  154. byte[] seed = SecureRandom.getSeed(SEED_SIZE);
  155. assertEquals("seed has incorrect size", SEED_SIZE, seed.length);
  156. try {
  157. new SecureRandom().getSeed(-42);
  158. fail("expected an exception");
  159. } catch (Exception e) {
  160. // ok
  161. }
  162. }
  163. /**
  164. * java.security.SecureRandom#nextBytes(byte[])
  165. */
  166. public void test_nextBytes$B() {
  167. // Test for method void java.security.SecureRandom.nextBytes(byte [])
  168. byte[] bytes = new byte[313];
  169. try {
  170. new SecureRandom().nextBytes(bytes);
  171. } catch (Exception e) {
  172. fail("next bytes not ok : " + e);
  173. }
  174. try {
  175. new SecureRandom().nextBytes(null);
  176. fail("expected exception");
  177. } catch (Exception e) {
  178. // ok
  179. }
  180. }
  181. /**
  182. * java.security.SecureRandom#setSeed(byte[])
  183. */
  184. public void test_setSeed$B() {
  185. // Test for method void java.security.SecureRandom.setSeed(byte [])
  186. try {
  187. new SecureRandom().setSeed(SEED_BYTES);
  188. } catch (Exception e) {
  189. fail("seed generation with bytes failed : " + e);
  190. }
  191. try {
  192. new SecureRandom().setSeed(null);
  193. fail("expected exception");
  194. } catch (Exception e) {
  195. // ok
  196. }
  197. }
  198. /**
  199. * java.security.SecureRandom#setSeed(long)
  200. */
  201. public void test_setSeedJ() {
  202. // Test for method void java.security.SecureRandom.setSeed(long)
  203. try {
  204. new SecureRandom().setSeed(SEED_VALUE);
  205. } catch (Exception e) {
  206. fail("seed generation with long failed : " + e);
  207. }
  208. try {
  209. new SecureRandom().setSeed(-1);
  210. } catch (Exception e) {
  211. fail("unexpected exception: " + e);
  212. }
  213. }
  214. /**
  215. * java.security.SecureRandom#getAlgorithm()
  216. */
  217. public void test_getAlgorithm() {
  218. // Regression for HARMONY-750
  219. SecureRandomSpi spi = new SecureRandomSpi() {
  220. protected void engineSetSeed(byte[] arg) {
  221. }
  222. protected void engineNextBytes(byte[] arg) {
  223. }
  224. protected byte[] engineGenerateSeed(int arg) {
  225. return null;
  226. }
  227. };
  228. SecureRandom sr = new SecureRandom(spi, null) {
  229. };
  230. assertEquals("unknown", sr.getAlgorithm());
  231. }
  232. // Regression Test for HARMONY-3552.
  233. public void test_nextJ() throws Exception {
  234. MySecureRandom mySecureRandom = new MySecureRandom(
  235. new MySecureRandomSpi(), null);
  236. int numBits = 29;
  237. int random = mySecureRandom.getNext(numBits);
  238. assertEquals(numBits, Integer.bitCount(random));
  239. numBits = 0;
  240. random = mySecureRandom.getNext(numBits);
  241. assertEquals(numBits, Integer.bitCount(random));
  242. numBits = 40;
  243. random = mySecureRandom.getNext(numBits);
  244. assertEquals(32, Integer.bitCount(random));
  245. numBits = -1;
  246. random = mySecureRandom.getNext(numBits);
  247. assertEquals(0, Integer.bitCount(random));
  248. }
  249. /**
  250. * Two {@link SecureRandom} objects, created with
  251. * {@link SecureRandom#getInstance(String)} and initialized before use
  252. * with the same seed, should return the same results.<p>
  253. *
  254. * In the future, it may sense to disallow seeding {@code SecureRandom},
  255. * as it tends to be error prone and open up security holes.
  256. * See {@link SecureRandom} for more details about insecure seeding.
  257. *
  258. * Note that this only works with the Harmony "Crypto" provider.
  259. */
  260. public void testSameSeedGeneratesSameResults() throws Exception {
  261. byte[] seed1 = { 'a', 'b', 'c' };
  262. SecureRandom sr1 = SecureRandom.getInstance("SHA1PRNG", "Crypto");
  263. sr1.setSeed(seed1);
  264. byte[] seed2 = { 'a', 'b', 'c' };
  265. SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG", "Crypto");
  266. sr2.setSeed(seed2);
  267. assertTrue(sr1.nextLong() == sr2.nextLong());
  268. }
  269. /**
  270. * Assert that a {@link SecureRandom} object seeded from a constant
  271. * seed always returns the same value, even across VM restarts.
  272. *
  273. * Future versions of Android may change the implementation of
  274. * SHA1PRNG, so users of {@code SecureRandom} should not assume
  275. * the same seed will always produce the same value. This test
  276. * is not a guarantee of future compatibility.
  277. *
  278. * In fact, this test only works with the Harmony "Crypto" provider.
  279. */
  280. public void testAlwaysSameValueWithSameSeed() throws Exception {
  281. byte[] seed1 = { 'a', 'b', 'c' };
  282. SecureRandom sr1 = SecureRandom.getInstance("SHA1PRNG", "Crypto");
  283. sr1.setSeed(seed1);
  284. // This long value has no special meaning and may change in the future.
  285. assertEquals(6180693691264871500l, sr1.nextLong());
  286. }
  287. /**
  288. * Validate that calling {@link SecureRandom#setSeed} <b>after</b> generating
  289. * a random number compliments, but doesn't replace, the existing seed.
  290. *
  291. * Compare this test to {@link #testAlwaysSameValueWithSameSeed()}.
  292. */
  293. public void testSetSeedComplimentsAfterFirstRandomNumber() throws Exception {
  294. byte[] seed1 = { 'a', 'b', 'c' };
  295. SecureRandom sr1 = SecureRandom.getInstance("SHA1PRNG");
  296. sr1.nextInt();
  297. sr1.setSeed(seed1);
  298. // This long value has no special meaning
  299. assertTrue(6180693691264871500l != sr1.nextLong());
  300. }
  301. class MySecureRandom extends SecureRandom {
  302. private static final long serialVersionUID = 1L;
  303. public MySecureRandom(SecureRandomSpi secureRandomSpi, Provider provider) {
  304. super(secureRandomSpi, provider);
  305. }
  306. public int getNext(int numBits) {
  307. return super.next(numBits);
  308. }
  309. }
  310. class MySecureRandomSpi extends SecureRandomSpi {
  311. private static final long serialVersionUID = 1L;
  312. @Override
  313. protected byte[] engineGenerateSeed(int arg0) {
  314. return null;
  315. }
  316. @Override
  317. protected void engineNextBytes(byte[] bytes) {
  318. for (int i = 0; i < bytes.length; i++) {
  319. bytes[i] = (byte) 0xFF;
  320. }
  321. }
  322. @Override
  323. protected void engineSetSeed(byte[] arg0) {
  324. return;
  325. }
  326. }
  327. class MyProvider extends Provider {
  328. MyProvider() {
  329. super("MyProvider", 1.0, "Provider for testing");
  330. put("MessageDigest.SHA-1", "SomeClassName");
  331. put("MessageDigest.abc", "SomeClassName");
  332. put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
  333. }
  334. MyProvider(String name, double version, String info) {
  335. super(name, version, info);
  336. }
  337. public void putService(Provider.Service s) {
  338. super.putService(s);
  339. }
  340. public void removeService(Provider.Service s) {
  341. super.removeService(s);
  342. }
  343. }
  344. }