File: create_hash.c

package info (click to toggle)
account-utils 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 836 kB
  • sloc: ansic: 8,789; xml: 1,584; sh: 77; makefile: 10
file content (59 lines) | stat: -rw-r--r-- 1,295 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// SPDX-License-Identifier: BSD-2-Clause

#include "config.h"

#include <errno.h>
#include <assert.h>
#include <crypt.h>
#include <syslog.h>

#include "basics.h"
#include "files.h"

int
create_hash(const char *password, const char *prefix,
	    unsigned long count, char **hash, char **error)
{
  /* Strings returned by crypt_gensalt_rn will be no longer than this. */
  char salt[CRYPT_GENSALT_OUTPUT_SIZE];
  _cleanup_free_ struct crypt_data *cdata = NULL;
  char *sp;

  assert(password);
  assert(hash);

  sp = crypt_gensalt_rn(prefix, count, NULL, 0, salt, sizeof(salt));
  if (sp == NULL)
    return -errno;

  cdata = calloc(1, sizeof(*cdata));
  if (cdata == NULL)
    return -ENOMEM;

  sp = crypt_r(password, salt, cdata);
  if (sp == NULL)
    return -errno;

  if (!strneq(sp, prefix, strlen(prefix)))
    {
      /* crypt doesn't know the algorithm, error out */
      int r = -ENOSYS;
      if (error)
	{
	  if (asprintf (error, "Algorithm with prefix '%s' is not supported by the crypto backend.", prefix) < 0)
	    {
	      *error = NULL;
	      r = -ENOMEM;
	    }
	}
      explicit_bzero(cdata, sizeof(struct crypt_data));
      return r;
    }

  *hash = strdup(sp);
  explicit_bzero(cdata, sizeof(struct crypt_data));
  if (*hash == NULL)
    return -ENOMEM;

  return 0;
}