/* Using the crypt lib, test for a valid password. */

/*
 *
 * example of using the crypt lib to decrypt
 * a DES password encrypted with crypt()
 *
 * remember to compile with -lcrypt
 * gcc -lcrypt -o decrypt decrypt.c
 * 
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

char *crypt(const char *key, const char *salt);
extern char *getpass();

void stripnl(char *str);

int main() {
  char salt[3];
  char *password;
  char encpasswd[15];

  /* Get the password that was encrypted using crypt */
  printf("Enter encrypted password string: ");
  fgets(encpasswd, sizeof(encpasswd), stdin);
  stripnl(encpasswd);

  /* Extract the salt from the encrypted password */
  salt[0] = encpasswd[0];
  salt[1] = encpasswd[1];
  salt[2] = 0;

  /* Get the plain text password, encrypt it with the same
     salt and then compare them. */
  password = getpass("Enter the password: ");
  if(!strcmp(crypt(password, salt), encpasswd))
	printf("Password validated.\n");
  else 
	printf("Password not valid.\n");

}

void stripnl(char *str) {
  while(strlen(str) && ( (str[strlen(str) - 1] == 13) || 
       ( str[strlen(str) - 1] == 10 ))) {
    str[strlen(str) - 1] = 0;
  }
}
