1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.apksig.kms.gcp; 18 19 import static com.android.apksig.kms.KmsType.GCP; 20 21 import com.android.apksig.SignerEngine; 22 import com.android.apksig.kms.KmsException; 23 24 import com.google.cloud.kms.v1.AsymmetricSignRequest; 25 import com.google.cloud.kms.v1.CryptoKeyVersionName; 26 import com.google.cloud.kms.v1.KeyManagementServiceClient; 27 import com.google.protobuf.ByteString; 28 29 import java.io.IOException; 30 31 /** Signs data using Google Cloud Platform. */ 32 public class GcpSignerEngine implements SignerEngine { 33 private final String mKeyAlias; 34 35 /** 36 * Create an engine to sign data with GCP 37 * 38 * @param keyAlias must be in the format of a parsable <a 39 * href="https://cloud.google.com/java/docs/reference/google-cloud-spanner/latest/com.google.spanner.admin.database.v1.CryptoKeyVersionName">CryptoKeyVersionName</a> 40 */ GcpSignerEngine(String keyAlias)41 public GcpSignerEngine(String keyAlias) { 42 mKeyAlias = keyAlias; 43 } 44 45 @Override sign(byte[] data)46 public byte[] sign(byte[] data) { 47 try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { 48 CryptoKeyVersionName cryptoKeyVersionName = CryptoKeyVersionName.parse(mKeyAlias); 49 return client.asymmetricSign( 50 AsymmetricSignRequest.newBuilder() 51 .setName(cryptoKeyVersionName.toString()) 52 .setData(ByteString.copyFrom(data)) 53 .build()) 54 .getSignature() 55 .toByteArray(); 56 } catch (IOException e) { 57 throw new KmsException(GCP, "Error initializing KeyManagementServiceClient", e); 58 } 59 } 60 } 61