xref: /freebsd/contrib/wireguard-tools/pubkey.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4  */
5 
6 #include <errno.h>
7 #include <stdio.h>
8 
9 #include "curve25519.h"
10 #include "encoding.h"
11 #include "subcommands.h"
12 #include "ctype.h"
13 
14 int pubkey_main(int argc, const char *argv[])
15 {
16 	uint8_t key[WG_KEY_LEN] __attribute__((aligned(sizeof(uintptr_t))));
17 	char base64[WG_KEY_LEN_BASE64];
18 	int trailing_char;
19 
20 	if (argc != 1) {
21 		fprintf(stderr, "Usage: %s %s\n", PROG_NAME, argv[0]);
22 		return 1;
23 	}
24 
25 	if (fread(base64, 1, sizeof(base64) - 1, stdin) != sizeof(base64) - 1) {
26 		errno = EINVAL;
27 		fprintf(stderr, "%s: Key is not the correct length or format\n", PROG_NAME);
28 		return 1;
29 	}
30 	base64[WG_KEY_LEN_BASE64 - 1] = '\0';
31 
32 	for (;;) {
33 		trailing_char = getc(stdin);
34 		if (!trailing_char || char_is_space(trailing_char))
35 			continue;
36 		if (trailing_char == EOF)
37 			break;
38 		fprintf(stderr, "%s: Trailing characters found after key\n", PROG_NAME);
39 		return 1;
40 	}
41 
42 	if (!key_from_base64(key, base64)) {
43 		fprintf(stderr, "%s: Key is not the correct length or format\n", PROG_NAME);
44 		return 1;
45 	}
46 	curve25519_generate_public(key, key);
47 	key_to_base64(base64, key);
48 	puts(base64);
49 	return 0;
50 }
51