762cbab27ab001ea498b8d5792242beebe31ecac
[oweals/busybox.git] / libbb / pw_encrypt.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routine.
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include "libbb.h"
11
12 /*
13  * DES and MD5 crypt implementations are taken from uclibc.
14  * They were modified to not use static buffers.
15  * Comparison with uclibc (before uclibc had 70k staic buffers reinstated):
16  *   text    data     bss     dec     hex filename
17  * 759909     604    6684  767197   bb4dd busybox_old
18  * 759579     604    6684  766867   bb393 busybox_unstripped
19  */
20 /* Common for them */
21 static const uint8_t ascii64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
22 #include "pw_encrypt_des.c"
23 #include "pw_encrypt_md5.c"
24
25
26 static struct const_des_ctx *des_cctx;
27 static struct des_ctx *des_ctx;
28
29 /* my_crypt returns malloc'ed data */
30 static char *my_crypt(const char *key, const char *salt)
31 {
32         /* First, check if we are supposed to be using the MD5 replacement
33          * instead of DES...  */
34         if (salt[0] == '$' && salt[1] == '1' && salt[2] == '$') {
35                 return md5_crypt(xzalloc(MD5_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
36         }
37
38         {
39                 if (!des_cctx)
40                         des_cctx = const_des_init();
41                 des_ctx = des_init(des_ctx, des_cctx);
42                 return des_crypt(des_ctx, xzalloc(DES_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
43         }
44 }
45
46 /* So far nobody wants to have it public */
47 static void my_crypt_cleanup(void)
48 {
49         free(des_cctx);
50         free(des_ctx);
51         des_cctx = NULL;
52         des_ctx = NULL;
53 }
54
55 char *pw_encrypt(const char *clear, const char *salt, int cleanup)
56 {
57         char *encrypted;
58
59 #if 0 /* was CONFIG_FEATURE_SHA1_PASSWORDS, but there is no such thing??? */
60         if (strncmp(salt, "$2$", 3) == 0) {
61                 return sha1_crypt(clear);
62         }
63 #endif
64
65         encrypted = my_crypt(clear, salt);
66
67         if (cleanup)
68                 my_crypt_cleanup();
69
70         return encrypted;
71 }