1 /* 2 * Copyright (C) 2023 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.adservices.ohttp.algorithms; 18 19 import com.android.adservices.ohttp.HkdfMessageDigestNativeRef; 20 import com.android.adservices.ohttp.KdfNativeRef; 21 22 import com.google.auto.value.AutoValue; 23 24 import java.util.function.Supplier; 25 26 /** Get the algorithm spec of a Key Derivation Function algorithm */ 27 @AutoValue 28 public abstract class KdfAlgorithmSpec { 29 30 // As defined in https://www.rfc-editor.org/rfc/rfc9180#name-key-derivation-functions-kd 31 public static final int HKDF_SHA256_IDENTIFIER = 0x0001; 32 33 private static final String HKDF_SHA256 = "HKDF_SHA256"; 34 35 // The variables as defined in https://www.rfc-editor.org/rfc/rfc9180#name-kdf-identifiers 36 37 /** Get the identifier for the algorithm */ identifier()38 public abstract int identifier(); 39 40 /** Get the name of the algorithm */ name()41 public abstract String name(); 42 43 /** Get the output size of the Extract function in byte */ extractOutputLength()44 public abstract int extractOutputLength(); 45 46 /** Gets the supplier of the KDF algorithm native reference */ kdfNativeRefSupplier()47 public abstract Supplier<KdfNativeRef> kdfNativeRefSupplier(); 48 49 /** Gets the supplier of the associated message digest native reference */ messageDigestSupplier()50 public abstract Supplier<HkdfMessageDigestNativeRef> messageDigestSupplier(); 51 hkdfSha256()52 private static KdfAlgorithmSpec hkdfSha256() { 53 return new AutoValue_KdfAlgorithmSpec( 54 HKDF_SHA256_IDENTIFIER, 55 HKDF_SHA256, 56 /* extractOutputLength= */ 32, 57 () -> KdfNativeRef.getHpkeKdfHkdfSha256Reference(), 58 () -> HkdfMessageDigestNativeRef.getHkdfSha256MessageDigestReference()); 59 } 60 61 /** 62 * Gets the KDF algorithm corresponding to the identifier 63 * 64 * <p>As specified in https://www.rfc-editor.org/rfc/rfc9180#name-key-derivation-functions-kd 65 */ get(int identifier)66 public static KdfAlgorithmSpec get(int identifier) throws UnsupportedHpkeAlgorithmException { 67 if (identifier == HKDF_SHA256_IDENTIFIER) { 68 return hkdfSha256(); 69 } 70 71 throw new UnsupportedHpkeAlgorithmException("Only HKDF ID = 0X0001 supported"); 72 } 73 } 74