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