CSM27 : Assorted Tips

Password Encryption Example

The following C program takes a one or two arguments. The first argument is a password, the second, optional, on gives the salt. If the salt is not given, a pseudo-random salt is used.

It is an example of how the crypt(3) function can be used. The output from the program could be pasted directly into a password file for Unix or for apache.

/* (C) 2007: Hans Georg Schaathun  */
/* $Id: tips.php 351 2008-09-12 16:17:39Z css1hs $ */
#define _XOPEN_SOURCE
#include 

/* #include  */
#include 
#include 
#include 
#include 
#include 

char rc ( int t ) ;

int main ( int argc, char *argv[] ) {
  char salt[3];
  int t;
  char *pw;

  if ( ( argc > 3 ) || ( argc < 2 ) ) {
    fprintf ( stderr, "Error: no argument.\n" );
    exit ( 2 ) ;
  };
  if ( 3 == argc ) {
    salt[0] = argv[2][0];
    salt[1] = argv[2][1];
  } else {
    srandom ( time ( NULL ) );
    t = random () % 4096;
    if ( t < 0 ) t = 0 - t;
    salt[0] = rc ( t % 64 ); 
    salt[1] = rc ( t / 64 ); 
  };
  salt[2] = 0 ;

  pw = crypt ( argv[1], salt );

  printf ( "%s\n", pw );
}

char rc ( int t ) {
  if ( t < 0 ) {
    fprintf ( stderr, "Error: INSANE.\n" );
    exit ( 16 ) ;
  };
  if ( t < 26 ) return ( t + 'a') ;
  if ( t < 52 ) return ( t + 'A' - 26 );
  if ( t < 62 ) return ( t + '1' - 36 );
  if ( t == 62 ) return ( '.' );
  if ( t == 63 ) return ( '/' );
  fprintf ( stderr, "Error: INSANE: %i.\n", t );
  exit ( 16 ) ;
}