-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathKeyGenerator.cs
More file actions
110 lines (92 loc) · 3 KB
/
Copy pathKeyGenerator.cs
File metadata and controls
110 lines (92 loc) · 3 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System.Text;
using System.Security.Cryptography;
using System;
using UnityEngine;
namespace Shell.Protector
{
public class KeyGenerator
{
//key1 is fixed key
//key2 is user key
public static byte[] MakeKeyBytes(string fixedKey, string userKey, int userKeylength = 4)
{
byte[] key = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] fixedKeyBytes = Encoding.ASCII.GetBytes(fixedKey);
byte[] userKeyBytes = Encoding.ASCII.GetBytes(userKey);
byte[] hash = GetKeyHash(userKeyBytes);
for (int i = 0; i < fixedKeyBytes.Length; ++i)
key[i] = fixedKeyBytes[i];
if (userKeylength > 0)
{
for (int i = (16 - userKeylength), j = 0; i < key.Length; ++i, ++j)
{
if (j < userKeyBytes.Length)
key[i] = userKeyBytes[j] ^= hash[j];
else
key[i] = hash[j];
}
}
return key;
}
public static byte[] GetKeyHash(byte[] key, string salt = null)
{
SHA256 sha256 = SHA256.Create();
byte[] hash = sha256.ComputeHash(key);
if (salt == null)
{
return hash;
}
byte[] saltBytes = Encoding.ASCII.GetBytes(salt);
for(int i = 0; i < hash.Length; ++i)
hash[i] ^= saltBytes[i % saltBytes.Length];
return hash;
}
public static byte[] GetHash(int data)
{
SHA256 sha256 = SHA256.Create();
byte[] bytes = BitConverter.GetBytes(data);
byte[] hash = sha256.ComputeHash(bytes);
return hash;
}
public static string GenerateRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=|\\/?.>,<~`\'\" ";
StringBuilder builder = new StringBuilder();
using (RandomNumberGenerator random = RandomNumberGenerator.Create())
{
byte[] buffer = new byte[4];
for (int i = 0; i < length; i++)
{
random.GetBytes(buffer);
int index = (int)(BitConverter.ToUInt32(buffer, 0) % chars.Length);
builder.Append(chars[index]);
}
}
return builder.ToString();
}
public static uint SimpleHash(byte[] data, uint hashMagic)
{
if (data.Length != 16)
throw new ArgumentException("Input must be exactly 16 bytes.");
uint hash = 0x811C9DC5u;
hash *= hashMagic;
for (int i = 0; i < 16; i++)
{
uint k = data[i];
k *= 0xcc9e2d51u;
k = (k << 15) | (k >> 17);
k *= 0x1b873593u;
hash ^= k;
hash = (hash << 13) | (hash >> 19);
hash = hash * 5u + 0xe6546b64u;
}
hash ^= 16u;
hash ^= (hash >> 16);
hash *= 0x85ebca6bu;
hash ^= (hash >> 13);
hash *= 0xc2b2ae35u;
hash ^= (hash >> 16);
return hash;
}
}
}