• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2015, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/curve25519.h>
16 
17 #include <errno.h>
18 #include <stdio.h>
19 #include <string.h>
20 
21 #include "internal.h"
22 
23 
24 struct FileCloser {
operator ()FileCloser25   void operator()(FILE *file) {
26     fclose(file);
27   }
28 };
29 
30 using ScopedFILE = std::unique_ptr<FILE, FileCloser>;
31 
32 static const struct argument kArguments[] = {
33     {
34         "-out-public", kRequiredArgument, "The file to write the public key to",
35     },
36     {
37         "-out-private", kRequiredArgument,
38         "The file to write the private key to",
39     },
40     {
41         "", kOptionalArgument, "",
42     },
43 };
44 
WriteToFile(const std::string & path,const uint8_t * in,size_t in_len)45 static bool WriteToFile(const std::string &path, const uint8_t *in,
46                         size_t in_len) {
47   ScopedFILE file(fopen(path.c_str(), "wb"));
48   if (!file) {
49     fprintf(stderr, "Failed to open '%s': %s\n", path.c_str(), strerror(errno));
50     return false;
51   }
52   if (fwrite(in, in_len, 1, file.get()) != 1) {
53     fprintf(stderr, "Failed to write to '%s': %s\n", path.c_str(),
54             strerror(errno));
55     return false;
56   }
57   return true;
58 }
59 
GenerateEd25519Key(const std::vector<std::string> & args)60 bool GenerateEd25519Key(const std::vector<std::string> &args) {
61   std::map<std::string, std::string> args_map;
62 
63   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
64     PrintUsage(kArguments);
65     return false;
66   }
67 
68   uint8_t public_key[32], private_key[64];
69   ED25519_keypair(public_key, private_key);
70 
71   return WriteToFile(args_map["-out-public"], public_key, sizeof(public_key)) &&
72          WriteToFile(args_map["-out-private"], private_key,
73                      sizeof(private_key));
74 }
75