-
Notifications
You must be signed in to change notification settings - Fork 5
/
GenAESCMAC.cs
80 lines (67 loc) · 2.57 KB
/
GenAESCMAC.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;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
namespace EdgeAuther
{
class GenAESCMAC
{
//Code taken from https://stackoverflow.com/questions/29163493/aes-cmac-calculation-c-sharp
public static byte[] AESEncrypt(byte[] key, byte[] iv, byte[] data)
{
using (MemoryStream ms = new MemoryStream())
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider
{
Mode = CipherMode.CBC,
Padding = PaddingMode.None
};
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
}
public static byte[] Rol(byte[] b)
{
byte[] r = new byte[b.Length];
byte carry = 0;
for (int i = b.Length - 1; i >= 0; i--)
{
ushort u = (ushort)(b[i] << 1);
r[i] = (byte)((u & 0xff) + carry);
carry = (byte)((u & 0xff00) >> 8);
}
return r;
}
public static byte[] AESCMAC(byte[] key, byte[] data)
{
byte[] L = AESEncrypt(key, new byte[16], new byte[16]);
byte[] FirstSubkey = Rol(L);
if ((L[0] & 0x80) == 0x80)
FirstSubkey[15] ^= 0x87;
byte[] SecondSubkey = Rol(FirstSubkey);
if ((FirstSubkey[0] & 0x80) == 0x80)
SecondSubkey[15] ^= 0x87;
if (((data.Length != 0) && (data.Length % 16 == 0)) == true)
{
for (int j = 0; j < FirstSubkey.Length; j++)
data[data.Length - 16 + j] ^= FirstSubkey[j];
}
else
{
byte[] padding = new byte[16 - data.Length % 16];
padding[0] = 0x80;
data = data.Concat<byte>(padding.AsEnumerable()).ToArray();
for (int j = 0; j < SecondSubkey.Length; j++)
data[data.Length - 16 + j] ^= SecondSubkey[j];
}
byte[] encResult = AESEncrypt(key, new byte[16], data);
byte[] HashValue = new byte[16];
Array.Copy(encResult, encResult.Length - HashValue.Length, HashValue, 0, HashValue.Length);
return HashValue;
}
}
}