|
| 1 | +今天才刚发现原来清华大学校园网的Auth连接方式,使用了XXTea加密算法。 |
| 2 | + |
| 3 | +由于不确定是否魔改过,在这里贴一份。 |
| 4 | + |
| 5 | +``` csharp |
| 6 | +private static uint[] ToUInt32Array(byte[] data, bool includeLength) |
| 7 | +{ |
| 8 | + int length = data.Length; |
| 9 | + int n = (length + 3) / 4; |
| 10 | + uint[] result; |
| 11 | + if (includeLength) |
| 12 | + { |
| 13 | + result = new uint[n + 1]; |
| 14 | + result[n] = (uint)length; |
| 15 | + } |
| 16 | + else |
| 17 | + { |
| 18 | + result = new uint[Math.Max(n, 4)]; |
| 19 | + } |
| 20 | + Unsafe.CopyBlock(ref Unsafe.As<uint, byte>(ref result[0]), ref data[0], (uint)length); |
| 21 | + return result; |
| 22 | +} |
| 23 | +private static byte[] ToByteArray(uint[] data, bool includeLength) |
| 24 | +{ |
| 25 | + int d = data.Length; |
| 26 | + uint n = (uint)(d << 2); |
| 27 | + if (includeLength) |
| 28 | + { |
| 29 | + uint m = data[d - 1]; |
| 30 | + n -= 4; |
| 31 | + if (m < n - 3 || m > n) |
| 32 | + { |
| 33 | + return Array.Empty<byte>(); |
| 34 | + } |
| 35 | + n = m; |
| 36 | + } |
| 37 | + byte[] result = new byte[n]; |
| 38 | + Unsafe.CopyBlock(ref result[0], ref Unsafe.As<uint, byte>(ref data[0]), n); |
| 39 | + return result; |
| 40 | +} |
| 41 | +private static uint MX(uint sum, uint y, uint z, int p, uint e, uint[] k) |
| 42 | +{ |
| 43 | + return ((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4) ^ (sum ^ y)) + (k[(p & 3) ^ (int)e] ^ z); |
| 44 | +} |
| 45 | +public static byte[] XXTeaEncrypt(string str, string key) |
| 46 | +{ |
| 47 | + if (str.Length == 0) |
| 48 | + { |
| 49 | + return Array.Empty<byte>(); |
| 50 | + } |
| 51 | + uint[] v = ToUInt32Array(Encoding.UTF8.GetBytes(str), true); |
| 52 | + uint[] k = ToUInt32Array(Encoding.UTF8.GetBytes(key), false); |
| 53 | + int n = v.Length - 1; |
| 54 | + uint z = v[n]; |
| 55 | + uint y; |
| 56 | + int q = 6 + 52 / (n + 1); |
| 57 | + uint sum = 0; |
| 58 | + unchecked |
| 59 | + { |
| 60 | + while (q-- > 0) |
| 61 | + { |
| 62 | + sum += 0x9E3779B9; |
| 63 | + uint e = (sum >> 2) & 3; |
| 64 | + for (int p = 0; p <= n; p++) |
| 65 | + { |
| 66 | + y = v[(p + 1) % (n + 1)]; |
| 67 | + z = v[p] += MX(sum, y, z, p, e, k); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return ToByteArray(v, false); |
| 72 | +} |
| 73 | +``` |
0 commit comments