1 // Copyright 2020 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 package com.google.crypto.tink.tinkkey.internal; 17 18 import com.google.crypto.tink.KeyTemplate; 19 import com.google.crypto.tink.KeyTemplate.OutputPrefixType; 20 import com.google.crypto.tink.proto.KeyData; 21 import com.google.crypto.tink.tinkkey.TinkKey; 22 import com.google.errorprone.annotations.Immutable; 23 24 /** 25 * Wraps the proto {@code KeyData} as an implementation of a {@code TinkKey}. The underlying {@code 26 * KeyData} determines whether this ProtoKey has a secret. 27 * 28 * <p>ProtoKey is not intended for use outside of the Tink project. 29 */ 30 @Immutable 31 public final class ProtoKey implements TinkKey { 32 private final KeyData keyData; 33 private final boolean hasSecret; 34 private final OutputPrefixType outputPrefixType; 35 36 /** 37 * Constructs a ProtoKey with {@code hasSecret()} returning true if the input {@code KeyData} has 38 * key material of type UNKNOWN_KEYMATERIAL, SYMMETRIC, or ASYMMETRIC_PRIVATE. 39 */ ProtoKey(KeyData keyData, OutputPrefixType opt)40 public ProtoKey(KeyData keyData, OutputPrefixType opt) { 41 this.hasSecret = isSecret(keyData); 42 this.keyData = keyData; 43 this.outputPrefixType = opt; 44 } 45 isSecret(KeyData keyData)46 private static boolean isSecret(KeyData keyData) { 47 return keyData.getKeyMaterialType() == KeyData.KeyMaterialType.UNKNOWN_KEYMATERIAL 48 || keyData.getKeyMaterialType() == KeyData.KeyMaterialType.SYMMETRIC 49 || keyData.getKeyMaterialType() == KeyData.KeyMaterialType.ASYMMETRIC_PRIVATE; 50 } 51 getProtoKey()52 public KeyData getProtoKey() { 53 return keyData; 54 } 55 getOutputPrefixType()56 public OutputPrefixType getOutputPrefixType() { 57 return outputPrefixType; 58 } 59 60 @Override hasSecret()61 public boolean hasSecret() { 62 return hasSecret; 63 } 64 65 /** 66 * @throws UnsupportedOperationException There is currently no direct way of getting a {@code 67 * KeyTemplate} from {@code KeyData}. 68 */ 69 @Override getKeyTemplate()70 public KeyTemplate getKeyTemplate() { 71 throw new UnsupportedOperationException(); 72 } 73 } 74