1 /* *****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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 * *****************************************************************/
28 #define XOR_BUF(in, out, bufSize)\
31 for(i=0; i< (bufSize); i++)\
33 (out)[i] = (in)[i] ^ (out)[i];\
44 if ( ((uint8_t *)&a)[0] == 0x1) // little
52 static void GetBigEndianBuf(uint8_t *buf, int num)
54 uint8_t *nBuf = (uint8_t *)#
55 if ( isLittle() == 1 )
58 for (i = 0; i < sizeof(int); i++)
60 buf[i] = nBuf[ sizeof(int) - i - 1];
65 memcpy(buf, nBuf, sizeof(int));
69 // TODO: Add comments to explain implementation.
70 int DeriveCryptoKeyFromPassword(const unsigned char *passwd, size_t pLen,
71 const uint8_t *salt, const size_t saltLen,
72 const size_t iterations,
73 const size_t keyLen, uint8_t *derivedKey)
76 uint8_t buf[DTLS_HMAC_DIGEST_SIZE];
77 uint8_t uBuf[DTLS_HMAC_DIGEST_SIZE];
80 size_t nOctetInLastBlock = 0;
82 nBlocks = (size_t)ceil ((double)keyLen / (double)DTLS_HMAC_DIGEST_SIZE);
83 nOctetInLastBlock = keyLen - (nBlocks - 1) * DTLS_HMAC_DIGEST_SIZE;
85 dtls_hmac_context_t *ctx = NULL;
86 ctx = dtls_hmac_new( (const unsigned char *)passwd, pLen);
89 OIC_LOG(ERROR, TAG, "DTLS HMAC Context is NULL");
94 size_t idx = 0; //index for buffer
96 while (i != nBlocks + 1)
99 dtls_hmac_init(ctx, (const unsigned char *)passwd, pLen);
100 while (counter != iterations)
104 uint8_t intBuf[4] = {0x00, 0x00, 0x00, 0x00};
105 dtls_hmac_update(ctx, salt, saltLen);
106 GetBigEndianBuf(intBuf, i);
107 dtls_hmac_update(ctx, intBuf, 4);
109 int len = dtls_hmac_finalize(ctx, buf);
110 if (DTLS_HMAC_DIGEST_SIZE != len)
112 OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
115 memcpy(uBuf, buf, DTLS_HMAC_DIGEST_SIZE);
119 dtls_hmac_init(ctx, (const unsigned char *)passwd, pLen);
120 dtls_hmac_update(ctx, buf, DTLS_HMAC_DIGEST_SIZE);
121 int len = dtls_hmac_finalize(ctx, buf);
122 if (DTLS_HMAC_DIGEST_SIZE != len)
124 OIC_LOG(ERROR, TAG, "DTLS HMAC is failed");
127 XOR_BUF(buf, uBuf, DTLS_HMAC_DIGEST_SIZE);
135 memcpy(derivedKey + idx, uBuf, nOctetInLastBlock);
139 memcpy(derivedKey + idx, uBuf, DTLS_HMAC_DIGEST_SIZE);
140 idx += DTLS_HMAC_DIGEST_SIZE;