.NET去除强签名

概述

使用dnlib来去除强签名及引用的签名。

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Text;
using dnlib.DotNet;

namespace Program
{
    public class Program
    {
        static void Main(string[] args)
        {
            string inputFolder = @"C:\Users\Administrator\Desktop\input";
            string outputFolder = @"C:\Users\Administrator\Desktop\output";
            string PublicKeyToken = "631468bce49458f1";

            var files = Directory.GetFiles(inputFolder, "*.dll");
            foreach (var file in files)
            {
                RemoveStrongSign(file, outputFolder, PublicKeyToken);
            }
        }
        static void RemoveStrongSign(string InputFilePath, string OutputFolder, string PublicKeyToken)
        {
            ModuleContext modCtx = ModuleDef.CreateModuleContext();
            ModuleDefMD module = ModuleDefMD.Load(InputFilePath, modCtx);
            AssemblyDef asm = module.Assembly;
            var nullPublicToken = PublicKey.CreatePublicKey(new byte[0]);

            if (asm.PublicKey == null && asm.HasPublicKey == true)
            {
                asm.HasPublicKey = false;
            }
            if (asm.PublicKey != null && asm.PublicKey.Token != null && asm.PublicKey.Token.ToString().Equals(PublicKeyToken))
            {
                asm.HasPublicKey = false;
                asm.PublicKey = nullPublicToken;
            }

            var asmRefs = module.GetAssemblyRefs();
            foreach (var item in asmRefs)
            {
                if (item.PublicKeyOrToken.ToString().Equals(PublicKeyToken))
                {
                    item.PublicKeyOrToken = nullPublicToken;
                }
            }
            module.Write(OutputFolder + @"\" + module.FullName);
        }
    }
}
Licensed under CC BY-NC-SA 4.0