XTEA加密算法 for C#
时间: 2023-07-12 12:47:51 浏览: 253
以下是C#实现的XTEA加密算法代码:
```csharp
public class XTEA
{
private static uint[] key = { 0x12345678, 0x23456789, 0x34567890, 0x45678901 };
public static byte[] Encrypt(byte[] data)
{
int padding = 8 - data.Length % 8;
byte[] paddedData = new byte[data.Length + padding];
Array.Copy(data, paddedData, data.Length);
byte[] result = new byte[paddedData.Length];
for (int i = 0; i < paddedData.Length; i += 8)
{
uint block1 = BitConverter.ToUInt32(paddedData, i);
uint block2 = BitConverter.ToUInt32(paddedData, i + 4);
uint sum = 0;
uint delta = 0x9E3779B9;
for (int j = 0; j < 32; j++)
{
block1 += ((block2 << 4 ^ block2 >> 5) + block2) ^ (sum + key[sum & 3]);
sum += delta;
block2 += ((block1 << 4 ^ block1 >> 5) + block1) ^ (sum + key[sum >> 11 & 3]);
}
byte[] encryptedBlock1 = BitConverter.GetBytes(block1);
byte[] encryptedBlock2 = BitConverter.GetBytes(block2);
Array.Copy(encryptedBlock1, 0, result, i, 4);
Array.Copy(encryptedBlock2, 0, result, i + 4, 4);
}
return result;
}
public static byte[] Decrypt(byte[] data)
{
byte[] result = new byte[data.Length];
for (int i = 0; i < data.Length; i += 8)
{
uint block1 = BitConverter.ToUInt32(data, i);
uint block2 = BitConverter.ToUInt32(data, i + 4);
uint sum = 0xC6EF3720;
uint delta = 0x9E3779B9;
for (int j = 0; j < 32; j++)
{
block2 -= ((block1 << 4 ^ block1 >> 5) + block1) ^ (sum + key[sum >> 11 & 3]);
sum -= delta;
block1 -= ((block2 << 4 ^ block2 >> 5) + block2) ^ (sum + key[sum & 3]);
}
byte[] decryptedBlock1 = BitConverter.GetBytes(block1);
byte[] decryptedBlock2 = BitConverter.GetBytes(block2);
Array.Copy(decryptedBlock1, 0, result, i, 4);
Array.Copy(decryptedBlock2, 0, result, i + 4, 4);
}
int padding = result[result.Length - 1];
byte[] unpaddedData = new byte[result.Length - padding];
Array.Copy(result, unpaddedData, unpaddedData.Length);
return unpaddedData;
}
}
```
使用方法示例:
```csharp
string data = "Hello World!";
byte[] encryptedData = XTEA.Encrypt(Encoding.UTF8.GetBytes(data));
byte[] decryptedData = XTEA.Decrypt(encryptedData);
string result = Encoding.UTF8.GetString(decryptedData);
Console.WriteLine(result); // 输出:Hello World!
```
注意:此代码仅作为示例供参考,实际使用时需要根据具体需求进行修改和优化。
阅读全文