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
|
|
|
|
{
|
2025-05-11 17:36:58 +08:00
|
|
|
|
private readonly string _vmGenerationSecretKey;
|
2025-05-11 12:48:53 +08:00
|
|
|
|
private readonly IRandom _random;
|
|
|
|
|
|
|
|
|
|
public const int CodeGenerationSecretKeyLength = 1024;
|
|
|
|
|
|
2025-05-11 17:36:58 +08:00
|
|
|
|
public const int VirtualMachineVersion = 1;
|
|
|
|
|
|
|
|
|
|
public VirtualMachineCreator(string vmGenerationSecretKey)
|
2025-05-11 12:48:53 +08:00
|
|
|
|
{
|
2025-05-11 17:36:58 +08:00
|
|
|
|
_vmGenerationSecretKey = vmGenerationSecretKey;
|
|
|
|
|
byte[] byteGenerationSecretKey = KeyGenerator.GenerateKey(vmGenerationSecretKey, CodeGenerationSecretKeyLength);
|
|
|
|
|
_random = new RandomWithKey(byteGenerationSecretKey, 0);
|
2025-05-11 12:48:53 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
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
|
|
|
|
{
|
2025-05-11 17:36:58 +08:00
|
|
|
|
if (opCodeCount < 64)
|
|
|
|
|
{
|
|
|
|
|
throw new System.Exception("OpCode count should be >= 64");
|
|
|
|
|
}
|
|
|
|
|
if ((opCodeCount & (opCodeCount - 1)) != 0)
|
|
|
|
|
{
|
|
|
|
|
throw new System.Exception("OpCode count should be power of 2");
|
|
|
|
|
}
|
2025-05-11 12:48:53 +08:00
|
|
|
|
var opCodes = new EncryptionInstructionWithOpCode[opCodeCount];
|
|
|
|
|
for (int i = 0; i < opCodes.Length; i++)
|
|
|
|
|
{
|
|
|
|
|
opCodes[i] = CreateEncryptOpCode((ushort)i);
|
|
|
|
|
}
|
2025-05-11 17:36:58 +08:00
|
|
|
|
return new VirtualMachine(VirtualMachineVersion, _vmGenerationSecretKey, opCodes);
|
2025-05-11 12:48:53 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|