]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/examples/genpass.c
Update copyright dates with scripts/update-copyrights
[thirdparty/glibc.git] / manual / examples / genpass.c
CommitLineData
d9a17c07 1/* Encrypting Passwords
2b778ceb 2 Copyright (C) 1991-2021 Free Software Foundation, Inc.
d9a17c07
RM
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
5a82c748 15 along with this program; if not, see <https://www.gnu.org/licenses/>.
d9a17c07
RM
16*/
17
63f791d3 18#include <stdio.h>
63f791d3
GK
19#include <unistd.h>
20#include <crypt.h>
21
d9a17c07 22int
63f791d3
GK
23main(void)
24{
841785ba
ZW
25 unsigned char ubytes[16];
26 char salt[20];
27 const char *const saltchars =
63f791d3
GK
28 "./0123456789ABCDEFGHIJKLMNOPQRST"
29 "UVWXYZabcdefghijklmnopqrstuvwxyz";
841785ba 30 char *hash;
63f791d3 31 int i;
d9a17c07 32
841785ba
ZW
33 /* Retrieve 16 unpredictable bytes from the operating system. */
34 if (getentropy (ubytes, sizeof ubytes))
35 {
36 perror ("getentropy");
37 return 1;
38 }
39
40 /* Use them to fill in the salt string. */
41 salt[0] = '$';
42 salt[1] = '5'; /* SHA-256 */
43 salt[2] = '$';
44 for (i = 0; i < 16; i++)
45 salt[3+i] = saltchars[ubytes[i] & 0x3f];
46 salt[3+i] = '\0';
47
48 /* Read in the user's passphrase and hash it. */
49 hash = crypt (getpass ("Enter new passphrase: "), salt);
50 if (!hash || hash[0] == '*')
51 {
52 perror ("crypt");
53 return 1;
54 }
d9a17c07 55
63f791d3 56 /* Print the results. */
841785ba 57 puts (hash);
63f791d3
GK
58 return 0;
59}