1 /* 2 * Copyright 2023 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. 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 distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 package walkthrough; 15 16 import static com.google.common.truth.Truth.assertThat; 17 import static java.nio.charset.StandardCharsets.UTF_8; 18 19 import com.google.crypto.tink.KeysetHandle; 20 import com.google.crypto.tink.aead.AeadConfig; 21 import org.junit.Test; 22 import org.junit.runner.RunWith; 23 import org.junit.runners.JUnit4; 24 25 @RunWith(JUnit4.class) 26 public final class ReadCleartextKeysetExampleTest { 27 private static final String KEYSET_TO_SERIALIZE = 28 "{" 29 + " \"key\": [" 30 + " {" 31 + " \"keyData\": {" 32 + " \"keyMaterialType\": \"SYMMETRIC\"," 33 + " \"typeUrl\": \"type.googleapis.com/google.crypto.tink.AesGcmKey\"," 34 + " \"value\": \"GhD+9l0RANZjzZEZ8PDp7LRW\"" 35 + " }," 36 + " \"keyId\": 1931667682," 37 + " \"outputPrefixType\": \"TINK\"," 38 + " \"status\": \"ENABLED\"" 39 + " }" 40 + " ]," 41 + " \"primaryKeyId\": 1931667682" 42 + "}"; 43 44 @Test readKeyset_succeedsWithValidInputs()45 public void readKeyset_succeedsWithValidInputs() throws Exception { 46 AeadConfig.register(); 47 48 byte[] plaintext = "plaintext".getBytes(UTF_8); 49 byte[] associatedData = "associatedData".getBytes(UTF_8); 50 51 KeysetHandle deserializedKeyset = ReadCleartextKeysetExample.readKeyset(KEYSET_TO_SERIALIZE); 52 53 // Make sure the keyset was read correctly trying to decrypt ciphertext. 54 byte[] decrypted = 55 ObtainAndUseAeadPrimitiveExample.aeadEncryptDecrypt( 56 deserializedKeyset, plaintext, associatedData); 57 assertThat(decrypted).isEqualTo(plaintext); 58 } 59 } 60