replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / src / pbkdf2.c
1 /******************************************************************
2 *
3 * Copyright 2016 Microsoft Corporation
4 *
5 *
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 ******************************************************************/
20
21 #include "logger.h"
22 #include "mbedtls/pkcs5.h"
23 #include "mbedtls/md.h"
24
25 #define TAG "OIC_SEC_PBDKF2"
26
27 int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
28     const uint8_t *salt, const size_t saltLen,
29     const size_t iterations,
30     const size_t keyLen, uint8_t *derivedKey)
31 {
32     mbedtls_md_context_t sha_ctx;
33     const mbedtls_md_info_t *info_sha;
34     int ret = -1;
35
36     /* Setup the hash/HMAC function, for the PBKDF2 function. */
37     mbedtls_md_init(&sha_ctx);
38
39     info_sha = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
40     if (info_sha == NULL)
41     {
42         OIC_LOG(ERROR, TAG, "Failed to get hash information");
43         return ret;
44     }
45
46     ret = mbedtls_md_setup(&sha_ctx, info_sha, 1);
47     if (ret != 0)
48     {
49         OIC_LOG(ERROR, TAG, "Failed to setup hash function");
50         return ret;
51     }
52
53     ret = mbedtls_pkcs5_pbkdf2_hmac(&sha_ctx, passwd, pLen, salt, saltLen, iterations, keyLen, derivedKey);
54     if (ret != 0)
55     {
56         OIC_LOG(ERROR, TAG, "Call to mbedtls PBKDF2 function failed");
57     }
58
59     mbedtls_md_free(&sha_ctx);
60     return ret;
61 }