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 #include <keymaster/km_openssl/kdf.h>
18
19 namespace keymaster {
20
Kdf()21 Kdf::Kdf() : is_initialized_(false) {}
22
Init(keymaster_digest_t digest_type,const uint8_t * secret,size_t secret_len,const uint8_t * salt,size_t salt_len)23 bool Kdf::Init(keymaster_digest_t digest_type, const uint8_t* secret, size_t secret_len,
24 const uint8_t* salt, size_t salt_len) {
25 is_initialized_ = false;
26
27 switch (digest_type) {
28 case KM_DIGEST_SHA1:
29 digest_size_ = 20;
30 digest_type_ = digest_type;
31 break;
32 case KM_DIGEST_SHA_2_256:
33 digest_size_ = 32;
34 digest_type_ = digest_type;
35 break;
36 default:
37 return false;
38 }
39
40 if (!secret || secret_len == 0) return false;
41
42 secret_key_len_ = secret_len;
43 secret_key_.reset(dup_buffer(secret, secret_len));
44 if (!secret_key_.get()) return false;
45
46 salt_len_ = salt_len;
47 if (salt && salt_len > 0) {
48 salt_.reset(dup_buffer(salt, salt_len));
49 if (!salt_.get()) return false;
50 } else {
51 salt_.reset();
52 }
53
54 is_initialized_ = true;
55 return true;
56 }
57
Uint32ToBigEndianByteArray(uint32_t number,uint8_t * output)58 bool Kdf::Uint32ToBigEndianByteArray(uint32_t number, uint8_t* output) {
59 if (!output) return false;
60
61 output[0] = (number >> 24) & 0xff;
62 output[1] = (number >> 16) & 0xff;
63 output[2] = (number >> 8) & 0xff;
64 output[3] = (number)&0xff;
65 return true;
66 }
67
68 } // namespace keymaster
69