learncrypto/source/app.d

83 lines
2.2 KiB
D
Raw Normal View History

2016-02-14 11:00:28 +01:00
import std.getopt;
import std.string : format;
2016-02-28 14:25:58 +01:00
import std.stdio : stderr, writeln;
2016-02-14 11:00:28 +01:00
import cipher : Cipher;
import actions;
int main(string[] args)
{
bool[string] actions = ["genKey" : false, "encrypt" : false, "decrypt" : false, "benchmark" : false];
2016-02-14 11:00:28 +01:00
Cipher cipher = Cipher.chacha20;
2016-02-14 11:00:28 +01:00
string keyFileName = "symkey.asc";
bool armor;
GetoptResult result;
try
{
result = getopt(args, std.getopt.config.bundling, "gen-key|g",
"Generate a new 256 bit key.", &actions["genKey"],
"encrypt|e", "Encrypt a message.", &actions["encrypt"],
"decrypt|d", "Decrypt a message.", &actions["decrypt"],
"benchmark|b", "Perform some benchmarks.", &actions["benchmark"],
"cipher|c", "The cipher to use (default: %s).".format(cipher), &cipher, "key|k",
"The file which contains the key (default: %s).".format(keyFileName),
&keyFileName, "armor|a", "use ascii-armored I/O.", &armor);
}
2016-02-28 14:25:58 +01:00
catch (Exception e)
{
stderr.writeln(e.msg);
return 1;
}
2016-02-14 11:00:28 +01:00
size_t numberOfActions;
2016-02-28 14:25:58 +01:00
foreach (value; actions.values)
2016-02-14 11:00:28 +01:00
numberOfActions += value;
2016-02-28 14:25:58 +01:00
if (numberOfActions == 1)
2016-02-14 11:00:28 +01:00
{
try
{
2016-02-28 14:25:58 +01:00
if (actions["genKey"])
2016-02-14 11:00:28 +01:00
{
generateKey(armor);
}
2016-02-28 14:25:58 +01:00
else if (actions["encrypt"])
2016-02-14 11:00:28 +01:00
{
encrypt(keyFileName, cipher, armor);
}
2016-02-28 14:25:58 +01:00
else if (actions["decrypt"])
2016-02-14 11:00:28 +01:00
{
decrypt(keyFileName, cipher, armor);
}
else if (actions["benchmark"])
{
bench();
}
2016-02-14 11:00:28 +01:00
}
2016-02-28 14:25:58 +01:00
catch (Exception e)
2016-02-14 11:00:28 +01:00
{
stderr.writeln(e.msg);
return 1;
}
}
else
{
result.helpWanted = true;
2016-02-14 11:00:28 +01:00
}
2016-02-28 14:25:58 +01:00
if (result.helpWanted)
printHelp(result.options);
2016-02-14 11:00:28 +01:00
return 0;
}
void printHelp(Option[] options)
{
defaultGetoptPrinter("Usage: ./learncrypt [options]\n\nCommon options:", options[$ - 1 .. $]);
defaultGetoptPrinter("\nGlobal options:", options[$ - 2 .. $ - 1]);
defaultGetoptPrinter("\nActions:", options[0 .. 4]);
defaultGetoptPrinter("\nAction options:", options[4 .. 5]);
}