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