1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 #if !ENABLE_USE_BB_CRYPT
14 /* static const uint8_t ascii64[] ALIGN1 =
15 * "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
18 static int i64c(int i)
28 return ('A' - 12 + i);
29 return ('a' - 38 + i);
32 int FAST_FUNC crypt_make_salt(char *p, int cnt /*, int x */)
35 unsigned x = getpid() + monotonic_us();
37 /* x = (x*1664525 + 1013904223) % 2^32 generator is lame
38 * (low-order bit is not "random", etc...),
39 * but for our purposes it is good enough */
40 x = x*1664525 + 1013904223;
41 /* BTW, Park and Miller's "minimal standard generator" is
42 * x = x*16807 % ((2^31)-1)
43 * It has no problem with visibly alternating lowest bit
44 * but is also weak in cryptographic sense + needs div,
45 * which needs more code (and slower) on many CPUs */
53 char* FAST_FUNC crypt_make_pw_salt(char salt[MAX_PW_SALT_LEN], const char *algo)
56 char *salt_ptr = salt;
58 /* Standard chpasswd uses uppercase algos ("MD5", not "md5").
59 * Need to be case-insensitive in the code below.
61 if ((algo[0]|0x20) != 'd') { /* not des */
62 len = 8/2; /* so far assuming md5 */
66 #if !ENABLE_USE_BB_CRYPT || ENABLE_USE_BB_CRYPT_SHA
67 if ((algo[0]|0x20) == 's') { /* sha */
68 salt[1] = '5' + (strcasecmp(algo, "sha512") == 0);
73 crypt_make_salt(salt_ptr, len);
77 #if ENABLE_USE_BB_CRYPT
80 to64(char *s, unsigned v, int n)
83 /* *s++ = ascii64[v & 0x3f]; */
91 * DES and MD5 crypt implementations are taken from uclibc.
92 * They were modified to not use static buffers.
95 #include "pw_encrypt_des.c"
96 #include "pw_encrypt_md5.c"
97 #if ENABLE_USE_BB_CRYPT_SHA
98 #include "pw_encrypt_sha.c"
101 /* Other advanced crypt ids (TODO?): */
102 /* $2$ or $2a$: Blowfish */
104 static struct const_des_ctx *des_cctx;
105 static struct des_ctx *des_ctx;
107 /* my_crypt returns malloc'ed data */
108 static char *my_crypt(const char *key, const char *salt)
111 if (salt[0] == '$' && salt[1] && salt[2] == '$') {
113 return md5_crypt(xzalloc(MD5_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
114 #if ENABLE_USE_BB_CRYPT_SHA
115 if (salt[1] == '5' || salt[1] == '6')
116 return sha_crypt((char*)key, (char*)salt);
121 des_cctx = const_des_init();
122 des_ctx = des_init(des_ctx, des_cctx);
123 return des_crypt(des_ctx, xzalloc(DES_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
126 /* So far nobody wants to have it public */
127 static void my_crypt_cleanup(void)
135 char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
139 encrypted = my_crypt(clear, salt);
147 #else /* if !ENABLE_USE_BB_CRYPT */
149 char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
153 s = crypt(clear, salt);
155 * glibc used to return "" on malformed salts (for example, ""),
156 * but since 2.17 it returns NULL.
158 return xstrdup(s ? s : "");