LMS.service/LMS.Common/RSAKey/ComplexKeyObfuscator.cs

100 lines
3.6 KiB
C#
Raw Normal View History

2024-10-13 17:04:47 +08:00
using System.Security.Cryptography;
namespace LMS.Common.RSAKey
{
/// <summary>
/// 这是一个混淆器,用于对密钥进行混淆,以增加破解难度
/// </summary>
public static class ComplexKeyObfuscator
{
private const int SaltSize = 16;
/// <summary>
/// 混淆方法
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static byte[] Obfuscate(byte[] key)
{
if (key == null || key.Length == 0)
throw new ArgumentException("Key cannot be null or empty");
byte[] salt = GenerateRandomSalt();
byte[] obfuscatedKey = new byte[key.Length];
Array.Copy(key, obfuscatedKey, key.Length);
// 多层混淆操作
for (int i = 0; i < obfuscatedKey.Length; i++)
{
// 异或操作
obfuscatedKey[i] ^= salt[i % salt.Length];
obfuscatedKey[i] ^= (byte)((i * 17) % 256); // 使用质数17
obfuscatedKey[i] ^= (byte)((obfuscatedKey.Length - i) % 256);
// 位移操作
obfuscatedKey[i] = (byte)(((obfuscatedKey[i] << 3) | (obfuscatedKey[i] >> 5)) & 0xFF);
// 基于位置的置换
int newPos = (i * 7 + 5) % obfuscatedKey.Length; // 使用质数7
byte temp = obfuscatedKey[i];
obfuscatedKey[i] = obfuscatedKey[newPos];
obfuscatedKey[newPos] = temp;
}
// 将salt和混淆后的密钥合并
byte[] result = new byte[salt.Length + obfuscatedKey.Length];
Array.Copy(salt, 0, result, 0, salt.Length);
Array.Copy(obfuscatedKey, 0, result, salt.Length, obfuscatedKey.Length);
return result;
}
/// <summary>
/// 解决混淆方法
/// </summary>
/// <param name="obfuscatedData"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static byte[] Deobfuscate(byte[] obfuscatedData)
{
if (obfuscatedData == null || obfuscatedData.Length <= SaltSize)
throw new ArgumentException("Invalid obfuscated data");
byte[] salt = new byte[SaltSize];
byte[] obfuscatedKey = new byte[obfuscatedData.Length - SaltSize];
Array.Copy(obfuscatedData, 0, salt, 0, SaltSize);
Array.Copy(obfuscatedData, SaltSize, obfuscatedKey, 0, obfuscatedKey.Length);
// 反向多层混淆操作
for (int i = obfuscatedKey.Length - 1; i >= 0; i--)
{
// 反向置换
int newPos = (i * 7 + 5) % obfuscatedKey.Length;
byte temp = obfuscatedKey[i];
obfuscatedKey[i] = obfuscatedKey[newPos];
obfuscatedKey[newPos] = temp;
// 反向位移操作
obfuscatedKey[i] = (byte)(((obfuscatedKey[i] >> 3) | (obfuscatedKey[i] << 5)) & 0xFF);
// 反向异或操作
obfuscatedKey[i] ^= (byte)((obfuscatedKey.Length - i) % 256);
obfuscatedKey[i] ^= (byte)((i * 17) % 256);
obfuscatedKey[i] ^= salt[i % salt.Length];
}
return obfuscatedKey;
}
private static byte[] GenerateRandomSalt()
{
using var rng = RandomNumberGenerator.Create();
byte[] salt = new byte[SaltSize];
rng.GetBytes(salt);
return salt;
}
}
}