Как использовать Phoenix Protector в Visual Studio Xamarin

#xamarin #obfuscation

#xamarin #запутывание

Вопрос:

из того, что я вижу в ildasm, после использования Phoenix Protector в DLL результирующая запутанная DLL кажется ОЧЕНЬ запутанной. Не совсем так обстоит дело с Dotfuscator Community Edition.

Я могу поместить командную строку в раздел после сборки VS, чтобы вызвать Phoenix Protector, а затем скопировать результирующую DLL обратно в каталог основного выпуска.

ОДНАКО, когда я делаю это, компоновщик завершается с ошибкой: он не может найти определенную процедуру.

Есть идеи о том, как использовать Phoenix Protector в DLL, которая упаковывается для Android.

Ответ №1:

Ну, я уже пробовал использовать его с xamarin и его сборкой, но приложение не может запуститься на моем Samsung. итак, я действительно не знаю, в чем проблема.

Здесь я расскажу вам, как его использовать.

Сначала создайте проект и назовите его как-нибудь, в моем случае Tasker

Создайте класс с именем Locker , это важно при использовании более чем одной платформы.

 using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;


namespace Tasker
{
    public abstract class Locker : Task
    {
        public string ApplicationPath { get; set; }
        public string Source { get; set; }
        protected string DllSource { get; set; }
        protected string settingsPath { get; set; }
        protected string TaskLocker { get; set; }
        public bool Hidden { get; set; }
        public bool StayOpen { get; set; }
        protected void Lock()
        {
            try
            {
                File.WriteAllText(TaskLocker, "true");
            }
            catch
            {

            }
        }

        protected void Release()
        {
            try
            {
                 File.Delete(TaskLocker);
            }
            catch
            {

            }
        }

        protected bool Await()
        {
            try
            {
                return File.Exists(TaskLocker) amp;amp; !string.IsNullOrWhiteSpace(File.ReadAllText(TaskLocker));
            }
            catch
            {
                return true;
            }
        }


        protected void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir))
            {
                var dic = new DirectoryInfo(dir);
                foreach (var file in dic.GetFiles("*.*", SearchOption.AllDirectories))
                    file.Delete();
                try
                {
                    dic.Delete(true);
                }
                catch
                {

                }
            }
        }

        protected bool SetDllSource()
        {
            DllSource = Source.Replace("\bin\", "\obj\");
            var dllFile = Path.GetFileName(Source);
            if (!File.Exists(DllSource))
            {
                base.Log.LogMessage(MessageImportance.High, DllSource   " Could not be found. Please rebuild agen, will try search for the right dll");
                var d = new DirectoryInfo(Path.GetDirectoryName(DllSource)).GetFiles($"*{dllFile}*", SearchOption.AllDirectories).FirstOrDefault(); // fix for mono
                if (d == null)
                {
                    base.Log.LogMessage(MessageImportance.High, DllSource   " Could not be found. Please rebuild agen ");
                    return false;
                }
                else DllSource = d.FullName;
                base.Log.LogMessage(MessageImportance.High, "will use this dll instead:"   DllSource);
            }
            return true;
        }
    }
}
  

теперь создайте класс с именем Phoenix_Protector , которое наследуется от locker

 using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

namespace Tasker
{
    public class Phoenix_Protector : Locker
    {
        static string CalculateMD5(string filename)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filename))
                {
                    var hash = md5.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "");
                }
            }
        }

        static string ToBase64String(string msg)
        {
            var hash = Encoding.Unicode.GetBytes(msg   "");
            return Convert.ToBase64String(hash);
        }

        private void CreateProjectFile()
        {
            if (!File.Exists(settingsPath))
            {
                var msg = DllSource.Trim();
                var base64String = ToBase64String(msg);
                var hash = CalculateMD5(msg);

                var str = new StringBuilder()
                    .AppendLine("<?xml version="1.0" ?>")
                    .AppendLine("<PROJECT Version="1">")
                    .AppendLine("    <FILES>")
                    .AppendLine("        <FILE>")
                    .AppendLine("           <SOURCE>")
                    .AppendLine("               "   base64String)
                    .AppendLine("           </SOURCE>")
                    .AppendLine("           <CHECKSUM>"   hash   "</CHECKSUM>")
                    .AppendLine("            <DOTNET>")
                    .AppendLine("               <OBFUSCATE_NAMES>TRUE</OBFUSCATE_NAMES>")
                    .AppendLine("               <OBFUSCATE_PUBLIC_NAMES>FALSE</OBFUSCATE_PUBLIC_NAMES>")
                    .AppendLine("               <OBFUSCATE_FIELDS>TRUE</OBFUSCATE_FIELDS>")
                    .AppendLine("               <OBFUSCATE_PROPERTIES>FALSE</OBFUSCATE_PROPERTIES>")
                    .AppendLine("               <EXCLUDE_NAMES>FALSE</EXCLUDE_NAMES>")
                    .AppendLine("               <NO_OBFUSCATION_ARRAY></NO_OBFUSCATION_ARRAY>")
                    .AppendLine("               <OBFUSCATE_STRINGS>TRUE</OBFUSCATE_STRINGS>")
                    .AppendLine("               <CODE_SCRAMBLE>FALSE</CODE_SCRAMBLE>")
                    .AppendLine("               <REMOVE_SNS>FALSE</REMOVE_SNS>")
                    .AppendLine("            </DOTNET>")
                    .AppendLine("        </FILE>")
                    .AppendLine("    </FILES>")
                    .AppendLine("</PROJECT>");

                File.WriteAllText(settingsPath, str.ToString());

            }
        }

        public override bool Execute()
        {
            var directory = Path.GetDirectoryName(Source);
            var dllDirNew = Path.Combine(directory, Path.GetFileNameWithoutExtension(Source));
            var applicationPath = Path.GetDirectoryName(ApplicationPath);
            var name = Path.GetFileName(ApplicationPath);
            var nettype = directory.Split('\').Last();
            settingsPath = Path.Combine(new DirectoryInfo(Path.GetDirectoryName(Source)).Parent.Parent.FullName, nettype   "_Obfuscation_Project.ppe");
            TaskLocker = Path.Combine(new DirectoryInfo(Path.GetDirectoryName(Source)).Parent.Parent.FullName, "lock.config");
            if (!SetDllSource())
            {
                return false;
            }

            DeleteFolder(dllDirNew);
            base.Log.LogMessage(MessageImportance.High, "Process:"   DllSource);

            Directory.CreateDirectory(dllDirNew);
            CreateProjectFile();
            while (Await())
                Thread.Sleep(300);
            Lock();
            var args = $"-p "{settingsPath}" "{dllDirNew}" {(StayOpen ? "/K" : "")}";

            var process = new Process
            {
                StartInfo = new ProcessStartInfo()
                {
                    Arguments = args,
                    FileName = name,
                    WorkingDirectory = applicationPath,
                    WindowStyle = Hidden ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal
                }
            };

            var exited = false;
            process.EnableRaisingEvents = true;
            process.Exited  = new EventHandler((o, e) =>
            {
                exited = true;
            });
            string counter = ".";
            base.Log.LogMessage(MessageImportance.High, "Obfuscation-Start:"   Source);
            base.Log.LogMessage(MessageImportance.High, "ApplicationWorkingDirectory:"   applicationPath);
            base.Log.LogMessage(MessageImportance.High, "ApplicationFileName:"   name);
            base.Log.LogMessage(MessageImportance.High, "Args:"   args);
            process.Start();
            const int SleepAmount = 100;
            var elapsedTime = 0;
            while (!exited)
            {
                base.Log.LogMessage(MessageImportance.High, counter);
                counter  = ".";
                elapsedTime  = SleepAmount;
                Thread.Sleep(SleepAmount);
            }

            Thread.Sleep(1000);
            var files = new DirectoryInfo(dllDirNew).GetFiles("*.*", SearchOption.AllDirectories);
            if (files.Any())
            {
                foreach (var file in files)
                {
                    if (Source.Contains(file.Name))
                    {
                        base.Log.LogMessage(MessageImportance.High, $"Copy:{file.FullName} To {Source}");
                        File.Delete(Source);
                        file.CopyTo(Source, true);
                    }
                    else
                    {
                        //var xName = file.Name.Contains("appExtension") ? $"{autoName}.{file.Name}" : file.Name;


                        base.Log.LogMessage(MessageImportance.High, $"Copy:{file.FullName} To {Path.Combine(directory, file.Name)}");
                        File.Delete(Path.Combine(directory, file.Name));
                        file.CopyTo(Path.Combine(directory, file.Name), true);
                    }
                }

                DeleteFolder(dllDirNew);
            }

            base.Log.LogMessage(MessageImportance.High, "Obfuscation-Finish:"   Source);
            Release();
            return true;
        }
    }
}
  

Это UserTask .

Теперь создайте Obfuscation.props файл и сохраните его в корневой папке вашего решения.

 <?xml version="1.0" encoding="utf-8" ?>
<Project>
 <UsingTask TaskName="Tasker.Phoenix_Protector" AssemblyFile="E:ProjectsTaskerbinReleasenetstandard2.0tasker.dll" />
 </Project>
  

И теперь в вашем файле проекта ( csproj ) Добавьте эти строки внизу.

   <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)'=='Release'">
    <Phoenix_Protector ApplicationPath="C:Program Files (x86)NTCorePhoenix ProtectorPhoenix_Protector.exe" Source="$(TargetPath)" />
  </Target>

  <Import Condition="Exists('..Obfuscation.props')" Project="..Obfuscation.props" />
  

Дайте мне знать, как это происходит, я имею в виду, если ваше приложение запустится, в моем случае все заработает. запутывание ddl и сборка решения. Я также могу создать свой apk и установить его, но сбой моего приложения, я еще не исследовал это.

Я также не могу использовать progaurd, когда я запутываю свою dll. И это происходит не только с Phoenix_Protector, но и с другими приложениями для запутывания.

Я должен также упомянуть, что вам следует переименовать Phoenix Protector в Phoenix_Protector , иначе командная строка действительно не будет работать.