]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - puttygen.c
Jacob's patch to make passphrase boxes work more sanely
[PuTTY.git] / puttygen.c
1 /*
2  * PuTTY key generation front end.
3  */
4
5 #include <windows.h>
6 #include <commctrl.h>
7 #include <time.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 #define PUTTY_DO_GLOBALS
12
13 #include "putty.h"
14 #include "ssh.h"
15 #include "winstuff.h"
16
17 #define WM_DONEKEY (WM_XUSER + 1)
18
19 #define DEFAULT_KEYSIZE 1024
20
21 /* ----------------------------------------------------------------------
22  * Progress report code. This is really horrible :-)
23  */
24 #define PHASE1TOTAL 0x10000
25 #define PHASE2TOTAL 0x10000
26 #define PHASE3TOTAL 0x04000
27 #define PHASE1START 0
28 #define PHASE2START (PHASE1TOTAL)
29 #define PHASE3START (PHASE1TOTAL + PHASE2TOTAL)
30 #define TOTALTOTAL  (PHASE1TOTAL + PHASE2TOTAL + PHASE3TOTAL)
31 #define PROGRESSBIGRANGE 65535
32 #define DIVISOR     ((TOTALTOTAL + PROGRESSBIGRANGE - 1) / PROGRESSBIGRANGE)
33 #define PROGRESSRANGE (TOTALTOTAL / DIVISOR)
34 struct progress {
35     unsigned phase1param, phase1current, phase1n;
36     unsigned phase2param, phase2current, phase2n;
37     unsigned phase3mult;
38     HWND progbar;
39 };
40
41 static void progress_update(void *param, int phase, int iprogress) {
42     struct progress *p = (struct progress *)param;
43     unsigned progress = iprogress;
44     int position;
45
46     switch (phase) {
47       case -1:
48         p->phase1param = 0x10000 + progress;
49         p->phase1current = 0x10000; p->phase1n = 0;
50         return;
51       case -2:
52         p->phase2param = 0x10000 + progress;
53         p->phase2current = 0x10000; p->phase2n = 0;
54         return;
55       case -3:
56         p->phase3mult = PHASE3TOTAL / progress;
57         return;
58       case 1:
59         while (p->phase1n < progress) {
60             p->phase1n++;
61             p->phase1current *= p->phase1param;
62             p->phase1current /= 0x10000;
63         }
64         position = PHASE1START + 0x10000 - p->phase1current;
65         break;
66       case 2:
67         while (p->phase2n < progress) {
68             p->phase2n++;
69             p->phase2current *= p->phase2param;
70             p->phase2current /= 0x10000;
71         }
72         position = PHASE2START + 0x10000 - p->phase2current;
73         break;
74       case 3:
75         position = PHASE3START + progress * p->phase3mult;
76         break;
77     }
78
79     SendMessage(p->progbar, PBM_SETPOS, position / DIVISOR, 0);
80 }
81
82 extern char ver[];
83
84 #define PASSPHRASE_MAXLEN 512
85
86 struct PassphraseProcStruct {
87     char *passphrase;
88     char *comment;
89 };
90
91 /*
92  * Dialog-box function for the passphrase box.
93  */
94 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
95                                    WPARAM wParam, LPARAM lParam) {
96     static char *passphrase = NULL;
97     struct PassphraseProcStruct *p;
98
99     switch (msg) {
100       case WM_INITDIALOG:
101         SetForegroundWindow(hwnd);
102         SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
103                       SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
104
105         /*
106          * Centre the window.
107          */
108         {                              /* centre the window */
109             RECT rs, rd;
110             HWND hw;
111
112             hw = GetDesktopWindow();
113             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
114                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
115                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
116                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
117         }
118
119         p = (struct PassphraseProcStruct *)lParam;
120         passphrase = p->passphrase;
121         if (p->comment)
122             SetDlgItemText(hwnd, 101, p->comment);
123         *passphrase = 0;
124         SetDlgItemText(hwnd, 102, passphrase);
125         return 0;
126       case WM_COMMAND:
127         switch (LOWORD(wParam)) {
128           case IDOK:
129             if (*passphrase)
130                 EndDialog (hwnd, 1);
131             else
132                 MessageBeep (0);
133             return 0;
134           case IDCANCEL:
135             EndDialog (hwnd, 0);
136             return 0;
137           case 102:                    /* edit box */
138             if ((HIWORD(wParam) == EN_CHANGE) && passphrase) {
139                 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
140                 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
141             }
142             return 0;
143         }
144         return 0;
145       case WM_CLOSE:
146         EndDialog (hwnd, 0);
147         return 0;
148     }
149     return 0;
150 }
151
152 /*
153  * Prompt for a key file. Assumes the filename buffer is of size
154  * FILENAME_MAX.
155  */
156 static int prompt_keyfile(HWND hwnd, char *dlgtitle,
157                           char *filename, int save) {
158     OPENFILENAME of;
159     memset(&of, 0, sizeof(of));
160 #ifdef OPENFILENAME_SIZE_VERSION_400
161     of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
162 #else
163     of.lStructSize = sizeof(of);
164 #endif
165     of.hwndOwner = hwnd;
166     of.lpstrFilter = "All Files\0*\0\0\0";
167     of.lpstrCustomFilter = NULL;
168     of.nFilterIndex = 1;
169     of.lpstrFile = filename; *filename = '\0';
170     of.nMaxFile = FILENAME_MAX;
171     of.lpstrFileTitle = NULL;
172     of.lpstrInitialDir = NULL;
173     of.lpstrTitle = dlgtitle;
174     of.Flags = 0;
175     if (save)
176         return GetSaveFileName(&of);
177     else
178         return GetOpenFileName(&of);
179 }
180
181 /*
182  * This function is needed to link with the DES code. We need not
183  * have it do anything at all.
184  */
185 void logevent(char *msg) {
186 }
187
188 /*
189  * Dialog-box function for the Licence box.
190  */
191 static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
192                                  WPARAM wParam, LPARAM lParam) {
193     switch (msg) {
194       case WM_INITDIALOG:
195         /*
196          * Centre the window.
197          */
198         {                              /* centre the window */
199             RECT rs, rd;
200             HWND hw;
201
202             hw = GetDesktopWindow();
203             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
204                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
205                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
206                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
207         }
208
209         return 1;
210       case WM_COMMAND:
211         switch (LOWORD(wParam)) {
212           case IDOK:
213             EndDialog(hwnd, 1);
214             return 0;
215         }
216         return 0;
217       case WM_CLOSE:
218         EndDialog(hwnd, 1);
219         return 0;
220     }
221     return 0;
222 }
223
224 /*
225  * Dialog-box function for the About box.
226  */
227 static int CALLBACK AboutProc (HWND hwnd, UINT msg,
228                                WPARAM wParam, LPARAM lParam) {
229     switch (msg) {
230       case WM_INITDIALOG:
231         /*
232          * Centre the window.
233          */
234         {                              /* centre the window */
235             RECT rs, rd;
236             HWND hw;
237
238             hw = GetDesktopWindow();
239             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
240                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
241                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
242                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
243         }
244
245         SetDlgItemText (hwnd, 100, ver);
246         return 1;
247       case WM_COMMAND:
248         switch (LOWORD(wParam)) {
249           case IDOK:
250             EndDialog(hwnd, 1);
251             return 0;
252           case 101:
253             EnableWindow(hwnd, 0);
254             DialogBox (hinst, MAKEINTRESOURCE(214), NULL, LicenceProc);
255             EnableWindow(hwnd, 1);
256             SetActiveWindow(hwnd);
257             return 0;
258         }
259         return 0;
260       case WM_CLOSE:
261         EndDialog(hwnd, 1);
262         return 0;
263     }
264     return 0;
265 }
266
267 /*
268  * Thread to generate a key.
269  */
270 struct rsa_key_thread_params {
271     HWND progressbar;                  /* notify this with progress */
272     HWND dialog;                       /* notify this on completion */
273     int keysize;                       /* bits in key */
274     struct RSAKey *key;
275 };
276 static DWORD WINAPI generate_rsa_key_thread(void *param) {
277     struct rsa_key_thread_params *params =
278         (struct rsa_key_thread_params *)param;
279     struct progress prog;
280     prog.progbar = params->progressbar;
281
282     rsa_generate(params->key, params->keysize, progress_update, &prog);
283
284     PostMessage(params->dialog, WM_DONEKEY, 0, 0);
285
286     sfree(params);
287     return 0;
288 }
289
290 struct MainDlgState {
291     int collecting_entropy;
292     int generation_thread_exists;
293     int key_exists;
294     int entropy_got, entropy_required, entropy_size;
295     int keysize;
296     int ssh2;
297     char **commentptr;                 /* points to key.comment or ssh2key.comment */
298     struct ssh2_userkey ssh2key;
299     unsigned *entropy;
300     struct RSAKey key;
301 };
302
303 static void hidemany(HWND hwnd, const int *ids, int hideit) {
304     while (*ids) {
305         ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW));
306     }
307 }
308
309 static void setupbigedit1(HWND hwnd, int id, struct RSAKey *key) {
310     char *buffer;
311     char *dec1, *dec2;
312
313     dec1 = bignum_decimal(key->exponent);
314     dec2 = bignum_decimal(key->modulus);
315     buffer = smalloc(strlen(dec1)+strlen(dec2)+
316                      strlen(key->comment)+30);
317     sprintf(buffer, "%d %s %s %s",
318             bignum_bitcount(key->modulus),
319             dec1, dec2, key->comment);
320     SetDlgItemText(hwnd, id, buffer);
321     sfree(dec1);
322     sfree(dec2);
323     sfree(buffer);
324 }
325
326 static void setupbigedit2(HWND hwnd, int id, struct ssh2_userkey *key) {
327     unsigned char *pub_blob;
328     char *buffer, *p;
329     int pub_len;
330     int i;
331
332     pub_blob = key->alg->public_blob(key->data, &pub_len);
333     buffer = smalloc(strlen(key->alg->name) + 4*((pub_len+2)/3) +
334                      strlen(key->comment) + 3);
335     strcpy(buffer, key->alg->name);
336     p = buffer + strlen(buffer);
337     *p++ = ' ';
338     i = 0;
339     while (i < pub_len) {
340         int n = (pub_len-i < 3 ? pub_len-i : 3);
341         base64_encode_atom(pub_blob+i, n, p);
342         i += n;
343         p += 4;
344     }
345     *p++ = ' ';
346     strcpy(p, key->comment);
347     SetDlgItemText(hwnd, id, buffer);
348     sfree(pub_blob);
349     sfree(buffer);    
350 }
351
352 /*
353  * Dialog-box function for the main PuTTYgen dialog box.
354  */
355 static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
356                                  WPARAM wParam, LPARAM lParam) {
357     enum {
358         controlidstart = 100,
359         IDC_TITLE,
360         IDC_BOX_KEY,
361         IDC_NOKEY,
362         IDC_GENERATING,
363         IDC_PROGRESS,
364         IDC_PKSTATIC, IDC_KEYDISPLAY,
365         IDC_FPSTATIC, IDC_FINGERPRINT,
366         IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
367         IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
368         IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT,
369         IDC_BOX_ACTIONS,
370         IDC_GENSTATIC, IDC_GENERATE,
371         IDC_LOADSTATIC, IDC_LOAD,
372         IDC_SAVESTATIC, IDC_SAVE,
373         IDC_BOX_PARAMS,
374         IDC_TYPESTATIC, IDC_KEYSSH1, IDC_KEYSSH2RSA,
375         IDC_BITSSTATIC, IDC_BITS,
376         IDC_ABOUT,
377     };
378     static const int nokey_ids[] = { IDC_NOKEY, 0 };
379     static const int generating_ids[] = { IDC_GENERATING, IDC_PROGRESS, 0 };
380     static const int gotkey_ids[] = {
381         IDC_PKSTATIC, IDC_KEYDISPLAY,
382         IDC_FPSTATIC, IDC_FINGERPRINT,
383         IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
384         IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
385         IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 0 };
386     static const char generating_msg[] =
387         "Please wait while a key is generated...";
388     static const char entropy_msg[] =
389         "Please generate some randomness by moving the mouse over the blank area.";
390     struct MainDlgState *state;
391
392     switch (msg) {
393       case WM_INITDIALOG:
394         /*
395          * Centre the window.
396          */
397         {                              /* centre the window */
398             RECT rs, rd;
399             HWND hw;
400
401             hw = GetDesktopWindow();
402             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
403                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
404                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
405                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
406         }
407
408         state = smalloc(sizeof(*state));
409         state->generation_thread_exists = FALSE;
410         state->collecting_entropy = FALSE;
411         state->entropy = NULL;
412         state->key_exists = FALSE;
413         SetWindowLong(hwnd, GWL_USERDATA, (LONG)state);
414         {
415             struct ctlpos cp, cp2;
416
417             /* Accelerators used: acglops */
418
419             ctlposinit(&cp, hwnd, 10, 10, 10);
420             bartitle(&cp, "Public and private key generation for PuTTY",
421                     IDC_TITLE);
422             beginbox(&cp, "Key",
423                      IDC_BOX_KEY);
424             cp2 = cp;
425             statictext(&cp2, "No key.", IDC_NOKEY);
426             cp2 = cp;
427             statictext(&cp2, "",
428                        IDC_GENERATING);
429             progressbar(&cp2, IDC_PROGRESS);
430             bigeditctrl(&cp,
431                         "&Public key for pasting into authorized_keys file:",
432                         IDC_PKSTATIC, IDC_KEYDISPLAY, 7);
433             SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
434             staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
435                        IDC_FINGERPRINT, 75);
436             SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1, 0);
437             staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
438                        IDC_COMMENTEDIT, 75);
439             staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
440                            IDC_PASSPHRASE1EDIT, 75);
441             staticpassedit(&cp, "C&onfirm passphrase:", IDC_PASSPHRASE2STATIC,
442                            IDC_PASSPHRASE2EDIT, 75);
443             endbox(&cp);
444             beginbox(&cp, "Actions",
445                      IDC_BOX_ACTIONS);
446             staticbtn(&cp, "Generate a public/private key pair",
447                       IDC_GENSTATIC, "&Generate", IDC_GENERATE);
448             staticbtn(&cp, "Load an existing private key file",
449                       IDC_LOADSTATIC, "&Load", IDC_LOAD);
450             staticbtn(&cp, "Save the generated key to a new file",
451                       IDC_SAVESTATIC, "&Save", IDC_SAVE);
452             endbox(&cp);
453             beginbox(&cp, "Parameters",
454                      IDC_BOX_PARAMS);
455             radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 2,
456                           "SSH&1 (RSA)", IDC_KEYSSH1,
457                           "SSH2 &RSA", IDC_KEYSSH2RSA, NULL);
458             staticedit(&cp, "Number of &bits in a generated key:",
459                        IDC_BITSSTATIC, IDC_BITS, 20);
460             endbox(&cp);
461         }
462         CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2RSA, IDC_KEYSSH1);
463         SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);
464
465         /*
466          * Initially, hide the progress bar and the key display,
467          * and show the no-key display. Also disable the Save
468          * button, because with no key we obviously can't save
469          * anything.
470          */
471         hidemany(hwnd, nokey_ids, FALSE);
472         hidemany(hwnd, generating_ids, TRUE);
473         hidemany(hwnd, gotkey_ids, TRUE);
474         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
475
476         return 1;
477       case WM_MOUSEMOVE:
478         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
479         if (state->collecting_entropy &&
480             state->entropy &&
481             state->entropy_got < state->entropy_required) {
482             state->entropy[state->entropy_got++] = lParam;
483             state->entropy[state->entropy_got++] = GetMessageTime();
484             SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
485                                state->entropy_got, 0);
486             if (state->entropy_got >= state->entropy_required) {
487                 struct rsa_key_thread_params *params;
488                 DWORD threadid;
489
490                 /*
491                  * Seed the entropy pool
492                  */
493                 random_add_heavynoise(state->entropy, state->entropy_size);
494                 memset(state->entropy, 0, state->entropy_size);
495                 sfree(state->entropy);
496                 state->collecting_entropy = FALSE;
497
498                 SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
499                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
500                                    MAKELPARAM(0, PROGRESSRANGE));
501                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
502
503                 params = smalloc(sizeof(*params));
504                 params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
505                 params->dialog = hwnd;
506                 params->keysize = state->keysize;
507                 params->key = &state->key;
508
509                 if (!CreateThread(NULL, 0, generate_rsa_key_thread,
510                                   params, 0, &threadid)) {
511                     MessageBox(hwnd, "Out of thread resources",
512                                "Key generation error",
513                                MB_OK | MB_ICONERROR);
514                     sfree(params);
515                 } else {
516                     state->generation_thread_exists = TRUE;
517                 }
518             }
519         }
520         break;
521       case WM_COMMAND:
522         switch (LOWORD(wParam)) {
523           case IDC_COMMENTEDIT:
524             if (HIWORD(wParam) == EN_CHANGE) {
525                 state = (struct MainDlgState *)
526                     GetWindowLong(hwnd, GWL_USERDATA);
527                 if (state->key_exists) {
528                     HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
529                     int len = GetWindowTextLength(editctl);
530                     if (*state->commentptr)
531                         sfree(*state->commentptr);
532                     *state->commentptr = smalloc(len+1);
533                     GetWindowText(editctl, *state->commentptr, len+1);
534                     if (state->ssh2) {
535                         setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
536                     } else {
537                         setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
538                     }
539                 }
540             }
541             break;
542           case IDC_ABOUT:
543             EnableWindow(hwnd, 0);
544             DialogBox (hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
545             EnableWindow(hwnd, 1);
546             SetActiveWindow(hwnd);
547             return 0;
548           case IDC_GENERATE:
549             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
550             if (!state->generation_thread_exists) {
551                 BOOL ok;
552                 state->keysize = GetDlgItemInt(hwnd, IDC_BITS,
553                                                &ok, FALSE);
554                 if (!ok) state->keysize = DEFAULT_KEYSIZE;
555                 /* If we ever introduce a new key type, check it here! */
556                 state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
557                 if (state->keysize < 256) {
558                     int ret = MessageBox(hwnd,
559                                          "PuTTYgen will not generate a key"
560                                          " smaller than 256 bits.\n"
561                                          "Key length reset to 256. Continue?",
562                                          "PuTTYgen Warning",
563                                          MB_ICONWARNING | MB_OKCANCEL);
564                     if (ret != IDOK)
565                         break;
566                     state->keysize = 256;
567                     SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
568                 }
569                 hidemany(hwnd, nokey_ids, TRUE);
570                 hidemany(hwnd, generating_ids, FALSE);
571                 hidemany(hwnd, gotkey_ids, TRUE);
572                 EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
573                 EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
574                 EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
575                 state->key_exists = FALSE;
576                 SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
577                 state->collecting_entropy = TRUE;
578
579                 /*
580                  * My brief statistical tests on mouse movements
581                  * suggest that there are about 2.5 bits of
582                  * randomness in the x position, 2.5 in the y
583                  * position, and 1.7 in the message time, making
584                  * 5.7 bits of unpredictability per mouse movement.
585                  * However, other people have told me it's far less
586                  * than that, so I'm going to be stupidly cautious
587                  * and knock that down to a nice round 2. With this
588                  * method, we require two words per mouse movement,
589                  * so with 2 bits per mouse movement we expect 2
590                  * bits every 2 words.
591                  */
592                 state->entropy_required = (state->keysize/2) * 2;
593                 state->entropy_got = 0;
594                 state->entropy_size = (state->entropy_required *
595                                        sizeof(*state->entropy));
596                 state->entropy = smalloc(state->entropy_size);
597
598                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
599                                    MAKELPARAM(0, state->entropy_required));
600                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
601             }
602             break;
603           case IDC_SAVE:
604             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
605             if (state->key_exists) {
606                 char filename[FILENAME_MAX];
607                 char passphrase[PASSPHRASE_MAXLEN];
608                 char passphrase2[PASSPHRASE_MAXLEN];
609                 GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
610                                passphrase, sizeof(passphrase));
611                 GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
612                                passphrase2, sizeof(passphrase2));
613                 if (strcmp(passphrase, passphrase2)) {
614                     MessageBox(hwnd,
615                                "The two passphrases given do not match.",
616                                "PuTTYgen Error",
617                                MB_OK | MB_ICONERROR);
618                     break;
619                 }
620                 if (!*passphrase) {
621                     int ret;
622                     ret = MessageBox(hwnd,
623                                      "Are you sure you want to save this key\n"
624                                      "without a passphrase to protect it?",
625                                      "PuTTYgen Warning",
626                                      MB_YESNO | MB_ICONWARNING);
627                     if (ret != IDYES)
628                         break;
629                 }
630                 if (prompt_keyfile(hwnd, "Save private key as:",
631                                    filename, 1)) {
632                     int ret;
633                     FILE *fp = fopen(filename, "r");
634                     if (fp) {
635                         char buffer[FILENAME_MAX+80];
636                         fclose(fp);
637                         sprintf(buffer, "Overwrite existing file\n%.*s?",
638                                 FILENAME_MAX, filename);
639                         ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
640                                          MB_YESNO | MB_ICONWARNING);
641                         if (ret != IDYES)
642                             break;
643                     }
644                     if (state->ssh2) {
645                         ret = ssh2_save_userkey(filename, &state->ssh2key,
646                                                 *passphrase ? passphrase : NULL);
647                     } else {
648                         ret = saversakey(filename, &state->key,
649                                          *passphrase ? passphrase : NULL);
650                     }
651                     if (ret <= 0) {
652                         MessageBox(hwnd, "Unable to save key file",
653                                    "PuTTYgen Error",
654                                    MB_OK | MB_ICONERROR);
655                     }
656                 }
657             }
658             break;
659           case IDC_LOAD:
660             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
661             if (!state->generation_thread_exists) {
662                 char filename[FILENAME_MAX];
663                 if (prompt_keyfile(hwnd, "Load private key:",
664                                    filename, 0)) {
665                     char passphrase[PASSPHRASE_MAXLEN];
666                     int needs_pass;
667                     int ver;
668                     int ret;
669                     char *comment;
670                     struct PassphraseProcStruct pps;
671                     struct RSAKey newkey1;
672                     struct ssh2_userkey *newkey2;
673
674                     ver = keyfile_version(filename);
675                     if (ver == 0) {
676                         MessageBox(NULL, "Couldn't load private key.",
677                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
678                         break;
679                     }
680
681                     comment = NULL;
682                     if (ver == 1)
683                         needs_pass = rsakey_encrypted(filename, &comment);
684                     else
685                         needs_pass = ssh2_userkey_encrypted(filename, &comment);
686                     pps.passphrase = passphrase;
687                     pps.comment = comment;
688                     do {
689                         if (needs_pass) {
690                             int dlgret;
691                             dlgret = DialogBoxParam(hinst,
692                                                     MAKEINTRESOURCE(210),
693                                                     NULL, PassphraseProc,
694                                                     (LPARAM)&pps);
695                             if (!dlgret) {
696                                 ret = -2;
697                                 break;
698                             }
699                         } else
700                             *passphrase = '\0';
701                         if (ver == 1)
702                             ret = loadrsakey(filename, &newkey1, passphrase);
703                         else {
704                             newkey2 = ssh2_load_userkey(filename, passphrase);
705                             if (newkey2 == SSH2_WRONG_PASSPHRASE)
706                                 ret = -1;
707                             else if (!newkey2)
708                                 ret = 0;
709                             else
710                                 ret = 1;
711                         }
712                     } while (ret == -1);
713                     if (comment) sfree(comment);
714                     if (ret == 0) {
715                         MessageBox(NULL, "Couldn't load private key.",
716                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
717                     } else if (ret == 1) {
718                         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
719                         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
720                         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
721                         /*
722                          * Now update the key controls with all the
723                          * key data.
724                          */
725                         {
726                             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
727                                            passphrase);
728                             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
729                                            passphrase);
730                             if (ver == 1) {
731                                 char buf[128];
732                                 char *savecomment;
733
734                                 state->ssh2 = FALSE;
735                                 state->commentptr = &state->key.comment;
736                                 state->key = newkey1;
737
738                                 /*
739                                  * Set the key fingerprint.
740                                  */
741                                 savecomment = state->key.comment;
742                                 state->key.comment = NULL;
743                                 rsa_fingerprint(buf, sizeof(buf), &state->key);
744                                 state->key.comment = savecomment;
745
746                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
747                                 /*
748                                  * Construct a decimal representation
749                                  * of the key, for pasting into
750                                  * .ssh/authorized_keys on a Unix box.
751                                  */
752                                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
753                             } else {
754                                 char *fp;
755                                 char *savecomment;
756
757                                 state->ssh2 = TRUE;
758                                 state->commentptr = &state->ssh2key.comment;
759                                 state->ssh2key = *newkey2;   /* structure copy */
760                                 sfree(newkey2);
761
762                                 savecomment = state->ssh2key.comment;
763                                 state->ssh2key.comment = NULL;
764                                 fp = state->
765                                     ssh2key.alg->fingerprint(state->ssh2key.data);
766                                 state->ssh2key.comment = savecomment;
767
768                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
769                                 sfree(fp);
770
771                                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
772                             }
773                             SetDlgItemText(hwnd, IDC_COMMENTEDIT,
774                                            *state->commentptr);
775                         }
776                         /*
777                          * Finally, hide the progress bar and show
778                          * the key data.
779                          */
780                         hidemany(hwnd, nokey_ids, TRUE);
781                         hidemany(hwnd, generating_ids, TRUE);
782                         hidemany(hwnd, gotkey_ids, FALSE);
783                         state->key_exists = TRUE;
784                     }
785                 }
786             }
787             break;
788         }
789         return 0;
790       case WM_DONEKEY:
791         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
792         state->generation_thread_exists = FALSE;
793         state->key_exists = TRUE;
794         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
795         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
796         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
797         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
798         if (state->ssh2) {
799             state->ssh2key.data = &state->key;
800             state->ssh2key.alg = &ssh_rsa;
801             state->commentptr = &state->ssh2key.comment;
802         } else {
803             state->commentptr = &state->key.comment;
804         }
805         /*
806          * Invent a comment for the key. We'll do this by including
807          * the date in it. This will be so horrifyingly ugly that
808          * the user will immediately want to change it, which is
809          * what we want :-)
810          */
811         *state->commentptr = smalloc(30);
812         {
813             time_t t;
814             struct tm *tm;
815             time(&t);
816             tm = localtime(&t);
817             strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
818         }
819             
820         /*
821          * Now update the key controls with all the key data.
822          */
823         {
824             char *savecomment;
825             /*
826              * Blank passphrase, initially. This isn't dangerous,
827              * because we will warn (Are You Sure?) before allowing
828              * the user to save an unprotected private key.
829              */
830             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
831             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
832             /*
833              * Set the comment.
834              */
835             SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
836             /*
837              * Set the key fingerprint.
838              */
839             savecomment = *state->commentptr;
840             *state->commentptr = NULL;
841             if (state->ssh2) {
842                 char *fp;
843                 fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
844                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
845                 sfree(fp);
846             } else {
847                 char buf[128];
848                 rsa_fingerprint(buf, sizeof(buf), &state->key);
849                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
850             }
851             *state->commentptr = savecomment;
852             /*
853              * Construct a decimal representation of the key, for
854              * pasting into .ssh/authorized_keys on a Unix box.
855              */
856             if (state->ssh2) {
857                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
858             } else {
859                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
860             }
861         }
862         /*
863          * Finally, hide the progress bar and show the key data.
864          */
865         hidemany(hwnd, nokey_ids, TRUE);
866         hidemany(hwnd, generating_ids, TRUE);
867         hidemany(hwnd, gotkey_ids, FALSE);
868         break;
869       case WM_CLOSE:
870         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
871         sfree(state);
872         EndDialog(hwnd, 1);
873         return 0;
874     }
875     return 0;
876 }
877
878 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
879     InitCommonControls();
880     hinst = inst;
881     random_init();
882     return DialogBox(hinst, MAKEINTRESOURCE(201), NULL, MainDlgProc) != IDOK;
883 }