#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <sys/time.h>

void
usage( void)
{
   fprintf( stderr, "usage: cpw md5|des\n");
   exit(1);
}

static unsigned char itoa64[] =         /* 0 ... 63 => ascii - 64 */
   "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

void
to64( char *s, long v, int n)
{
   while (--n >= 0) {
      *s++ = itoa64[v&0x3f];
      v >>= 6;
   }
}

int
main( int argc, char **argv)
{
   char buf[ _PASSWORD_LEN+1], salt[10];
   struct timeval tv;
   char *p;

   if ( argc != 2) usage();
   gettimeofday( &tv, 0);
   srandomdev();
   if ( strcmp( argv[1], "md5") == 0) {
      strncpy(&salt[0], "$1$", 3);
      to64(&salt[3], random(), 3);
      to64(&salt[6], tv.tv_usec, 3);
      salt[8] = '\0';
   } else if ( strcmp( argv[1], "des") == 0) {
      to64(&salt[0], random(), 3);
      to64(&salt[3], tv.tv_usec, 3);
      to64(&salt[6], tv.tv_sec, 2);
      salt[8] = '\0';
   } else
      usage();
   p = getpass( "Type password:");
   strcpy( buf, p);
   if ( strcmp( buf, getpass( "Retype password:")) != 0) {
      fprintf( stderr, "Password mismatch\n");
      exit(1);
   }
   printf( "Encrypted password: \"%s\"\n", crypt(buf,salt));
   return 0;
}
