Logo  

CS473 - Computer Networks

Displaying exercises/e8/solution/mkpwd.c

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <crypt.h>

#define K	1024

// Compile with gcc -o mkpwd mkpwd.c -lcrypt

char *saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";

int main(int argc, char *argv[])
{
  int i;

  if (argc < 3) {
    printf("Usage: <username> <password>\n");
    exit(0);
  }

  srand(time(0)+getpid());
  char *username = argv[1];
  char *password = argv[2];

  char salt[33], buf[K];
  for(i=0; i < 32; i++)
    salt[i] = saltchars[rand()%strlen(saltchars)];
  salt[i] = '\0';

  sprintf(buf,"$5$rounds=5000$%s", salt);
  
  FILE *db = fopen("auth.db", "a");
  if (db == NULL) {
    perror("fopen");
    exit(0);
  }
  fprintf(db,"%s:%s\n", username, crypt(password, buf));
  fclose(db);

  return 0;
}