rand.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 <string>
  15. #include <vector>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <openssl/rand.h>
  20. #include "internal.h"
  21. static const struct argument kArguments[] = {
  22. {
  23. "-hex", kBooleanArgument,
  24. "Hex encoded output."
  25. },
  26. {
  27. "", kOptionalArgument, "",
  28. },
  29. };
  30. bool Rand(const std::vector<std::string> &args) {
  31. bool forever = true, hex = false;
  32. size_t len = 0;
  33. if (!args.empty()) {
  34. std::vector<std::string> args_copy(args);
  35. const std::string &last_arg = args.back();
  36. if (!last_arg.empty() && last_arg[0] != '-') {
  37. char *endptr;
  38. unsigned long long num = strtoull(last_arg.c_str(), &endptr, 10);
  39. if (*endptr == 0) {
  40. len = num;
  41. forever = false;
  42. args_copy.pop_back();
  43. }
  44. }
  45. std::map<std::string, std::string> args_map;
  46. if (!ParseKeyValueArguments(&args_map, args_copy, kArguments)) {
  47. PrintUsage(kArguments);
  48. return false;
  49. }
  50. hex = args_map.count("-hex") > 0;
  51. }
  52. uint8_t buf[4096];
  53. uint8_t hex_buf[8192];
  54. size_t done = 0;
  55. while (forever || done < len) {
  56. size_t todo = sizeof(buf);
  57. if (!forever && todo > len - done) {
  58. todo = len - done;
  59. }
  60. RAND_bytes(buf, todo);
  61. if (hex) {
  62. static const char hextable[16 + 1] = "0123456789abcdef";
  63. for (unsigned i = 0; i < todo; i++) {
  64. hex_buf[i*2] = hextable[buf[i] >> 4];
  65. hex_buf[i*2 + 1] = hextable[buf[i] & 0xf];
  66. }
  67. if (fwrite(hex_buf, todo*2, 1, stdout) != 1) {
  68. return false;
  69. }
  70. } else {
  71. if (fwrite(buf, todo, 1, stdout) != 1) {
  72. return false;
  73. }
  74. }
  75. done += todo;
  76. }
  77. if (hex && fwrite("\n", 1, 1, stdout) != 1) {
  78. return false;
  79. }
  80. return true;
  81. }