egra: checkbox fixes
[iv.d.git] / stc / arc4.d
blob8abfba42bd5ec4aab672da7d6b3b71e7d6049211
1 /*
2 * ARC4 engine by unknown.
3 * Copyright (C) 2014 Ketmar Dark // Invisible Vector (ketmar@ketmar.no-ip.org)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License ONLY.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * Get a copy of the GNU GPL from <http://www.gnu.org/licenses/>.
16 module iv.stc.arc4 /*is aliced*/;
18 import std.range;
19 import iv.alice;
20 import iv.stc.core;
23 public struct ARC4Engine(uint NSkipBytes) {
24 // base stream cipher interface
25 mixin StreamCipherCore;
27 public:
28 // cipher parameters
29 enum BlockSize = 256; // arbitrary number
30 enum IVSize = 8; // in bytes
31 enum KeySize = 32; // in bytes
32 enum SupportIV = false;
34 enum SkipBytes = NSkipBytes;
36 private:
37 void resetState(KR, IR) (KR key, IR iv) @trusted {
38 static if (hasLength!KR) assert(key.length > 0); else assert(!key.empty);
39 static if (hasLength!IR) assert(iv.length == 0); else assert(iv.empty);
40 ubyte[256] kb = void;
41 ubyte[] keybuf;
43 usize len = 0;
44 while (!key.empty && len < kb.length) {
45 kb.ptr[len++] = cast(ubyte)key.front;
46 key.popFront;
48 keybuf = kb[0..len];
50 // setup key
51 ubyte a, c;
52 statex = 0;
53 statey = 0;
54 foreach (ubyte i; 0..256) statem.ptr[i] = i;
55 c = 0;
56 foreach (ubyte i; 0..256) {
57 a = statem.ptr[i];
58 c = (c+a+cast(ubyte)keybuf.ptr[i%keybuf.length])&0xff;
59 statem.ptr[i] = statem.ptr[c];
60 statem.ptr[c] = a;
62 // setup IV (how?)
63 // discard first skipbytes bytes
64 static if (SkipBytes > 0) {
65 ubyte b;
66 ubyte x = statex;
67 ubyte y = statey;
68 foreach (immutable i; 0..SkipBytes) {
69 x = (x+1)&0xff;
70 a = statem.ptr[x];
71 y = (y+a)&0xff;
72 statem.ptr[x] = b = statem.ptr[y];
73 statem.ptr[y] = a;
75 statex = x;
76 statey = y;
80 void clearState () nothrow @trusted @nogc {
81 statem[] = 0;
82 statex = statey = 0;
85 void getBuf () nothrow @trusted @nogc {
86 ubyte a, b;
87 ubyte x = statex;
88 ubyte y = statey;
89 foreach (immutable i; 0..BlockSize) {
90 x = (x+1)&0xff;
91 a = statem.ptr[x];
92 y = (y+a)&0xff;
93 statem.ptr[x] = b = statem.ptr[y];
94 statem.ptr[y] = a;
95 buf.ptr[i] = statem.ptr[(a+b)&0xff];
97 statex = x;
98 statey = y;
101 private:
102 ubyte[256] statem; // permutation table
103 ubyte statex, statey; // permutation indicies
107 // default ARC4 engine
108 alias ARC4 = ARC4Engine!3072;