generate_ed25519.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include <openssl/curve25519.h>
  15. #include <errno.h>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include "internal.h"
  19. static const struct argument kArguments[] = {
  20. {
  21. "-out-public", kRequiredArgument, "The file to write the public key to",
  22. },
  23. {
  24. "-out-private", kRequiredArgument,
  25. "The file to write the private key to",
  26. },
  27. {
  28. "", kOptionalArgument, "",
  29. },
  30. };
  31. static bool WriteToFile(const std::string &path, const uint8_t *in,
  32. size_t in_len) {
  33. ScopedFILE file(fopen(path.c_str(), "wb"));
  34. if (!file) {
  35. fprintf(stderr, "Failed to open '%s': %s\n", path.c_str(), strerror(errno));
  36. return false;
  37. }
  38. if (fwrite(in, in_len, 1, file.get()) != 1) {
  39. fprintf(stderr, "Failed to write to '%s': %s\n", path.c_str(),
  40. strerror(errno));
  41. return false;
  42. }
  43. return true;
  44. }
  45. bool GenerateEd25519Key(const std::vector<std::string> &args) {
  46. std::map<std::string, std::string> args_map;
  47. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  48. PrintUsage(kArguments);
  49. return false;
  50. }
  51. uint8_t public_key[32], private_key[64];
  52. ED25519_keypair(public_key, private_key);
  53. return WriteToFile(args_map["-out-public"], public_key, sizeof(public_key)) &&
  54. WriteToFile(args_map["-out-private"], private_key,
  55. sizeof(private_key));
  56. }