1 /* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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 tests.security; 17 18 import dalvik.annotation.TestLevel; 19 import dalvik.annotation.TestTargetNew; 20 import dalvik.annotation.TestTargets; 21 import java.security.NoSuchAlgorithmException; 22 import java.security.SecureRandom; 23 import java.util.Arrays; 24 import junit.framework.TestCase; 25 public abstract class SecureRandomTest extends TestCase { 26 27 28 private final String algorithmName; 29 30 private int counter=0; 31 32 protected SecureRandomTest(String name) { 33 this.algorithmName = name; 34 } 35 36 protected void setUp() throws Exception { 37 super.setUp(); 38 } 39 40 @TestTargets({ 41 @TestTargetNew( 42 level=TestLevel.ADDITIONAL, 43 method="getInstance", 44 args={String.class} 45 ), 46 @TestTargetNew( 47 level=TestLevel.ADDITIONAL, 48 method="setSeed", 49 args={long.class} 50 ), 51 @TestTargetNew( 52 level=TestLevel.ADDITIONAL, 53 method="nextBytes", 54 args={byte[].class} 55 ), 56 @TestTargetNew( 57 level=TestLevel.COMPLETE, 58 method="method", 59 args={} 60 ) 61 }) 62 public void testSecureRandom() { 63 SecureRandom secureRandom1 = null; 64 try { 65 secureRandom1 = SecureRandom.getInstance(algorithmName); 66 } catch (NoSuchAlgorithmException e) { 67 fail(e.getMessage()); 68 } 69 70 SecureRandom secureRandom2 = null; 71 try { 72 secureRandom2 = SecureRandom.getInstance(algorithmName); 73 } catch (NoSuchAlgorithmException e) { 74 fail(e.getMessage()); 75 } 76 77 byte[] testRandom1 = getRandomBytes(secureRandom1); 78 byte[] testRandom2 = getRandomBytes(secureRandom2); 79 80 assertFalse(Arrays.equals(testRandom1, testRandom2)); 81 82 83 } 84 85 private byte[] getRandomBytes(SecureRandom random) { 86 byte[] randomData = new byte[64]; 87 88 random.setSeed(System.currentTimeMillis()+counter); 89 counter++; 90 91 random.nextBytes(randomData); 92 93 return randomData; 94 } 95 } 96