aboutsummaryrefslogblamecommitdiff
path: root/crypt.c
blob: 4c9f0fb92369cee5742b39bedb169f073d5a3544 (plain) (tree)
1
2
3
4
5
6
7
8
9








                                     
 

                                
                                
                
 

                                                       







                                                    

                 
 



                                                                              
                        
                                            
         
 






                                                                             
                                         
                                       
         
 

                           
 

  
                                
   
                         
 

                                         
 

  
                                                       
   
                                    
 

                                                        
 
#define _XOPEN_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strerror(3) */
#include <unistd.h> /* crypt(3) */

void error(char *);
void usage(FILE *, int);

int main (int argc, char **argv)
{
	char *hash, *key, *salt;
	int opt;

	while ((opt = getopt(argc, argv, "h")) != -1) {
		switch (opt) {
		case 'h': /* Help */
			usage(stdout, EXIT_SUCCESS);
			break;
		case '?': /* Unknown option */
			usage(stderr, EXIT_FAILURE);
			break;
		default: /* Shouldn't happen */
			abort();
		}
	}

	/*
	 * If we don't have three arguments left after processing the options,
	 * exit with usage information and error status
	 */
	if (argc != 3) {
		usage(stderr, EXIT_FAILURE);
	}

	key = argv[1];
	salt = argv[2];

	/*
	 * Create the hash, but exit immediately with the system error string
	 * if it returns a null pointer (error condition)
	 */
	if (!(hash = crypt(key, salt))) {
		error(strerror(errno));
	}

	puts(hash);
	exit(EXIT_SUCCESS);
}

/*
 * Exit with error error message
 */
void error(char *message)
{
	fprintf(stderr, "%s\n", message);
	exit(EXIT_FAILURE);
}

/*
 * Show usage to given stream, and exit with given code
 */
void usage(FILE *stream, int status)
{
	fputs("USAGE: crypt [-h | KEY SALT]\n", stream);
	exit(status);
}