/*
 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
 * of Technology 
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 *
 * Description.
 */

#include "adm_locl.h"

RCSID("$Header: /afs/nada.kth.se/src/packages/kth-krb/SourceRepository/krb4/admin/kstash.c,v 1.2 1995/10/27 10:55:29 bg Exp $");

/* change this later, but krblib_dbm needs it for now */
char   *progname;

static des_cblock master_key;
static des_key_schedule master_key_schedule;
static int kfile;

static void 
clear_secrets(void)
{
    bzero(master_key_schedule, sizeof(master_key_schedule));
    bzero(master_key, sizeof(master_key));
}

int
main(int argc, char **argv)
{
    long    n;
    if ((n = kerb_init())) {
	fprintf(stderr, "Kerberos db and cache init failed = %ld\n", n);
	exit(1);
    }

    if (kdb_get_master_key (TRUE, &master_key, master_key_schedule) != 0) {
      fprintf (stderr, "%s: Couldn't read master key.\n", argv[0]);
      fflush (stderr);
      clear_secrets();
      exit (-1);
    }

    if (kdb_verify_master_key (&master_key, master_key_schedule, stderr) < 0) {
      clear_secrets();
      exit (-1);
    }

    kfile = open(MKEYFILE, O_TRUNC | O_RDWR | O_CREAT, 0600);
    if (kfile < 0) {
	clear_secrets();
	fprintf(stderr, "\n\07\07%s: Unable to open master key file\n",
		argv[0]);
	exit(1);
    }
    if (write(kfile, (char *) master_key, 8) < 0) {
	clear_secrets();
	fprintf(stderr, "\n%s: Write I/O error on master key file\n",
		argv[0]);
	exit(1);
    }
    (void) close(kfile);
    clear_secrets();
    exit(0);
}
