1 // Copyright 2023 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; 18 19 import com.google.crypto.tink.internal.LegacyProtoParameters; 20 import com.google.crypto.tink.internal.MutableSerializationRegistry; 21 import com.google.crypto.tink.internal.ProtoParametersSerialization; 22 import com.google.crypto.tink.proto.KeyTemplate; 23 import com.google.protobuf.ExtensionRegistryLite; 24 import java.io.IOException; 25 import java.security.GeneralSecurityException; 26 27 /** Functions to parse and serialize Parameters in Tink's binary format based on Protobufs. */ 28 public final class TinkProtoParametersFormat { 29 /** 30 * Serializes a Parameters object into a byte[] according to Tink's binary format. 31 */ serialize(Parameters parameters)32 public static byte[] serialize(Parameters parameters) throws GeneralSecurityException { 33 if (parameters instanceof LegacyProtoParameters) { 34 return ((LegacyProtoParameters) parameters).getSerialization().getKeyTemplate().toByteArray(); 35 } 36 ProtoParametersSerialization s = 37 MutableSerializationRegistry.globalInstance() 38 .serializeParameters(parameters, ProtoParametersSerialization.class); 39 return s.getKeyTemplate().toByteArray(); 40 } 41 42 /** 43 * Parses a byte[] into a Parameters object according to Tink's binary format. 44 */ parse(byte[] serializedParameters)45 public static Parameters parse(byte[] serializedParameters) throws GeneralSecurityException { 46 KeyTemplate t; 47 try { 48 t = KeyTemplate.parseFrom(serializedParameters, ExtensionRegistryLite.getEmptyRegistry()); 49 } catch (IOException e) { 50 throw new GeneralSecurityException("Failed to parse proto", e); 51 } 52 return MutableSerializationRegistry.globalInstance() 53 .parseParametersWithLegacyFallback(ProtoParametersSerialization.checkedCreate(t)); 54 } 55 TinkProtoParametersFormat()56 private TinkProtoParametersFormat() {} 57 } 58