1 /*
2  * Copyright 2015 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 #pragma once
18 
19 #include <keymaster/km_openssl/kdf.h>
20 
21 #include <hardware/keymaster_defs.h>
22 
23 #include <keymaster/UniquePtr.h>
24 #include <keymaster/serializable.h>
25 
26 namespace keymaster {
27 
28 /**
29  * A light implementation of ISO18033KDF as defined by ISO-18033-2 (www.shoup.net/iso/std6.pdf) and
30  * its slightly different variant ANSI-X9-42.
31  */
32 class Iso18033Kdf : public Kdf {
33   public:
~Iso18033Kdf()34     ~Iso18033Kdf() {}
35 
Init(keymaster_digest_t digest_type,const uint8_t * secret,size_t secret_len)36     bool Init(keymaster_digest_t digest_type, const uint8_t* secret, size_t secret_len) {
37         return Kdf::Init(digest_type, secret, secret_len, nullptr /* salt */, 0 /* salt_len */);
38     }
39 
40     /**
41      * Generates ISO18033's derived key, as defined in ISO-18033-2 and ANSI-X9-42. In ISO 18033-2,
42      * KDF takes a secret and outputs:
43      *
44      * hash(secret || start_counter) || hash(secret|| start_counter + 1) || ...
45      *
46      * In ANSI-X9-42, KDF takes a secret and additional info, and outputs:
47      *
48      * hash(secret || start_counter || info) || hash(secret || start_counter + 1 || info) || ...
49      *
50      * Note that the KDFs are the same if the info field is considered optional.  In both cases the
51      * length of the output is specified by the caller, and the counter is encoded as a 4-element
52      * byte array.
53      */
54     bool GenerateKey(const uint8_t* info, size_t info_len, uint8_t* output,
55                      size_t output_len) override;
56 
57   protected:
Iso18033Kdf(uint32_t start_counter)58     explicit Iso18033Kdf(uint32_t start_counter) : start_counter_(start_counter) {}
59 
60   private:
61     uint32_t start_counter_;
62 };
63 
64 }  // namespace keymaster
65