Skip to content

Commit f5c2c89

Browse files
juergwcopybara-github
authored andcommitted
Allow negative key IDs in Java.
PiperOrigin-RevId: 559700249 Change-Id: I7add987257eb8097db27e3ac8a8929094594aa35
1 parent d3ba082 commit f5c2c89

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/main/java/com/google/crypto/tink/internal/Util.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ public static int randKeyId() {
3535
int result = 0;
3636
while (result == 0) {
3737
secureRandom.nextBytes(rand);
38-
// TODO(b/148124847): Other languages create key_ids with the MSB set, so we should here too.
3938
result =
40-
((rand[0] & 0x7f) << 24)
39+
((rand[0] & 0xff) << 24)
4140
| ((rand[1] & 0xff) << 16)
4241
| ((rand[2] & 0xff) << 8)
4342
| (rand[3] & 0xff);

src/test/java/com/google/crypto/tink/internal/UtilTest.java

+8-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package com.google.crypto.tink.internal;
1717

1818
import static com.google.common.truth.Truth.assertThat;
19+
import static java.nio.charset.StandardCharsets.US_ASCII;
1920
import static org.junit.Assert.assertFalse;
2021
import static org.junit.Assert.assertThrows;
2122
import static org.junit.Assert.assertTrue;
@@ -38,11 +39,17 @@ public void randKeyId_repeatedCallsShouldOutputDifferentValues() {
3839
.isAtLeast(2);
3940
}
4041

42+
@Test
43+
public void randKeyId_repeatedCallsShouldOutputANegativeValue() {
44+
assertThat(IntStream.range(0, 100).map(unused -> Util.randKeyId()).min().getAsInt())
45+
.isAtMost(0);
46+
}
47+
4148
@Test
4249
public void toBytesFromPrintableAscii_works() throws Exception {
4350
String pureAsciiString =
4451
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
45-
Bytes pureAsciiBytes = Bytes.copyFrom(pureAsciiString.getBytes("ASCII"));
52+
Bytes pureAsciiBytes = Bytes.copyFrom(pureAsciiString.getBytes(US_ASCII));
4653
assertThat(Util.toBytesFromPrintableAscii(pureAsciiString)).isEqualTo(pureAsciiBytes);
4754
}
4855

0 commit comments

Comments
 (0)