Skip to content

Commit

Permalink
Allow negative key IDs in Java.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 559700249
Change-Id: I7add987257eb8097db27e3ac8a8929094594aa35
  • Loading branch information
juergw authored and copybara-github committed Aug 24, 2023
1 parent d3ba082 commit f5c2c89
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
3 changes: 1 addition & 2 deletions src/main/java/com/google/crypto/tink/internal/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
9 changes: 8 additions & 1 deletion src/test/java/com/google/crypto/tink/internal/UtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
}

Expand Down

0 comments on commit f5c2c89

Please sign in to comment.