55 lines
1.7 KiB
C#
55 lines
1.7 KiB
C#
using System;
|
|
using System.Text;
|
|
|
|
namespace xaskel_coder
|
|
{
|
|
public static class Tea
|
|
{
|
|
private const uint DELTA = 0x9E3779B9;
|
|
|
|
public static string Encode(string text, string key)
|
|
{
|
|
if (string.IsNullOrEmpty(text))
|
|
return string.Empty;
|
|
|
|
byte[] textBytes = Encoding.UTF8.GetBytes(text),
|
|
keyBytes = Encoding.UTF8.GetBytes(key);
|
|
|
|
uint[] key32 = new uint[4];
|
|
Buffer.BlockCopy(keyBytes, 0, key32, 0, Math.Min(keyBytes.Length, 16));
|
|
|
|
int textLength = textBytes.Length,
|
|
bufferLength = textLength;
|
|
|
|
if (bufferLength % 4 != 0)
|
|
bufferLength += 4 - (bufferLength % 4);
|
|
|
|
bufferLength = bufferLength / 4;
|
|
uint[] text32 = new uint[bufferLength + 1];
|
|
Buffer.BlockCopy(textBytes, 0, text32, 0, textBytes.Length);
|
|
|
|
uint previous = 0;
|
|
for (int offset = 0; offset < bufferLength; offset++)
|
|
{
|
|
uint v = text32[offset],
|
|
sum = 0;
|
|
|
|
for (int i = 0; i < 32; i++)
|
|
{
|
|
v += (((previous << 4) ^ (previous >> 5)) + previous) ^ (sum + key32[sum & 3]);
|
|
sum += DELTA;
|
|
previous += (((v << 4) ^ (v >> 5)) + v) ^ (sum + key32[(sum >> 11) & 3]);
|
|
}
|
|
|
|
text32[offset] = v;
|
|
}
|
|
text32[bufferLength] = previous;
|
|
|
|
byte[] resultBytes = new byte[(bufferLength + 1) * 4];
|
|
Buffer.BlockCopy(text32, 0, resultBytes, 0, resultBytes.Length);
|
|
|
|
return Convert.ToBase64String(resultBytes);
|
|
}
|
|
}
|
|
}
|