-
Notifications
You must be signed in to change notification settings - Fork 2
/
Arcfour.cs
80 lines (70 loc) · 2 KB
/
Arcfour.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
namespace generator
{
/// <summary>
/// https://datatracker.ietf.org/doc/html/draft-kaukonen-cipher-arcfour-03
/// </summary>
public class Arcfour
{
private byte _i;
private byte _j;
private readonly byte[] _s;
public Arcfour(byte[] seed)
{
if (seed.Length != 256)
{
throw new ArgumentOutOfRangeException(nameof(seed), "error");
}
var checker = new bool[256];
foreach (var x in seed)
{
if (checker[x])
{
throw new ArgumentOutOfRangeException(nameof(seed), "error");
}
checker[x] = true;
}
_i = 0;
_j = 0;
_s = new byte[256];
Buffer.BlockCopy(seed, 0, _s, 0, 256);
}
public int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue), "error");
}
var a = new byte[8];
a[0] = GetByte();
a[1] = GetByte();
a[2] = GetByte();
a[3] = GetByte();
a[4] = GetByte();
a[5] = GetByte();
a[6] = GetByte();
a[7] = GetByte();
return (int)(BitConverter.ToUInt64(a) % (ulong)maxValue);
}
public int Next(int minValue, int maxValue)
{
return Next(maxValue - minValue) + minValue;
}
public double NextDouble()
{
var a = new byte[4];
a[0] = GetByte();
a[1] = GetByte();
a[2] = GetByte();
a[3] = GetByte();
return BitConverter.ToUInt32(a) / (uint.MaxValue + 1.0);
}
private byte GetByte()
{
++_i;
_j = (byte)(_j + _s[_i]);
(_s[_i], _s[_j]) = (_s[_j], _s[_i]);
return _s[(byte)(_s[_i] + _s[_j])];
}
}
}