xref: /freebsd/contrib/wpa/wpa_supplicant/wpa_passphrase.c (revision 1d386b48a555f61cb7325543adbbb5c3f3407a66)
1 /*
2  * WPA Supplicant - ASCII passphrase to WPA PSK tool
3  * Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "common.h"
12 #include "crypto/sha1.h"
13 
14 
15 int main(int argc, char *argv[])
16 {
17 	unsigned char psk[32];
18 	int i;
19 	char *ssid, *passphrase, buf[64], *pos;
20 	size_t len;
21 
22 	if (argc < 2) {
23 		printf("usage: wpa_passphrase <ssid> [passphrase]\n"
24 			"\nIf passphrase is left out, it will be read from "
25 			"stdin\n");
26 		return 1;
27 	}
28 
29 	ssid = argv[1];
30 
31 	if (argc > 2) {
32 		passphrase = argv[2];
33 	} else {
34 		fprintf(stderr, "# reading passphrase from stdin\n");
35 		if (fgets(buf, sizeof(buf), stdin) == NULL) {
36 			fprintf(stderr, "Failed to read passphrase\n");
37 			return 1;
38 		}
39 		buf[sizeof(buf) - 1] = '\0';
40 		pos = buf;
41 		while (*pos != '\0') {
42 			if (*pos == '\r' || *pos == '\n') {
43 				*pos = '\0';
44 				break;
45 			}
46 			pos++;
47 		}
48 		passphrase = buf;
49 	}
50 
51 	len = os_strlen(passphrase);
52 	if (len < 8 || len > 63) {
53 		fprintf(stderr, "Passphrase must be 8..63 characters\n");
54 		return 1;
55 	}
56 	if (has_ctrl_char((u8 *) passphrase, len)) {
57 		fprintf(stderr, "Invalid passphrase character\n");
58 		return 1;
59 	}
60 
61 	pbkdf2_sha1(passphrase, (u8 *) ssid, os_strlen(ssid), 4096, psk, 32);
62 
63 	printf("network={\n");
64 	printf("\tssid=\"%s\"\n", ssid);
65 	printf("\t#psk=\"%s\"\n", passphrase);
66 	printf("\tpsk=");
67 	for (i = 0; i < 32; i++)
68 		printf("%02x", psk[i]);
69 	printf("\n");
70 	printf("}\n");
71 
72 	return 0;
73 }
74