forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetXorEncryption.cs
More file actions
60 lines (54 loc) · 1.59 KB
/
NetXorEncryption.cs
File metadata and controls
60 lines (54 loc) · 1.59 KB
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
using System;
using System.Text;
namespace LiteNetLib.Encryption
{
public class NetXorEncryption : NetEncryption
{
private byte[] _byteKey;
/// <summary>
/// NetXorEncryption constructor
/// </summary>
public NetXorEncryption(byte[] key)
{
_byteKey = key;
}
/// <summary>
/// NetXorEncryption constructor
/// </summary>
public NetXorEncryption(string key)
{
_byteKey = Encoding.UTF8.GetBytes(key);
}
/// <summary>
/// Decrypt an incoming message
/// </summary>
public override bool Decrypt(byte[] rawData, int start, ref int length)
{
var cur = start;
for (var i = 0; i < length; i++, cur++)
{
var offset = i % _byteKey.Length;
rawData[cur] = (byte) (rawData[cur] ^ _byteKey[offset]);
}
return true;
}
/// <summary>
/// Encrypt an outgoing message
/// </summary>
public override bool Encrypt(byte[] rawData, ref int start, ref int length)
{
var cur = start;
for (var i = 0; i < length; i++, cur++)
{
var offset = i % _byteKey.Length;
rawData[cur] = (byte) (rawData[cur] ^ _byteKey[offset]);
}
return true;
}
public override void SetKey(byte[] data, int offset, int count)
{
_byteKey = new byte[count];
Array.Copy(data, offset, _byteKey, 0, count);
}
}
}