Fabcoin Core  0.16.2
P2P Digital Currency
crypto_scrypt-check.c
Go to the documentation of this file.
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <math.h>
5 
6 #include "b64.h"
7 #include "slowequals.h"
8 #include "libscrypt.h"
9 
10 #if defined(_WIN32)
11 /* On windows, strtok uses a thread-local static variable in strtok to
12  * make strtok thread-safe. It also neglects to provide a strtok_r. */
13 #define strtok_r(str, val, saveptr) strtok((str), (val))
14 #endif
15 
16 int libscrypt_check(char *mcf, const char *password)
17 {
18  /* Return values:
19  * <0 error
20  * == 0 password incorrect
21  * >0 correct password
22  */
23 
24 #ifndef _WIN32
25  char *saveptr = NULL;
26 #endif
27  uint32_t params;
28  uint64_t N;
29  uint8_t r, p;
30  int retval;
31  uint8_t hashbuf[64];
32  char outbuf[128];
33  uint8_t salt[32];
34  char *tok;
35 
36  if(memcmp(mcf, SCRYPT_MCF_ID, 3) != 0)
37  {
38  /* Only version 0 supported */
39  return -1;
40  }
41 
42  tok = strtok_r(mcf, "$", &saveptr);
43  if ( !tok )
44  return -1;
45 
46  tok = strtok_r(NULL, "$", &saveptr);
47 
48  if ( !tok )
49  return -1;
50 
51  params = (uint32_t)strtoul(tok, NULL, 16);
52  if ( params == 0 )
53  return -1;
54 
55  tok = strtok_r(NULL, "$", &saveptr);
56 
57  if ( !tok )
58  return -1;
59 
60  p = params & 0xff;
61  r = (params >> 8) & 0xff;
62  N = params >> 16;
63 
64  if (N > SCRYPT_SAFE_N)
65  return -1;
66 
67  N = (uint64_t)1 << N;
68 
69  /* Useful debugging:
70  printf("We've obtained salt 'N' r p of '%s' %d %d %d\n", tok, N,r,p);
71  */
72 
73  memset(salt, 0, sizeof(salt)); /* Keeps splint happy */
74  retval = libscrypt_b64_decode(tok, (unsigned char*)salt, sizeof(salt));
75  if (retval < 1)
76  return -1;
77 
78  retval = libscrypt_scrypt((uint8_t*)password, strlen(password), salt,
79  (uint32_t)retval, N, r, p, hashbuf, sizeof(hashbuf));
80 
81  if (retval != 0)
82  return -1;
83 
84  retval = libscrypt_b64_encode((unsigned char*)hashbuf, sizeof(hashbuf),
85  outbuf, sizeof(outbuf));
86 
87  if (retval == 0)
88  return -1;
89 
90  tok = strtok_r(NULL, "$", &saveptr);
91 
92  if ( !tok )
93  return -1;
94 
95  if(slow_equals(tok, outbuf) == 0)
96  return 0;
97 
98  return 1; /* This is the "else" condition */
99 }
100 
#define SCRYPT_SAFE_N
Definition: libscrypt.h:47
int libscrypt_scrypt(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt, size_t saltlen, uint64_t N, uint32_t r, uint32_t p, uint8_t *buf, size_t buflen)
crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen): Compute scrypt(passwd[0 ...
#define SCRYPT_MCF_ID
Definition: libscrypt.h:52
int libscrypt_check(char *mcf, const char *password)
int libscrypt_b64_decode(char const *src, unsigned char *target, size_t targsize)
Definition: b64.c:187
int slow_equals(const char *a, const char *b)
Definition: slowequals.c:5
int libscrypt_b64_encode(unsigned char const *src, size_t srclength, char *target, size_t targsize)
Definition: b64.c:123