Implemented a better way of choosing the encryption algorithm

This commit is contained in:
Johannes Loher 2016-02-27 01:37:03 +01:00
parent ec29e06391
commit 7acebd713e
3 changed files with 32 additions and 22 deletions

View file

@ -67,13 +67,6 @@ auto chacha20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce)
return copy;
}
}
// We need this, so choose works with, if hasElaborateCopyConstructor!R
static if (hasElaborateCopyConstructor!R)
this(this)
{
}
}
return rangeResult(range, key, nonce);
}

View file

@ -1,9 +1,8 @@
module cipher;
private import std.range : isInputRange, ElementType, chooseAmong;
private import std.range : isInputRange, ElementType, InputRange, ForwardRange, inputRangeObject;
private import salsa20;
private import chacha20;
import std.stdio;
public:
@ -13,10 +12,36 @@ enum Cipher
chacha20
}
auto cipherFunction(R)(R range, ubyte[32] key, ubyte[8] nonce, Cipher cipher)
if(isInputRange!R && is(ElementType!R : ubyte))
mixin(cipherFunctionString.format(q{InputRange}, q{isInputRange!R && !(isForwardRange!R)}));
mixin(cipherFunctionString.format(q{ForwardRange}, q{isForwardRange!R}));
unittest
{
return chooseAmong(cipher,
range.salsa20Cipher(key, nonce),
range.chacha20Cipher(key, nonce));
import std.array;
ubyte[32] key;
ubyte[8] nonce;
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))));
}
private:
enum cipherFunctionString = q{
%s!(ElementType!R) cipherFunction(R)(R range, ubyte[32] key, ubyte[8] nonce, Cipher cipher)
if(is(ElementType!R : ubyte) && %s)
{
final switch(cipher)
{
case Cipher.salsa20:
return range.salsa20Cipher(key, nonce).inputRangeObject;
case Cipher.chacha20:
return range.chacha20Cipher(key, nonce).inputRangeObject;
}
}
};

View file

@ -65,14 +65,6 @@ auto salsa20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce)
return copy;
}
}
// We need this, so choose works with, if hasElaborateCopyConstructor!R
static if (hasElaborateCopyConstructor!R)
this(this)
{
}
}
return rangeResult(range, key, nonce);