(root)/
glibc-2.38/
manual/
examples/
genpass.c
       1  /* Encrypting Passwords
       2     Copyright (C) 1991-2023 Free Software Foundation, Inc.
       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
      15     along with this program; if not, see <https://www.gnu.org/licenses/>.
      16  */
      17  
      18  #include <stdio.h>
      19  #include <unistd.h>
      20  #include <crypt.h>
      21  
      22  int
      23  main(void)
      24  {
      25    unsigned char ubytes[16];
      26    char salt[20];
      27    const char *const saltchars =
      28      "./0123456789ABCDEFGHIJKLMNOPQRST"
      29      "UVWXYZabcdefghijklmnopqrstuvwxyz";
      30    char *hash;
      31    int i;
      32  
      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      }
      55  
      56    /* Print the results.  */
      57    puts (hash);
      58    return 0;
      59  }