4 * Copyright (c) Freescale Semiconductor, Inc. All rights reserved.
5 * See included license file for license details.
17 #include "smart_ptr.h"
22 const char k_toolName[] = "keygen";
24 //! Current version number for the tool.
25 const char k_version[] = "1.0";
28 const char k_copyright[] = "Copyright (c) 2006-2009 Freescale Semiconductor, Inc.\nAll rights reserved.";
30 //! Definition of command line options.
31 static const char * k_optionsDefinition[] = {
41 const char k_usageText[] = "\nOptions:\n\
42 -?/--help Show this help\n\
43 -v/--version Display tool version\n\
44 -q/--quiet Output only warnings and errors\n\
45 -V/--verbose Print extra detailed log information\n\
46 -n/--number <int> Number of keys to generate per file (default=1)\n\n";
48 //! An array of strings.
49 typedef std::vector<std::string> string_vector_t;
52 int main(int argc, char* argv[], char* envp[]);
55 * \brief Class that encapsulates the keygen interface.
57 * A single global logger instance is created during object construction. It is
58 * never freed because we need it up to the last possible minute, when an
59 * exception could be thrown.
64 int m_argc; //!< Number of command line arguments.
65 char ** m_argv; //!< String value for each command line argument.
66 StdoutLogger * m_logger; //!< Singleton logger instance.
67 string_vector_t m_positionalArgs; //!< Arguments coming after explicit options.
68 bool m_isVerbose; //!< Whether the verbose flag was turned on.
69 int m_keyCount; //!< Number of keys to generate.
75 * Creates the singleton logger instance.
77 keygen(int argc, char * argv[])
85 // create logger instance
86 m_logger = new StdoutLogger();
87 m_logger->setFilterLevel(Logger::INFO);
88 Log::setLogger(m_logger);
99 * Reads the command line options passed into the constructor.
101 * This method can return a return code to its caller, which will cause the
102 * tool to exit immediately with that return code value. Normally, though, it
103 * will return -1 to signal that the tool should continue to execute and
104 * all options were processed successfully.
106 * The Options class is used to parse command line options. See
107 * #k_optionsDefinition for the list of options and #k_usageText for the
108 * descriptive help for each option.
110 * \retval -1 The options were processed successfully. Let the tool run normally.
111 * \return A zero or positive result is a return code value that should be
112 * returned from the tool as it exits immediately.
116 Options options(*m_argv, k_optionsDefinition);
117 OptArgvIter iter(--m_argc, ++m_argv);
119 // process command line options
122 while (optchar = options(iter, optarg))
131 printf("%s %s\n%s\n", k_toolName, k_version, k_copyright);
135 Log::getLogger()->setFilterLevel(Logger::DEBUG);
139 Log::getLogger()->setFilterLevel(Logger::WARNING);
147 m_keyCount = strtol(optarg, NULL, 0);
151 Log::log(Logger::ERROR, "error: unrecognized option\n\n");
157 // handle positional args
158 if (iter.index() < m_argc)
160 // Log::SetOutputLevel leveler(Logger::DEBUG);
161 // Log::log("positional args:\n");
163 for (i = iter.index(); i < m_argc; ++i)
165 // Log::log("%d: %s\n", i - iter.index(), m_argv[i]);
166 m_positionalArgs.push_back(m_argv[i]);
175 * Prints help for the tool.
177 void printUsage(Options & options)
179 options.usage(std::cout, "key-files...");
180 printf(k_usageText, k_toolName);
184 * Core of the tool. Calls processOptions() to handle command line options
185 * before performing the real work the tool does.
191 // read command line options
193 if ((result = processOptions()) != -1)
198 // set verbose logging
201 // make sure a file was provided
202 if (m_positionalArgs.size() < 1)
204 throw std::runtime_error("no output file path was provided");
207 // generate key files
208 string_vector_t::const_iterator it = m_positionalArgs.begin();
209 for (; it != m_positionalArgs.end(); ++it)
211 generateKeyFile(*it);
214 catch (std::exception & e)
216 Log::log(Logger::ERROR, "error: %s\n", e.what());
221 Log::log(Logger::ERROR, "error: unexpected exception\n");
229 * \brief Turns on verbose logging.
231 void setVerboseLogging()
235 // verbose only affects the INFO and DEBUG filter levels
236 // if the user has selected quiet mode, it overrides verbose
237 switch (Log::getLogger()->getFilterLevel())
240 Log::getLogger()->setFilterLevel(Logger::INFO2);
243 Log::getLogger()->setFilterLevel(Logger::DEBUG2);
250 * \brief Opens the file at \a path and writes a random key file.
252 * Each key file will have #m_keyCount number of keys written into it,
253 * each on a line by itself.
255 void generateKeyFile(const std::string & path)
257 std::ofstream outputStream(path.c_str(), std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
258 if (outputStream.is_open())
261 for (i = 0; i < m_keyCount; ++i)
265 key.writeToStream(outputStream);
267 // put a newline after the key
268 outputStream.write("\n", 1);
274 Log::log(Logger::INFO, "wrote key file %s\n", path.c_str());
278 throw std::runtime_error("could not open output file");
283 * \brief Write the value of each byte of the \a key to the log.
285 void dumpKey(const AESKey<128> & key)
288 Log::log(Logger::INFO2, "key bytes: ");
289 AESKey<128>::key_t the_key;
290 key.getKey(&the_key);
294 Log::log(Logger::INFO2, "%02x ", the_key[q]);
296 Log::log(Logger::INFO2, "\n");
300 * \brief Log an array of bytes as hex.
302 void logHexArray(Logger::log_level_t level, const uint8_t * bytes, unsigned count)
304 Log::SetOutputLevel leveler(level);
307 for (i = 0; i < count; ++i, ++bytes)
309 if ((i % 16 == 0) && (i < count - 1))
315 Log::log(" 0x%04x: ", i);
317 Log::log("%02x ", *bytes & 0xff);
326 * Main application entry point. Creates an sbtool instance and lets it take over.
328 int main(int argc, char* argv[], char* envp[])
332 return keygen(argc, argv).run();
336 Log::log(Logger::ERROR, "error: unexpected exception\n");