From f5c2c8992e20134d24ec324a06a2c3ee73b439f3 Mon Sep 17 00:00:00 2001 From: Juerg Wullschleger Date: Thu, 24 Aug 2023 03:22:45 -0700 Subject: [PATCH] Allow negative key IDs in Java. PiperOrigin-RevId: 559700249 Change-Id: I7add987257eb8097db27e3ac8a8929094594aa35 --- src/main/java/com/google/crypto/tink/internal/Util.java | 3 +-- .../java/com/google/crypto/tink/internal/UtilTest.java | 9 ++++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/google/crypto/tink/internal/Util.java b/src/main/java/com/google/crypto/tink/internal/Util.java index 338357906..56853da82 100644 --- a/src/main/java/com/google/crypto/tink/internal/Util.java +++ b/src/main/java/com/google/crypto/tink/internal/Util.java @@ -35,9 +35,8 @@ public static int randKeyId() { int result = 0; while (result == 0) { secureRandom.nextBytes(rand); - // TODO(b/148124847): Other languages create key_ids with the MSB set, so we should here too. result = - ((rand[0] & 0x7f) << 24) + ((rand[0] & 0xff) << 24) | ((rand[1] & 0xff) << 16) | ((rand[2] & 0xff) << 8) | (rand[3] & 0xff); diff --git a/src/test/java/com/google/crypto/tink/internal/UtilTest.java b/src/test/java/com/google/crypto/tink/internal/UtilTest.java index 0ed877665..40588393d 100644 --- a/src/test/java/com/google/crypto/tink/internal/UtilTest.java +++ b/src/test/java/com/google/crypto/tink/internal/UtilTest.java @@ -16,6 +16,7 @@ package com.google.crypto.tink.internal; import static com.google.common.truth.Truth.assertThat; +import static java.nio.charset.StandardCharsets.US_ASCII; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -38,11 +39,17 @@ public void randKeyId_repeatedCallsShouldOutputDifferentValues() { .isAtLeast(2); } + @Test + public void randKeyId_repeatedCallsShouldOutputANegativeValue() { + assertThat(IntStream.range(0, 100).map(unused -> Util.randKeyId()).min().getAsInt()) + .isAtMost(0); + } + @Test public void toBytesFromPrintableAscii_works() throws Exception { String pureAsciiString = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - Bytes pureAsciiBytes = Bytes.copyFrom(pureAsciiString.getBytes("ASCII")); + Bytes pureAsciiBytes = Bytes.copyFrom(pureAsciiString.getBytes(US_ASCII)); assertThat(Util.toBytesFromPrintableAscii(pureAsciiString)).isEqualTo(pureAsciiBytes); }