3 * Utility program to generate a public/private key pair
5 * Copyright (C) 1998 by the Massachusetts Institute of Technology
6 * For copying and distribution information, please see the file
11 #include <mit-copyright.h>
15 #include <sys/param.h>
30 void printhex(FILE *out, unsigned char *buf, int len);
32 int main(int argc, char **argv)
34 R_RSA_PRIVATE_KEY private;
35 R_RSA_PUBLIC_KEY public;
36 R_RSA_PROTO_KEY proto;
37 R_RANDOM_STRUCT random;
41 char pubname[MAXPATHLEN], oldname[MAXPATHLEN];
42 char *whoami = argv[0], *inname = argv[1], *outname = argv[2];
44 if (strchr(whoami, '/'))
45 whoami = strrchr(whoami, '/');
49 com_err(NULL, 0, "Usage: %s infile outfile\n"
50 "where infile is a file of random data", whoami);
53 in = fopen(inname, "r");
56 com_err(whoami, errno, "trying to open %s", inname);
60 R_RandomInit(&random);
61 R_GetRandomBytesNeeded(&needed, &random);
63 if (fread(buf, needed, 1, in) != 1)
65 com_err(whoami, 0, "Not enough random input data: need %d bytes\n",
69 R_RandomUpdate(&random, buf, needed);
74 if (R_GeneratePEMKeys(&public, &private, &proto, &random))
76 com_err(whoami, 0, "Couldn't generate key");
80 sprintf(oldname, "%s.old", outname);
81 rename(outname, oldname);
82 out = fopen(outname, "w");
85 com_err(whoami, errno, "opening %s", outname);
88 if (fwrite(&private, sizeof(private), 1, out) != 1)
90 com_err(whoami, errno, "writing %s", outname);
95 sprintf(pubname, "%s.pub", outname);
96 sprintf(oldname, "%s.old", pubname);
97 rename(pubname, oldname);
98 out = fopen(pubname, "w");
101 com_err(whoami, errno, "opening %s", pubname);
104 if (fwrite(&public, sizeof(public), 1, out) != 1)
106 com_err(whoami, errno, "writing %s", pubname);
111 sprintf(pubname, "%s.pub.txt", outname);
112 out = fopen(pubname, "w");
115 com_err(whoami, errno, "opening %s", pubname);
118 printhex(out, public.modulus, MAX_RSA_MODULUS_LEN);
124 char hexd[] = { '0', '1', '2', '3', '4', '5', '6', '7',
125 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
127 void printhex(FILE *out, unsigned char *buf, int len)
131 fprintf(out, "%c%c", hexd[*buf>>4], hexd[*buf%0x10]);