1 // Copyright 2023 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 //////////////////////////////////////////////////////////////////////////////// 16 17 package com.google.crypto.tink.internal; 18 19 import static com.google.common.truth.Truth.assertThat; 20 import static org.junit.Assert.assertThrows; 21 22 import com.google.crypto.tink.testing.TestUtil; 23 import java.security.GeneralSecurityException; 24 import java.util.ArrayList; 25 import org.junit.Test; 26 import org.junit.runner.RunWith; 27 import org.junit.runners.JUnit4; 28 29 @RunWith(JUnit4.class) 30 public final class RandomWithoutConscryptTest { 31 32 @Test validateUsesConscrypt_onlyWorksOnAndroid()33 public void validateUsesConscrypt_onlyWorksOnAndroid() throws Exception { 34 if (TestUtil.isAndroid()) { 35 // Android uses Conscrypt by default. 36 Random.validateUsesConscrypt(); 37 } else { 38 assertThrows(GeneralSecurityException.class, Random::validateUsesConscrypt); 39 } 40 } 41 42 @Test randBytes_works()43 public void randBytes_works() throws Exception { 44 assertThat(Random.randBytes(10)).hasLength(10); 45 } 46 47 @Test randIntWithMax_works()48 public void randIntWithMax_works() throws Exception { 49 assertThat(Random.randInt(5)).isLessThan(5); 50 } 51 52 @Test randInt_works()53 public void randInt_works() throws Exception { 54 int unused = Random.randInt(); 55 } 56 57 @Test randBytes_areDifferent()58 public void randBytes_areDifferent() throws Exception { 59 assertThat(Random.randBytes(10)).isNotEqualTo(Random.randBytes(10)); 60 } 61 62 @Test randdomBytesInDifferentThreads_areDifferent()63 public void randdomBytesInDifferentThreads_areDifferent() throws Exception { 64 ArrayList<Thread> threads = new ArrayList<>(); 65 final byte[] b0 = new byte[10]; 66 final byte[] b1 = new byte[10]; 67 threads.add( 68 new Thread() { 69 @Override 70 public void run() { 71 System.arraycopy(Random.randBytes(10), 0, b0, 0, 10); 72 } 73 }); 74 threads.add( 75 new Thread() { 76 @Override 77 public void run() { 78 System.arraycopy(Random.randBytes(10), 0, b1, 0, 10); 79 } 80 }); 81 for (Thread thread : threads) { 82 thread.start(); 83 } 84 for (Thread thread : threads) { 85 thread.join(); 86 } 87 assertThat(b0).isNotEqualTo(b1); 88 } 89 } 90