Opposite operation to Assembly Load(byte[] rawAssembly)

前端 未结 3 882
庸人自扰
庸人自扰 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());
    

提交回复
热议问题