2016-02-14 11:00:28 +01:00
|
|
|
module cipher;
|
|
|
|
|
2016-07-06 02:00:03 +02:00
|
|
|
private:
|
2016-02-28 14:25:58 +01:00
|
|
|
|
2016-08-01 01:42:29 +02:00
|
|
|
import std.range : isInputRange, isForwardRange, ElementType, InputRange,
|
|
|
|
ForwardRange, inputRangeObject;
|
2016-07-06 02:00:03 +02:00
|
|
|
import std.string : format;
|
2016-07-04 15:00:52 +02:00
|
|
|
|
2016-07-06 02:00:03 +02:00
|
|
|
import salsa20;
|
|
|
|
import chacha20;
|
2016-02-14 11:00:28 +01:00
|
|
|
|
|
|
|
public:
|
|
|
|
|
2016-02-14 12:01:00 +01:00
|
|
|
enum Cipher
|
|
|
|
{
|
2016-02-14 11:00:28 +01:00
|
|
|
salsa20,
|
|
|
|
chacha20
|
|
|
|
}
|
|
|
|
|
2016-08-01 01:42:29 +02:00
|
|
|
template cipherFunction(R) if (isInputRange!R && is(ElementType!R : ubyte))
|
2016-06-09 14:10:06 +02:00
|
|
|
{
|
2016-07-04 15:00:52 +02:00
|
|
|
static if (isForwardRange!R)
|
2016-06-09 14:10:06 +02:00
|
|
|
alias ReturnType = ForwardRange;
|
|
|
|
else
|
|
|
|
alias ReturnType = InputRange;
|
|
|
|
|
|
|
|
ReturnType!(ElementType!R) cipherFunction(R range, ubyte[32] key, ubyte[8] nonce, Cipher cipher)
|
|
|
|
{
|
|
|
|
final switch (cipher)
|
|
|
|
{
|
2016-07-04 15:00:52 +02:00
|
|
|
case Cipher.salsa20:
|
|
|
|
return range.salsa20Cipher(key, nonce).inputRangeObject;
|
|
|
|
case Cipher.chacha20:
|
|
|
|
return range.chacha20Cipher(key, nonce).inputRangeObject;
|
2016-06-09 14:10:06 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-02-27 01:37:03 +01:00
|
|
|
|
|
|
|
unittest
|
2016-02-14 11:00:28 +01:00
|
|
|
{
|
2016-02-27 01:37:03 +01:00
|
|
|
import std.array;
|
2016-07-04 15:00:52 +02:00
|
|
|
|
|
|
|
immutable ubyte[32] key;
|
|
|
|
immutable ubyte[8] nonce;
|
2016-02-27 01:37:03 +01:00
|
|
|
ubyte[] a = [1, 2, 3];
|
|
|
|
auto b = a.cipherFunction(key, nonce, Cipher.salsa20);
|
|
|
|
InputRange!ubyte c = a.inputRangeObject;
|
|
|
|
auto d = c.cipherFunction(key, nonce, Cipher.salsa20);
|
|
|
|
|
|
|
|
static assert(isForwardRange!(typeof(b)));
|
|
|
|
static assert(isInputRange!(typeof(d)) && !(isForwardRange!(typeof(d))));
|
2016-02-14 11:00:28 +01:00
|
|
|
}
|