Skip to content

Commit 2d0e841

Browse files
committed
C++ify genkey
Switches to iostream for user I/O, implements -h/--help, adds default random pubkey generation feature and handles wrong usage gracefully.
1 parent 4e68717 commit 2d0e841

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

src/engine/genkey.cpp

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,56 @@
1+
#include <algorithm>
12
#include <sys/time.h>
2-
#include <sys/types.h>
3-
#include <unistd.h>
4-
#include <errno.h>
5-
#include <signal.h>
3+
#include <random>
4+
#include <iostream>
65

76
#include "cube.h"
87

98
int main(int argc, char **argv)
109
{
11-
//Generate key pair: genkey <seed>
12-
if(argc == 2)
13-
{
10+
std::string argv1;
11+
12+
// generate key pair with random seed generated by OS
13+
if (argc == 1) {
14+
std::random_device rd;
15+
std::mt19937 mt(rd());
16+
std::uniform_int_distribution<> distribution(1, 255);
17+
std::generate_n(std::back_inserter(argv1), 255, [&]() { return distribution(mt); });
18+
argc = 2;
19+
} else {
20+
argv1 = argv[1];
21+
}
22+
23+
// support --help/-h
24+
if (argv1 == "--help" || argv1 == "-h") {
25+
std::cerr << "Blue Nebula genkey utility" << std::endl;
26+
std::cerr << std::endl;
27+
std::cerr << "Usage:" << std::endl;
28+
std::cerr << std::endl;
29+
std::cerr << " genkey generate private and public key using random seed" << std::endl;
30+
std::cerr << " genkey <seed> generate private and public key using provided seed" << std::endl;
31+
std::cerr << " genkey <pubkey> <privkey> check if public key belongs to private key" << std::endl;
32+
std::cerr << " genkey -h/--help print this help" << std::endl;
33+
return EXIT_SUCCESS;
34+
}
35+
36+
// generate key pair with provided seed
37+
if(argc == 2) {
1438
vector<char> privkey, pubkey;
15-
genprivkey(argv[1], privkey, pubkey);
39+
genprivkey(argv1.c_str(), privkey, pubkey);
1640
printf("private key: %s\n", privkey.getbuf());
1741
printf("public key: %s\n", pubkey.getbuf());
1842
return EXIT_SUCCESS;
1943
}
20-
//Print yes/no to match pubkey with privkey: genkey <pubkey> <privkey>
21-
else if(argc == 3)
22-
{
44+
45+
// print yes/no to match pubkey with privkey: genkey <pubkey> <privkey>
46+
if(argc == 3) {
2347
vector<char> pubkey;
2448
genpubkey(argv[2], pubkey);
25-
printf("%s\n", !strcmp(argv[1], pubkey.getbuf()) ? "yes" : "no");
49+
std::cerr << (argv1 == pubkey.data() ? "yes" : "no") << std::endl;
2650
return EXIT_SUCCESS;
2751
}
52+
53+
// fallback
54+
std::cerr << "Error: unknown parameters, check " << argv[0] << " --help" << std::endl;
2855
return EXIT_FAILURE;
2956
}
30-

0 commit comments

Comments
 (0)