Blame manual/examples/genpass.c

Packit 6c4009
/* Encrypting Passwords
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <unistd.h>
Packit 6c4009
#include <crypt.h>
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main(void)
Packit 6c4009
{
Packit 6c4009
  unsigned char ubytes[16];
Packit 6c4009
  char salt[20];
Packit 6c4009
  const char *const saltchars =
Packit 6c4009
    "./0123456789ABCDEFGHIJKLMNOPQRST"
Packit 6c4009
    "UVWXYZabcdefghijklmnopqrstuvwxyz";
Packit 6c4009
  char *hash;
Packit 6c4009
  int i;
Packit 6c4009
Packit 6c4009
  /* Retrieve 16 unpredictable bytes from the operating system.  */
Packit 6c4009
  if (getentropy (ubytes, sizeof ubytes))
Packit 6c4009
    {
Packit 6c4009
      perror ("getentropy");
Packit 6c4009
      return 1;
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Use them to fill in the salt string.  */
Packit 6c4009
  salt[0] = '$';
Packit 6c4009
  salt[1] = '5'; /* SHA-256 */
Packit 6c4009
  salt[2] = '$';
Packit 6c4009
  for (i = 0; i < 16; i++)
Packit 6c4009
    salt[3+i] = saltchars[ubytes[i] & 0x3f];
Packit 6c4009
  salt[3+i] = '\0';
Packit 6c4009
Packit 6c4009
  /* Read in the user's passphrase and hash it.  */
Packit 6c4009
  hash = crypt (getpass ("Enter new passphrase: "), salt);
Packit 6c4009
  if (!hash || hash[0] == '*')
Packit 6c4009
    {
Packit 6c4009
      perror ("crypt");
Packit 6c4009
      return 1;
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Print the results.  */
Packit 6c4009
  puts (hash);
Packit 6c4009
  return 0;
Packit 6c4009
}