sockscape/server/Encryption/Cipher.cs

51 lines
1.4 KiB
C#
Raw Normal View History

2017-05-17 21:06:16 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using Square;
2017-05-17 21:06:16 +00:00
2017-05-25 21:08:21 +00:00
namespace CircleScape.Encryption {
2017-05-17 21:06:16 +00:00
class Cipher {
private byte[] Key = new byte[512 / 8];
private byte[] State = new byte[256];
2017-05-17 21:06:16 +00:00
public Cipher(BigInteger key) {
int i = 0, j = 0;
State = State.Select(x => (byte)i++).ToArray();
Key = Key.Select(x => (byte)0).ToArray();
Array.Copy(key.ToByteArray(), Key, Key.Length);
2017-05-17 21:06:16 +00:00
for(i = 0; i < State.Length; ++i) {
j = (j + State[i] + Key[i % Key.Length]) % 256;
Utils.Swap(ref State[i], ref State[j]);
2017-05-17 21:06:16 +00:00
}
GenerateStream(1024);
2017-05-17 21:06:16 +00:00
}
private byte[] GenerateStream(long length) {
var stream = new byte[length];
int i = 0, j = 0;
2017-05-17 21:06:16 +00:00
for(long x = 0; x < length; ++x) {
2017-05-17 21:06:16 +00:00
i = (i + 1) % 256;
j = (j + State[i]) % 256;
Utils.Swap(ref State[i], ref State[j]);
stream[x] = State[(State[i] + State[j]) % 256];
2017-05-17 21:06:16 +00:00
}
return stream;
}
public byte[] Parse(byte[] data) {
var stream = GenerateStream(data.LongLength);
for(long i = 0; i < data.LongLength; ++i)
data[i] ^= stream[i];
return data;
2017-05-17 21:06:16 +00:00
}
}
}