C # dynamically modifies the signature of the DLL and modifies the signature that references the DLL file

Source: Internet
Author: User

Original: C # dynamically modifies the signature of the DLL and modifies the signature referencing the DLL file

The read Redissessionstateprovider configuration mentions the use of mono Ceil to modify the assembly and its signature, the acquisition of that string inside the Getpublickey and Getpublikeytoken methods, and the subsequent signature we should all It is implemented with code, and the signature that is applied to the DLL file needs to be modified together.

So here's a simple helper method that I've implemented here:

namespaceconsolesession{usingMono.cecil; usingSystem; usingSystem.IO; usingSystem.Linq; usingSystem.Reflection; usingSystem.Runtime.InteropServices;  Public classChangeassemblyinfo { Public stringFileName {Set;Get; }  Public stringFullName {Set;Get; } }     Public classKeyhelper {Static byte[] Getnewkey (stringkeyfilename) {            using(FileStream Keypairstream =File.openread (Keyfilename)) {                return NewStrongNameKeyPair (Keypairstream).            PublicKey; }        }         Public Static voidReSign (stringKeyfilename,stringassemblyfilename) {assemblydefinition asm=assemblydefinition.readassembly (assemblyfilename); Asm. Name.publickey=Getnewkey (keyfilename); Asm.            Write (assemblyFileName); //creating a key container with a key file            byte[] pbKeyBlob =file.readallbytes (keyfilename); stringwszKeyContainer =Guid.NewGuid ().            ToString ();            StrongNameKeyInstall (wszKeyContainer, pbKeyBlob, pbkeyblob.length); //to sign an assembly by line using a new key containerStrongNameSignatureGeneration (assemblyFileName, wszKeyContainer, IntPtr.Zero,0,0,0); //to delete a newly created key containerStrongNameKeyDelete (wszKeyContainer); }        Private Static byte[] Trygetpublickeytoken (stringkeyfilename) {            Try            {                byte[] newpublickey; using(FileStream Keypairstream =File.openread (Keyfilename)) {Newpublickey=NewStrongNameKeyPair (Keypairstream).                PublicKey; }                intPcbstrongnametoken;                IntPtr Ppbstrongnametoken; StrongNameTokenFromPublicKey (Newpublickey, Newpublickey.length, outPpbstrongnametoken, outPcbstrongnametoken); vartoken =New byte[Pcbstrongnametoken]; Marshal.Copy (Ppbstrongnametoken, token,0, Pcbstrongnametoken);                StrongNameFreeBuffer (Ppbstrongnametoken); returntoken; }            Catch(Exception) {return NULL; }        }         Public Static voidRelink (stringKeyfilename, changeassemblyinfo[] assemblyinfolist) {            byte[] PublicKeyToken =Trygetpublickeytoken (keyfilename); if(PublicKeyToken = =NULL)            {                return; }            //get the name of each assembly            foreach(Changeassemblyinfo AssemblyInfoinchassemblyinfolist) {Assemblyinfo.fullname=assemblydefinition.readassembly (assemblyinfo.filename).            Name.fullname; }            //Check if it is referenced, yes, replace PublicKeyToken            foreach(Changeassemblyinfo AssemblyInfoinchassemblyinfolist) {assemblydefinition assembly=assemblydefinition.readassembly (assemblyinfo.filename); foreach(Moduledefinition moduleinchAssembly. Modules)foreach(Assemblynamereference Referenceinchmodule. Assemblyreferences)if(Assemblyinfolist.any (A = A.fullname = =Reference. FullName)) {reference. PublicKeyToken=PublicKeyToken; Assembly.                        Write (Assemblyinfo.filename); }            }        }        #regionThe StrongName library is included as a resource in MsCorEE.dll, and its series of APIs contain[DllImport ("Mscoree.dll", EntryPoint ="StrongNameKeyDelete", CharSet =CharSet.Auto)]Static extern BOOLStrongNameKeyDelete (stringwszKeyContainer); [DllImport ("Mscoree.dll", EntryPoint ="StrongNameKeyInstall", CharSet =CharSet.Auto)]Static extern BOOLStrongNameKeyInstall ([MarshalAs (UNMANAGEDTYPE.LPWSTR)]stringwszKeyContainer, [MarshalAs (UnmanagedType.LPArray, Sizeparamind Ex=2, SizeConst=0)]byte[] pbKeyBlob,intarg0); [DllImport ("Mscoree.dll", EntryPoint ="StrongNameSignatureGeneration", CharSet =CharSet.Auto)]Static extern BOOLStrongNameSignatureGeneration (stringwszFilePath,stringwszKeyContainer, IntPtr pbKeyBlob,intCbkeyblob,intppbSignatureBlob,intPcbsignatureblob); [DllImport ("Mscoree.dll", EntryPoint ="StrongNameErrorInfo", CharSet =CharSet.Auto)]Static extern UINTStrongNameErrorInfo (); [DllImport ("Mscoree.dll", EntryPoint ="StrongNameTokenFromPublicKey", CharSet =CharSet.Auto)]Static extern BOOLStrongNameTokenFromPublicKey (byte[] pbPublicKeyBlob,intCbpublickeyblob, outIntPtr Ppbstrongnametoken, out intPcbstrongnametoken); [DllImport ("Mscoree.dll", EntryPoint ="StrongNameFreeBuffer", CharSet =CharSet.Auto)]Static extern voidStrongNameFreeBuffer (IntPtr pbmemory); #endregion    }}

Call code as follows:

    usingSystem; usingSystem.IO; usingSystem.Linq; usingMono.cecil; classProgram {Static voidMain (string[] args) {            #regionmodifying assembliesstringFilePath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Microsoft.Web.RedisSessionStateProvider3.dll"); Assemblydefinition ASM=assemblydefinition.readassembly (FilePath); Typedefinition[] Types=ASM.            MainModule.Types.ToArray (); //Modify Providerconfiguration to publicTypedefinition typeconfiguration = types. FirstOrDefault (x = X.name = ="providerconfiguration"); Typeconfiguration.ispublic=true; //Modify the Providerconfiguration field to publicTypedefinition typeredisprovide = types. FirstOrDefault (x = X.name = ="Redissessionstateprovider"); FieldDefinition filedconfiguration= TypeRedisProvide.Fields.ToArray (). FirstOrDefault (x = X.name = ="Configuration"); Filedconfiguration.ispublic=true; //Save DLL fileFilePath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Microsoft.Web.RedisSessionStateProvider.dll"); Asm.            Write (FilePath); #endregion            stringKeyfilename =@"D:\mykey.snk"; //Modify the signature of a single DLL filekeyhelper.resign (Keyfilename,filepath); //Modify the signature that references the DLL fileKeyhelper.relink (Keyfilename,Newchangeassemblyinfo[] {Newchangeassemblyinfo {FileName =FilePath},NewChangeassemblyinfo {filename=path.combine (@"C:\Users\UNIT12\Documents\visual Studio 2015\projects\sessionwebapp\sessionwebapp\bin","SessionWebApp.dll")}            }); //console.readline ();        }        }

Resources:

Use Mono-cecil to re-sign. NET programs, relink references to related libraries

C # dynamically modifies the signature of the DLL and modifies the signature that references the DLL file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.