Opposite operation to Assembly Load(byte[] rawAssembly)

前端 未结 3 883
庸人自扰
庸人自扰 2021-02-14 22:37

I notice that there is a method of System.Reflection.Assembly, which is Assembly Load(byte[] rawAssembly).

I wonder if there is an opposite ope

相关标签:
3条回答
  • 2021-02-14 23:00

    System.Security.Policy.Hash is able to calculate a Hash regardless of the assembly's location. So we have at least 2 ways to obtain an assembly as a byte array:

    1) Using reflection:

    var hash = new Hash(assembly);
    var dllAsArray = (byte[]) hash.GetType()
        .GetMethod("GetRawData", BindingFlags.Instance | BindingFlags.NonPublic)
        .Invoke(hash, new object[0]);
    

    2) Using a fake HashAlgorithm implementation:

    public class GetWholeBodyPseudoHash : HashAlgorithm
    {
        protected override void Dispose(bool disposing)
        {
            if(disposing) _memoryStream.Dispose();
            base.Dispose(disposing);
        }
    
        static GetWholeBodyPseudoHash()
        {
            CryptoConfig.AddAlgorithm(typeof(GetWholeBodyPseudoHash), typeof(GetWholeBodyPseudoHash).FullName);
        }
    
        private MemoryStream _memoryStream=new MemoryStream();
        public override void Initialize()
        {
            _memoryStream.Dispose();
            _memoryStream = new MemoryStream();
        }
    
        protected override void HashCore(byte[] array, int ibStart, int cbSize)
        {
            _memoryStream.Write(array, ibStart, cbSize);
        }
    
        protected override byte[] HashFinal()
        {
            return _memoryStream.ToArray();
        }
    }
    
    ...
    var bytes = new Hash(yourAssembly).GenerateHash(new GetWholeBodyPseudoHash());
    
    0 讨论(0)
  • 2021-02-14 23:00

    System.Reflection.Assembly implements ISerializable. Create an instance of BinaryFormatter and call its Serialize method on any stream - MemoryStream, FileStream, etc.

    Assembly yourAssembly;
    var formatter = new BinaryFormatter();
    var ms = new MemoryStream();
    formatter.Serialize(ms, yourAssembly);
    var reloadedAssembly = Assembly.Load(ms.GetBuffer()); 
    
    0 讨论(0)
  • 2021-02-14 23:01

    To convert an assembly from AppDomain to byte[] use:

    var pi = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
    byte[] assemblyBytes = (byte[]) pi.Invoke(assembly, null);
    
    0 讨论(0)
提交回复
热议问题