1 // Copyright 2022 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // 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 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 //////////////////////////////////////////////////////////////////////////////// 16 17 package com.google.crypto.tink.testing; 18 19 import com.google.crypto.tink.InsecureSecretKeyAccess; 20 import com.google.crypto.tink.KeysetHandle; 21 import com.google.crypto.tink.TinkProtoKeysetFormat; 22 import com.google.crypto.tink.monitoring.MonitoringAnnotations; 23 import com.google.crypto.tink.testing.proto.AnnotatedKeyset; 24 import com.google.crypto.tink.testing.proto.CreationRequest; 25 import com.google.crypto.tink.testing.proto.CreationResponse; 26 import io.grpc.stub.StreamObserver; 27 import java.security.GeneralSecurityException; 28 29 /** 30 * Utility functions for implementing Services. 31 */ 32 final class Util { parseBinaryProtoKeyset(AnnotatedKeyset annotatedKeyset)33 static KeysetHandle parseBinaryProtoKeyset(AnnotatedKeyset annotatedKeyset) 34 throws GeneralSecurityException { 35 KeysetHandle handle = 36 TinkProtoKeysetFormat.parseKeyset( 37 annotatedKeyset.getSerializedKeyset().toByteArray(), InsecureSecretKeyAccess.get()); 38 return KeysetHandle.newBuilder(handle) 39 .setMonitoringAnnotations( 40 MonitoringAnnotations.newBuilder().addAll(annotatedKeyset.getAnnotationsMap()).build()) 41 .build(); 42 } 43 44 /** Responds to a "create" request for a specific class */ createPrimitiveForRpc( CreationRequest request, StreamObserver<CreationResponse> responseObserver, Class<?> primitiveClass)45 static void createPrimitiveForRpc( 46 CreationRequest request, 47 StreamObserver<CreationResponse> responseObserver, 48 Class<?> primitiveClass) { 49 try { 50 KeysetHandle keysetHandle = parseBinaryProtoKeyset(request.getAnnotatedKeyset()); 51 // We create to check if there is an exception thrown. 52 Object unused = keysetHandle.getPrimitive(primitiveClass); 53 } catch (GeneralSecurityException e) { 54 responseObserver.onNext(CreationResponse.newBuilder().setErr(e.toString()).build()); 55 responseObserver.onCompleted(); 56 return; 57 } 58 responseObserver.onNext(CreationResponse.getDefaultInstance()); 59 responseObserver.onCompleted(); 60 } 61 Util()62 private Util() {} 63 } 64