obfuz/Editor/EncryptionVM/VirtualMachineCreator.cs

55 lines
2.2 KiB
C#
Raw Normal View History

2025-05-11 12:53:24 +08:00
using Obfuz.EncryptionVM.Instructions;
2025-05-11 12:48:53 +08:00
using Obfuz.Utils;
using UnityEngine.Assertions;
2025-05-11 12:53:24 +08:00
namespace Obfuz.EncryptionVM
2025-05-11 12:48:53 +08:00
{
2025-05-11 12:53:24 +08:00
public class VirtualMachineCreator
2025-05-11 12:48:53 +08:00
{
private readonly int[] _vmGenerationSecretKey;
private readonly IRandom _random;
public const int CodeGenerationSecretKeyLength = 1024;
2025-05-11 12:53:24 +08:00
public VirtualMachineCreator(string vmGenerationSecretKey, byte[] encryptionSecretKey)
2025-05-11 12:48:53 +08:00
{
_vmGenerationSecretKey = KeyGenerator.ConvertToIntKey(KeyGenerator.GenerateKey(vmGenerationSecretKey, CodeGenerationSecretKeyLength));
_random = new RandomWithKey(encryptionSecretKey, 0);
}
private IEncryptionInstruction CreateRandomInstruction(int intSecretKeyLength)
{
switch (_random.NextInt(3))
{
case 0:
return new AddInstruction(_random.NextInt(), _random.NextInt(intSecretKeyLength));
case 1:
return new XorInstruction(_random.NextInt(), _random.NextInt(intSecretKeyLength));
case 2:
return new BitRotateInstruction(_random.NextInt(32), _random.NextInt(intSecretKeyLength));
default:
throw new System.Exception("Invalid instruction type");
}
}
private EncryptionInstructionWithOpCode CreateEncryptOpCode(ushort code)
{
2025-05-11 12:53:24 +08:00
IEncryptionInstruction inst = CreateRandomInstruction(VirtualMachine.SecretKeyLength / sizeof(int));
2025-05-11 12:48:53 +08:00
Assert.AreEqual(1234, inst.Decrypt(inst.Encrypt(1234, _vmGenerationSecretKey, 0x12345678), _vmGenerationSecretKey, 0x12345678));
return new EncryptionInstructionWithOpCode(code, inst);
}
2025-05-11 12:53:24 +08:00
public VirtualMachine CreateVirtualMachine(int opCodeCount)
2025-05-11 12:48:53 +08:00
{
Assert.IsTrue(opCodeCount > 0);
Assert.AreEqual(0, opCodeCount & (opCodeCount - 1));
var opCodes = new EncryptionInstructionWithOpCode[opCodeCount];
for (int i = 0; i < opCodes.Length; i++)
{
opCodes[i] = CreateEncryptOpCode((ushort)i);
}
2025-05-11 12:53:24 +08:00
return new VirtualMachine(_vmGenerationSecretKey, opCodes);
2025-05-11 12:48:53 +08:00
}
}
}