sha_crypt.c
Go to the documentation of this file.
1 /**
2  * @file sha_crypt.c
3  * @brief Unix crypt using SHA-256 and SHA-512
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneCRYPTO Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL CRYPTO_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/crypto.h"
36 #include "kdf/sha_crypt.h"
37 #include "hash/hash_algorithms.h"
38 
39 //Check crypto library configuration
40 #if (SHA_CRYPT_SUPPORT == ENABLED)
41 
42 //Base64 encoding table
43 static const char_t base64EncTable[64] =
44 {
45  '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
46  'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
47  'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
48  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
49 };
50 
51 
52 /**
53  * @brief SHA-crypt algorithm
54  * @param[in] hashAlgo Underlying hash function (SHA-256 or SHA-512)
55  * @param[in] password NULL-terminated password
56  * @param[in] salt NULL-terminated salt string
57  * @param[out] output Output string
58  * @param[out] outputLen Length of the output string (optional parameter)
59  * @return Error code
60  **/
61 
62 error_t shaCrypt(const HashAlgo *hashAlgo, const char_t *password,
63  const char_t *salt, char_t *output, size_t *outputLen)
64 {
65  bool_t flag;
66  uint_t rounds;
67  uint_t i;
68  size_t j;
69  size_t n;
70  char_t *p;
71  char_t *prefix;
72  size_t saltLen;
73  size_t passwordLen;
74  uint8_t dp[MAX_HASH_DIGEST_SIZE];
75  uint8_t ds[MAX_HASH_DIGEST_SIZE];
76  uint8_t digest[MAX_HASH_DIGEST_SIZE];
77 #if (CRYPTO_STATIC_MEM_SUPPORT == DISABLED)
78  HashContext *hashContext;
79 #else
80  HashContext hashContext[2];
81 #endif
82 
83  //Check parameters
84  if(hashAlgo == NULL || password == NULL || salt == NULL || output == NULL)
86 
87  //SHA-crypt is specified for SHA-256 and SHA-512 only
88  if(osStrcmp(hashAlgo->name, "SHA-256") == 0)
89  {
90  //The magic prefix is $5$ for SHA-256
91  prefix = "$5$";
92  }
93  else if(osStrcmp(hashAlgo->name, "SHA-512") == 0)
94  {
95  //The magic prefix is $6$ for SHA-256
96  prefix = "$6$";
97  }
98  else
99  {
100  //The hash algorithm is not supported
102  }
103 
104  //Skip the salt prefix, if any
105  if(osStrncmp(salt, prefix, 3) == 0)
106  {
107  salt += 3;
108  }
109 
110  //The rounds=<N> specification is optional
111  if(osStrncmp(salt, "rounds=", 7) == 0)
112  {
113  //The rounds=<N> specification is present in the input salt
114  flag = TRUE;
115 
116  //N is an unsigned decimal number
117  rounds = osStrtoul(salt + 7, &p, 10);
118 
119  //A trailing '$' is used to separate the rounds specification from the
120  //following text
121  if(*p != '$')
122  return ERROR_INVALID_SYNTAX;
123 
124  //Skip the trailing '$' character
125  salt = p + 1;
126 
127  //Any selection of N below the minimum will cause the use of 1,000
128  //rounds
129  rounds = MAX(rounds, SHA_CRYPT_MIN_ROUNDS);
130 
131  //A value of 1 billion and higher will cause 999,999,999 rounds to
132  //be used
133  rounds = MIN(rounds, SHA_CRYPT_MAX_ROUNDS);
134  }
135  else
136  {
137  //The rounds=<N> specification is absent
138  flag = FALSE;
139  //The default number of rounds is 5,000
140  rounds = SHA_CRYPT_DEFAULT_ROUNDS;
141  }
142 
143  //Retrieve the length of the salt string
144  saltLen = osStrlen(salt);
145  //The salt string can be up to 16 characters
146  saltLen = MIN(saltLen, SHA_CRYPT_MAX_SALT_LEN);
147 
148  //Retrieve the length of the password string
149  passwordLen = osStrlen(password);
150 
151 #if (CRYPTO_STATIC_MEM_SUPPORT == DISABLED)
152  //Allocate a memory buffer to hold the hash contexts
153  hashContext = cryptoAllocMem(2 * sizeof(HashContext));
154  //Failed to allocate memory?
155  if(hashContext == NULL)
156  return ERROR_OUT_OF_MEMORY;
157 #endif
158 
159  //Start digest A
160  hashAlgo->init(&hashContext[0]);
161  //The password string is added to digest A
162  hashAlgo->update(&hashContext[0], password, passwordLen);
163  //The salt string is added to digest A
164  hashAlgo->update(&hashContext[0], salt, saltLen);
165 
166  //Start digest B
167  hashAlgo->init(&hashContext[1]);
168  //Add the password to digest B
169  hashAlgo->update(&hashContext[1], password, passwordLen);
170  //Add the salt string to digest B
171  hashAlgo->update(&hashContext[1], salt, saltLen);
172  //Add the password again to digest B
173  hashAlgo->update(&hashContext[1], password, passwordLen);
174  //Finish digest B
175  hashAlgo->final(&hashContext[1], digest);
176 
177  //For each block of 64 bytes in the password string, add digest B to digest
178  //A. For the remaining N bytes of the password string add the first N bytes
179  //of digest B to digest A
180  for(j = 0; j < passwordLen; j += n)
181  {
182  n = MIN(passwordLen - j, hashAlgo->digestSize);
183  hashAlgo->update(&hashContext[0], digest, n);
184  }
185 
186  //Process each bit of the binary representation of the length of the password
187  //string up to and including the highest 1-digit, starting from to lowest bit
188  //position
189  for(n = passwordLen; n > 0; n >>= 1)
190  {
191  //Check the value of the current bit
192  if((n & 1) != 0)
193  {
194  //For a 1-digit add digest B to digest A
195  hashAlgo->update(&hashContext[0], digest, hashAlgo->digestSize);
196  }
197  else
198  {
199  //For a 0-digit add the password string
200  hashAlgo->update(&hashContext[0], password, passwordLen);
201  }
202  }
203 
204  //Finish digest A
205  hashAlgo->final(&hashContext[0], digest);
206 
207  //Start digest DP
208  hashAlgo->init(&hashContext[1]);
209 
210  //Process each byte in the password
211  for(j = 0; j < passwordLen; j++)
212  {
213  //Add the password to digest DP
214  hashAlgo->update(&hashContext[1], password, passwordLen);
215  }
216 
217  //Finish digest DP
218  hashAlgo->final(&hashContext[1], dp);
219 
220  //Start digest DS
221  hashAlgo->init(&hashContext[1]);
222 
223  //Repeat the following 16+A[0] times, where A[0] represents the first byte
224  //in digest A interpreted as an 8-bit unsigned value
225  for(j = 0; j < (digest[0] + 16U); j++)
226  {
227  //Add the salt to digest DS
228  hashAlgo->update(&hashContext[1], salt, saltLen);
229  }
230 
231  //Finish digest DS
232  hashAlgo->final(&hashContext[1], ds);
233 
234  //Repeat a loop according to the number specified in the rounds=<N>
235  //specification in the salt (or the default value if none is present)
236  for(i = 0; i < rounds; i++)
237  {
238  //Start digest C
239  hashAlgo->init(&hashContext[0]);
240 
241  //Odd or even round?
242  if((i & 1) != 0)
243  {
244  //For odd round numbers add the byte sequence P to digest C
245  for(j = 0; j < passwordLen; j += n)
246  {
247  //For each block of 32 or 64 bytes of length of the password string
248  //the entire digest DP is used. For the remaining N bytes use the
249  //first N bytes of digest DP
250  n = MIN(passwordLen - j, hashAlgo->digestSize);
251  hashAlgo->update(&hashContext[0], dp, n);
252  }
253  }
254  else
255  {
256  //For even round numbers add digest A/C
257  hashAlgo->update(&hashContext[0], digest, hashAlgo->digestSize);
258  }
259 
260  //Round number not divisible by 3?
261  if(i % 3 != 0)
262  {
263  //For all round numbers not divisible by 3 add the byte sequence S
264  for(j = 0; j < saltLen; j += n)
265  {
266  //For each block of 32 or 64 bytes of length of the salt string the
267  //entire digest DS is used. For the remaining N bytes use the first
268  //N bytes of digest DS
269  n = MIN(saltLen - j, hashAlgo->digestSize);
270  hashAlgo->update(&hashContext[0], ds, n);
271  }
272  }
273 
274  //Round number not divisible by 7?
275  if(i % 7 != 0)
276  {
277  //For all round numbers not divisible by 7 add the byte sequence P
278  for(j = 0; j < passwordLen; j += n)
279  {
280  //For each block of 32 or 64 bytes of length of the password string
281  //the entire digest DP is used. For the remaining N bytes use the
282  //first N bytes of digest DP
283  n = MIN(passwordLen - j, hashAlgo->digestSize);
284  hashAlgo->update(&hashContext[0], dp, n);
285  }
286  }
287 
288  //Odd or even round?
289  if((i & 1) != 0)
290  {
291  //For odd round numbers add digest A/C
292  hashAlgo->update(&hashContext[0], digest, hashAlgo->digestSize);
293  }
294  else
295  {
296  //For even round numbers add the byte sequence P
297  for(j = 0; j < passwordLen; j += n)
298  {
299  //For each block of 32 or 64 bytes of length of the password string
300  //the entire digest DP is used. For the remaining N bytes use the
301  //first N bytes of digest DP
302  n = MIN(passwordLen - j, hashAlgo->digestSize);
303  hashAlgo->update(&hashContext[0], dp, n);
304  }
305  }
306 
307  //Finish digest C
308  hashAlgo->final(&hashContext[0], digest);
309  }
310 
311  //The output string is an ASCII string that begins with the salt prefix
312  n = osSprintf(output, "%s", prefix);
313 
314  //Check whether the rounds=<N> specification is present in the input salt
315  //string
316  if(flag)
317  {
318  //A trailing '$' is added in this case to separate the rounds
319  //specification from the following text
320  n += osSprintf(output + n, "rounds=%u$", rounds);
321  }
322 
323  //The salt string truncated to 16 characters
324  saltLen = MIN(saltLen, SHA_CRYPT_MAX_SALT_LEN);
325 
326  //Append the salt string
327  osStrncpy(output + n, salt, saltLen);
328  n += saltLen;
329 
330  //Append a '$' character
331  output[n++] = '$';
332 
333  //Append the base-64 encoded final C digest
334  n += shaCryptEncodeBase64(hashAlgo, digest, output + n);
335 
336 #if (CRYPTO_STATIC_MEM_SUPPORT == DISABLED)
337  //Release hash context
338  cryptoFreeMem(hashContext);
339 #endif
340 
341  //Length of the output string (excluding the terminating NULL)
342  if(outputLen != NULL)
343  {
344  *outputLen = n;
345  }
346 
347  //Successful processing
348  return NO_ERROR;
349 }
350 
351 
352 /**
353  * @brief base-64 encoding algorithm
354  * @param[in] hashAlgo Underlying hash function (SHA-256 or SHA-512)
355  * @param[in] input Input digest to encode
356  * @param[out] output NULL-terminated string encoded with base-64 algorithm
357  * @return Length of the base-64 string
358  **/
359 
360 size_t shaCryptEncodeBase64(const HashAlgo *hashAlgo, const uint8_t *input,
361  uint8_t *output)
362 {
363  uint32_t value;
364  uint_t i;
365  uint_t j;
366  uint_t k;
367 
368  //SHA-256 or SHA-512 algorithm?
369  if(hashAlgo->digestSize == 32)
370  {
371  //Encode the SHA-256 digest using base-64
372  for(i = 0, j = 0, k = 0; i < 30; i += 3)
373  {
374  //Extract a group of three bytes from the digest
375  value = input[k] << 16;
376  value |= input[(k + 10) % 30] << 8;
377  value |= input[(k + 20) % 30];
378 
379  //Each group produces four characters as output
380  output[j++] = base64EncTable[value & 0x3F];
381  output[j++] = base64EncTable[(value >> 6) & 0x3F];
382  output[j++] = base64EncTable[(value >> 12) & 0x3F];
383  output[j++] = base64EncTable[(value >> 18) & 0x3F];
384 
385  //Next group
386  k = (k + 21) % 30;
387  }
388 
389  //For the last group there are not enough bytes left in the digest and
390  //the value zero is used in its place
391  value = input[31] << 8;
392  value |= input[30];
393 
394  //The last group produces three characters as output
395  output[j++] = base64EncTable[value & 0x3F];
396  output[j++] = base64EncTable[(value >> 6) & 0x3F];
397  output[j++] = base64EncTable[(value >> 12) & 0x3F];
398  }
399  else
400  {
401  //Encode the SHA-512 digest using base-64
402  for(i = 0, j = 0, k = 0; i < 63; i += 3)
403  {
404  //Extract a group of three bytes from the digest
405  value = input[k] << 16;
406  value |= input[(k + 21) % 63] << 8;
407  value |= input[(k + 42) % 63];
408 
409  //Each group produces four characters as output
410  output[j++] = base64EncTable[value & 0x3F];
411  output[j++] = base64EncTable[(value >> 6) & 0x3F];
412  output[j++] = base64EncTable[(value >> 12) & 0x3F];
413  output[j++] = base64EncTable[(value >> 18) & 0x3F];
414 
415  //Next group
416  k = (k + 22) % 63;
417  }
418 
419  //For the last group there are not enough bytes left in the digest and
420  //the value zero is used in its place
421  value = input[63];
422 
423  //The last group produces two characters as output
424  output[j++] = base64EncTable[value & 0x3F];
425  output[j++] = base64EncTable[(value >> 6) & 0x3F];
426  }
427 
428  //Properly terminate the string with a NULL character
429  output[j] = '\0';
430 
431  //Return the length of the base-64 string
432  return j;
433 }
434 
435 #endif
436 
error_t shaCrypt(const HashAlgo *hashAlgo, const char_t *password, const char_t *salt, char_t *output, size_t *outputLen)
SHA-crypt algorithm.
Definition: sha_crypt.c:62
HashAlgoInit init
Definition: crypto.h:1056
Generic hash algorithm context.
int bool_t
Definition: compiler_port.h:53
uint8_t p
Definition: ndp.h:300
#define TRUE
Definition: os_port.h:50
size_t digestSize
Definition: crypto.h:1052
Unix crypt using SHA-256 and SHA-512.
HashAlgoUpdate update
Definition: crypto.h:1057
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
#define SHA_CRYPT_DEFAULT_ROUNDS
Definition: sha_crypt.h:42
#define osStrcmp(s1, s2)
Definition: os_port.h:171
#define osStrlen(s)
Definition: os_port.h:165
Ipv6Addr prefix
#define MAX_HASH_DIGEST_SIZE
#define FALSE
Definition: os_port.h:46
@ ERROR_UNSUPPORTED_HASH_ALGO
Definition: error.h:130
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
error_t
Error codes.
Definition: error.h:43
#define osSprintf(dest,...)
Definition: os_port.h:231
const char_t * name
Definition: crypto.h:1047
General definitions for cryptographic algorithms.
#define MIN(a, b)
Definition: os_port.h:63
Collection of hash algorithms.
#define SHA_CRYPT_MIN_ROUNDS
Definition: sha_crypt.h:38
HashAlgoFinal final
Definition: crypto.h:1058
size_t shaCryptEncodeBase64(const HashAlgo *hashAlgo, const uint8_t *input, uint8_t *output)
base-64 encoding algorithm
Definition: sha_crypt.c:360
#define SHA_CRYPT_MAX_SALT_LEN
Definition: sha_crypt.h:45
#define osStrtoul(s, endptr, base)
Definition: os_port.h:255
#define MAX(a, b)
Definition: os_port.h:67
char char_t
Definition: compiler_port.h:48
uint8_t n
#define cryptoFreeMem(p)
Definition: crypto.h:791
#define osStrncpy(s1, s2, length)
Definition: os_port.h:213
uint8_t value[]
Definition: tcp.h:369
#define cryptoAllocMem(size)
Definition: crypto.h:786
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
#define osStrncmp(s1, s2, length)
Definition: os_port.h:177
Common interface for hash algorithms.
Definition: crypto.h:1046
#define SHA_CRYPT_MAX_ROUNDS
Definition: sha_crypt.h:40
unsigned int uint_t
Definition: compiler_port.h:50
@ NO_ERROR
Success.
Definition: error.h:44