Skip to content

Commit

Permalink
If available, use Conscrypt generate randomness.
Browse files Browse the repository at this point in the history
Also, we want to provide an additional internal function "validateUsesConscrypt" that lets us enforce to only use Conscrypt to generate randomness. For this, we move the "Random" class to internal, and add this function. The subtle class forwards calls to the internal class.

PiperOrigin-RevId: 545581282
Change-Id: I7af7112154e4d9db204446568dd75880f921ec8c
  • Loading branch information
juergw authored and copybara-github committed Jul 5, 2023
1 parent 49f2aed commit 6409bba
Show file tree
Hide file tree
Showing 10 changed files with 379 additions and 21 deletions.
2 changes: 2 additions & 0 deletions BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ gen_maven_jar_rules(
"//src/main/java/com/google/crypto/tink/internal:private_key_type_manager",
"//src/main/java/com/google/crypto/tink/internal:proto_key_serialization",
"//src/main/java/com/google/crypto/tink/internal:proto_parameters_serialization",
"//src/main/java/com/google/crypto/tink/internal:random",
"//src/main/java/com/google/crypto/tink/internal:registry_configuration",
"//src/main/java/com/google/crypto/tink/internal:serialization",
"//src/main/java/com/google/crypto/tink/internal:serialization_registry",
Expand Down Expand Up @@ -626,6 +627,7 @@ gen_maven_jar_rules(
"//src/main/java/com/google/crypto/tink/internal:private_key_type_manager-android",
"//src/main/java/com/google/crypto/tink/internal:proto_key_serialization-android",
"//src/main/java/com/google/crypto/tink/internal:proto_parameters_serialization-android",
"//src/main/java/com/google/crypto/tink/internal:random-android",
"//src/main/java/com/google/crypto/tink/internal:registry_configuration-android",
"//src/main/java/com/google/crypto/tink/internal:serialization-android",
"//src/main/java/com/google/crypto/tink/internal:serialization_registry-android",
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/google/crypto/tink/internal/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -738,3 +738,13 @@ java_library(
"@maven//:com_google_errorprone_error_prone_annotations",
],
)

java_library(
name = "random",
srcs = ["Random.java"],
)

android_library(
name = "random-android",
srcs = ["Random.java"],
)
87 changes: 87 additions & 0 deletions src/main/java/com/google/crypto/tink/internal/Random.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package com.google.crypto.tink.internal;

import java.security.GeneralSecurityException;
import java.security.SecureRandom;

/** Provides secure randomness using {@link SecureRandom}. */
public final class Random {
private static final ThreadLocal<SecureRandom> localRandom =
new ThreadLocal<SecureRandom>() {
@Override
protected SecureRandom initialValue() {
return newDefaultSecureRandom();
}
};

private static SecureRandom create() {
// Use Conscrypt if possible. Conscrypt may have three different provider names.
// For legacy compatibility reasons it uses the algorithm name "SHA1PRNG".
try {
return SecureRandom.getInstance("SHA1PRNG", "GmsCore_OpenSSL");
} catch (GeneralSecurityException e) {
// ignore
}
try {
return SecureRandom.getInstance("SHA1PRNG", "AndroidOpenSSL");
} catch (GeneralSecurityException e) {
// ignore
}
try {
return SecureRandom.getInstance("SHA1PRNG", "Conscrypt");
} catch (GeneralSecurityException e) {
// ignore
}
return new SecureRandom();
}

private static SecureRandom newDefaultSecureRandom() {
SecureRandom retval = create();
retval.nextLong(); // force seeding
return retval;
}

/** Returns a random byte array of size {@code size}. */
public static byte[] randBytes(int size) {
byte[] rand = new byte[size];
localRandom.get().nextBytes(rand);
return rand;
}

public static final int randInt(int max) {
return localRandom.get().nextInt(max);
}

public static final int randInt() {
return localRandom.get().nextInt();
}

/** Throws a GeneralSecurityException if the provider is not Conscrypt. */
public static final void validateUsesConscrypt() throws GeneralSecurityException {
String providerName = localRandom.get().getProvider().getName();
if (!providerName.equals("GmsCore_OpenSSL")
&& !providerName.equals("AndroidOpenSSL")
&& !providerName.equals("Conscrypt")) {
throw new GeneralSecurityException(
"Requires GmsCore_OpenSSL, AndroidOpenSSL or Conscrypt to generate randomness, but got "
+ providerName);
}
}

private Random() {}
}
2 changes: 2 additions & 0 deletions src/main/java/com/google/crypto/tink/subtle/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ java_library(
java_library(
name = "random",
srcs = ["Random.java"],
deps = ["//src/main/java/com/google/crypto/tink/internal:random"],
)

java_library(
Expand Down Expand Up @@ -862,6 +863,7 @@ android_library(
android_library(
name = "random-android",
srcs = ["Random.java"],
deps = ["//src/main/java/com/google/crypto/tink/internal:random-android"],
)

android_library(
Expand Down
28 changes: 7 additions & 21 deletions src/main/java/com/google/crypto/tink/subtle/Random.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,40 +16,26 @@

package com.google.crypto.tink.subtle;

import java.security.SecureRandom;

/**
* A simple wrapper of {@link SecureRandom}.
* Provides secure randomness using {@link SecureRandom}.
*
* @since 1.0.0
*/
public final class Random {
private static final ThreadLocal<SecureRandom> localRandom = new ThreadLocal<SecureRandom>() {
@Override
protected SecureRandom initialValue() {
return newDefaultSecureRandom();
}
};

private static SecureRandom newDefaultSecureRandom() {
SecureRandom retval = new SecureRandom();
retval.nextLong(); // force seeding
return retval;
}

/** @return a random byte array of size {@code size}. */
/** Returns a random byte array of size {@code size}. */
public static byte[] randBytes(int size) {
byte[] rand = new byte[size];
localRandom.get().nextBytes(rand);
return rand;
return com.google.crypto.tink.internal.Random.randBytes(size);
}

/** Returns a random int between 0 and max-1. */
public static final int randInt(int max) {
return localRandom.get().nextInt(max);
return com.google.crypto.tink.internal.Random.randInt(max);
}

/** Returns a random int. */
public static final int randInt() {
return localRandom.get().nextInt();
return com.google.crypto.tink.internal.Random.randInt();
}

private Random() {}
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/com/google/crypto/tink/internal/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -489,3 +489,28 @@ java_test(
"@maven//:junit_junit",
],
)

java_test(
name = "RandomTest",
size = "small",
srcs = ["RandomTest.java"],
deps = [
"//src/main/java/com/google/crypto/tink/internal:random",
"//src/main/java/com/google/crypto/tink/testing:test_util",
"@maven//:com_google_truth_truth",
"@maven//:junit_junit",
"@maven//:org_conscrypt_conscrypt_openjdk_uber",
],
)

java_test(
name = "RandomWithoutConscryptTest",
size = "small",
srcs = ["RandomWithoutConscryptTest.java"],
deps = [
"//src/main/java/com/google/crypto/tink/internal:random",
"//src/main/java/com/google/crypto/tink/testing:test_util",
"@maven//:com_google_truth_truth",
"@maven//:junit_junit",
],
)
104 changes: 104 additions & 0 deletions src/test/java/com/google/crypto/tink/internal/RandomTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package com.google.crypto.tink.internal;

import static com.google.common.truth.Truth.assertThat;

import com.google.crypto.tink.testing.TestUtil;
import java.security.Security;
import java.util.ArrayList;
import org.conscrypt.Conscrypt;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class RandomTest {

static boolean conscryptProviderAdded;

@BeforeClass
public static void setUp() {
try {
Conscrypt.checkAvailability();
Security.addProvider(Conscrypt.newProvider());
conscryptProviderAdded = true;
} catch (Exception | UnsatisfiedLinkError e) {
conscryptProviderAdded = false;
}
}

@Test
public void validateUsesConscrypt_doesNotThrowIfConscryptProviderIsAdded() throws Exception {
if (TestUtil.isAndroid()) {
// Android uses Conscrypt by default, but trying to add it manually fails.
assertThat(conscryptProviderAdded).isFalse();
} else {
assertThat(conscryptProviderAdded).isTrue();
}
Random.validateUsesConscrypt();
}

@Test
public void randBytes_works() throws Exception {
assertThat(Random.randBytes(10)).hasLength(10);
}

@Test
public void randIntWithMax_works() throws Exception {
assertThat(Random.randInt(5)).isLessThan(5);
}

@Test
public void randInt_works() throws Exception {
int unused = Random.randInt();
}

@Test
public void randBytes_areDifferent() throws Exception {
assertThat(Random.randBytes(32)).isNotEqualTo(Random.randBytes(32));
}

@Test
public void randomBytesInDifferentThreads_areDifferent() throws Exception {
ArrayList<Thread> threads = new ArrayList<>();
final byte[] b0 = new byte[10];
final byte[] b1 = new byte[10];
threads.add(
new Thread() {
@Override
public void run() {
System.arraycopy(Random.randBytes(10), 0, b0, 0, 10);
}
});
threads.add(
new Thread() {
@Override
public void run() {
System.arraycopy(Random.randBytes(10), 0, b1, 0, 10);
}
});
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
assertThat(b0).isNotEqualTo(b1);
}
}
Loading

0 comments on commit 6409bba

Please sign in to comment.