1 //******************************************************************
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "platform_features.h"
29 #define TAG "OIC_PBDKF2"
30 #define XOR_BUF(in, out, bufSize)\
34 for (i=0; i< (bufSize); i++)\
36 (out)[i] = (in)[i] ^ (out)[i];\
46 if ( ((uint8_t *)&a)[0] == 0x1) // little
54 static void GetBigEndianBuf(uint8_t *buf, int num)
56 uint8_t *nBuf = (uint8_t *)#
57 if ( isLittle() == 1 )
60 for (i = 0; i < sizeof(int); i++)
62 buf[i] = nBuf[ sizeof(int) - i - 1];
67 memcpy(buf, nBuf, sizeof(int));
71 // TODO: Add comments to explain implementation.
72 int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
73 const uint8_t *salt, const size_t saltLen,
74 const size_t iterations,
75 const size_t keyLen, uint8_t *derivedKey)
78 uint8_t buf[DTLS_HMAC_DIGEST_SIZE] = {0,};
79 uint8_t uBuf[DTLS_HMAC_DIGEST_SIZE] = {0,};
82 size_t nOctetInLastBlock = 0;
84 nBlocks = (size_t)ceil ((double)keyLen / (double)DTLS_HMAC_DIGEST_SIZE);
85 nOctetInLastBlock = keyLen - (nBlocks - 1) * DTLS_HMAC_DIGEST_SIZE;
87 dtls_hmac_context_t *ctx = NULL;
88 ctx = dtls_hmac_new( (const unsigned char *)passwd, pLen);
91 OIC_LOG(ERROR, TAG, "DTLS HMAC Context is NULL");
96 size_t idx = 0; //index for buffer
98 while (i != nBlocks + 1)
101 dtls_hmac_init(ctx, (const unsigned char *)passwd, pLen);
102 while (counter != iterations)
106 uint8_t intBuf[4] = {0x00, 0x00, 0x00, 0x00};
107 dtls_hmac_update(ctx, salt, saltLen);
108 GetBigEndianBuf(intBuf, i);
109 dtls_hmac_update(ctx, intBuf, 4);
111 int len = dtls_hmac_finalize(ctx, buf);
112 if (DTLS_HMAC_DIGEST_SIZE != len)
114 OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
117 memcpy(uBuf, buf, DTLS_HMAC_DIGEST_SIZE);
121 dtls_hmac_init(ctx, (const unsigned char *)passwd, pLen);
122 dtls_hmac_update(ctx, buf, DTLS_HMAC_DIGEST_SIZE);
123 int len = dtls_hmac_finalize(ctx, buf);
124 if (DTLS_HMAC_DIGEST_SIZE != len)
126 OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
129 XOR_BUF(buf, uBuf, DTLS_HMAC_DIGEST_SIZE);
137 memcpy(derivedKey + idx, uBuf, nOctetInLastBlock);
141 memcpy(derivedKey + idx, uBuf, DTLS_HMAC_DIGEST_SIZE);
142 idx += DTLS_HMAC_DIGEST_SIZE;