2025-05-11 17:36:58 +08:00
|
|
|
|
using Obfuz.Utils;
|
|
|
|
|
using System;
|
2025-05-11 10:37:42 +08:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq.Expressions;
|
|
|
|
|
using System.Runtime.CompilerServices;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using UnityEngine.Assertions;
|
|
|
|
|
using UnityEngine.UIElements;
|
|
|
|
|
|
2025-05-11 12:53:24 +08:00
|
|
|
|
namespace Obfuz.EncryptionVM
|
2025-05-11 10:37:42 +08:00
|
|
|
|
{
|
|
|
|
|
|
2025-05-11 12:53:24 +08:00
|
|
|
|
public class VirtualMachineSimulator : EncryptorBase
|
2025-05-11 10:37:42 +08:00
|
|
|
|
{
|
2025-05-11 12:48:53 +08:00
|
|
|
|
private readonly EncryptionInstructionWithOpCode[] _opCodes;
|
2025-05-11 10:37:42 +08:00
|
|
|
|
private readonly int[] _secretKey;
|
|
|
|
|
|
2025-05-11 17:36:58 +08:00
|
|
|
|
public VirtualMachineSimulator(VirtualMachine vm, byte[] byteSecretKey)
|
2025-05-11 10:37:42 +08:00
|
|
|
|
{
|
2025-05-11 12:48:53 +08:00
|
|
|
|
_opCodes = vm.opCodes;
|
2025-05-11 17:36:58 +08:00
|
|
|
|
_secretKey = KeyGenerator.ConvertToIntKey(byteSecretKey);
|
2025-05-11 12:48:53 +08:00
|
|
|
|
|
|
|
|
|
VerifyInstructions();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void VerifyInstructions()
|
|
|
|
|
{
|
|
|
|
|
int value = 0x11223344;
|
|
|
|
|
for (int i = 0; i < _opCodes.Length; i++)
|
|
|
|
|
{
|
|
|
|
|
int encryptedValue = _opCodes[i].Encrypt(value, _secretKey, i);
|
|
|
|
|
int decryptedValue = _opCodes[i].Decrypt(encryptedValue, _secretKey, i);
|
|
|
|
|
Assert.AreEqual(value, decryptedValue);
|
|
|
|
|
}
|
2025-05-11 10:37:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private List<ushort> DecodeOps(int ops)
|
|
|
|
|
{
|
|
|
|
|
var codes = new List<ushort>();
|
|
|
|
|
while (ops > 0)
|
|
|
|
|
{
|
|
|
|
|
var code = (ushort)(ops % _opCodes.Length);
|
|
|
|
|
codes.Add(code);
|
|
|
|
|
ops >>= 16;
|
|
|
|
|
}
|
|
|
|
|
return codes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override int Encrypt(int value, int ops, int salt)
|
|
|
|
|
{
|
|
|
|
|
var codes = DecodeOps(ops);
|
|
|
|
|
foreach (var code in codes)
|
|
|
|
|
{
|
|
|
|
|
var opCode = _opCodes[code];
|
|
|
|
|
value = opCode.Encrypt(value, _secretKey, salt);
|
|
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override int Decrypt(int value, int ops, int salt)
|
|
|
|
|
{
|
|
|
|
|
var codes = DecodeOps(ops);
|
|
|
|
|
for (int i = codes.Count - 1; i >= 0; i--)
|
|
|
|
|
{
|
|
|
|
|
var opCode = _opCodes[codes[i]];
|
|
|
|
|
value = opCode.Decrypt(value, _secretKey, salt);
|
|
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|