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 "kdf.h" 18 19 namespace keymaster { 20 21 Kdf::Kdf() : is_initialized_(false) {} 22 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) 41 return false; 42 43 secret_key_len_ = secret_len; 44 secret_key_.reset(dup_buffer(secret, secret_len)); 45 if (!secret_key_.get()) 46 return false; 47 48 salt_len_ = salt_len; 49 if (salt && salt_len > 0) { 50 salt_.reset(dup_buffer(salt, salt_len)); 51 if (!salt_.get()) 52 return false; 53 } else { 54 salt_.reset(); 55 } 56 57 is_initialized_ = true; 58 return true; 59 } 60 61 bool Kdf::Uint32ToBigEndianByteArray(uint32_t number, uint8_t* output) { 62 if (!output) 63 return false; 64 65 output[0] = (number >> 24) & 0xff; 66 output[1] = (number >> 16) & 0xff; 67 output[2] = (number >> 8) & 0xff; 68 output[3] = (number)&0xff; 69 return true; 70 } 71 72 } // namespace keymaster 73