fixed salsaa20

This commit is contained in:
Johannes Loher 2016-07-05 22:19:53 +02:00
parent e51b852a39
commit 0a9fef2cae

View file

@ -12,6 +12,8 @@ import utility;
public: public:
// TODO: Implement random access
auto salsa20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce) auto salsa20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce)
if (isInputRange!R && is(ElementType!R : ubyte)) if (isInputRange!R && is(ElementType!R : ubyte))
{ {
@ -20,26 +22,28 @@ auto salsa20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce)
private: private:
ulong count; ulong count;
R range; R range;
ubyte[] salsaSection; ubyte[64] salsaSection;
uint salsaCounter;
public: public:
bool empty() @property bool empty() @property
{ {
return range.empty || (count == ulong.max && salsaSection.empty); return range.empty || (count == ulong.max && salsaCounter == 64);
} }
ubyte front() @property ubyte front() @property
{ {
assert(!empty); assert(!empty);
return range.front ^ salsaSection.front; return range.front ^ salsaSection[salsaCounter];
} }
void popFront() void popFront()
{ {
assert(!empty); assert(!empty);
salsaSection.popFront(); if (++salsaCounter == 64)
if (salsaSection.empty)
{ {
import std.stdio;
salsaSection = salsa20Exp(key, concat!(ubyte[16])(nonce, littleEndianInv(++count))); salsaSection = salsa20Exp(key, concat!(ubyte[16])(nonce, littleEndianInv(++count)));
salsaCounter = 0;
} }
range.popFront(); range.popFront();
} }
@ -47,11 +51,25 @@ auto salsa20Cipher(R)(R range, ubyte[32] key, ubyte[8] nonce)
{ {
auto save() @property auto save() @property
{ {
return rangeResult(count, range.save, salsaSection.dup); return rangeResult(count, range.save, salsaSection);
} }
} }
} }
return rangeResult(0UL, range, salsa20Exp(key, concat!(ubyte[16])(nonce, littleEndianInv(0UL))).dup); return rangeResult(0UL, range, salsa20Exp(key, concat!(ubyte[16])(nonce, littleEndianInv(0UL))));
}
// TODO: Create more unittest!!!
@safe unittest
{
ubyte[] test = new ubyte[64];
ubyte[32] key;
ubyte[8] nonce;
test = test.salsa20Cipher(key, nonce).array;
assert(test == [154,151,246, 91,155, 76,114, 27,150, 10,103, 33, 69,252,168,212,
227, 46,103,249, 17, 30,169,121,206,156, 72, 38,128,106,238,230,
61,233,192,218, 43,215,249, 30,188,178, 99,155,249,137,198, 37,
27, 41,191, 56,211,154,155,220,231,197, 95, 75, 42,193, 42, 57]);
} }
private: private: