jeudi 6 avril 2017

Emitting a dynamic method

i try to create a dynamic method that will decrypt a string. For a simple example, i used Base64, ReverseString and Substring - 1

Any of these method is working and i can't find my mistake(s).

here the code :

` `     Guid g = Guid.NewGuid();
        AssemblyName asmname = new AssemblyName();
        asmname.Name = "DecryptionAssembly" + g;
        AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain().
            DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);

        // Add a dynamic module that contains one type that has one method that
        // has no arguments.
        ModuleBuilder modbuild = asmbuild.DefineDynamicModule("DecryptionModule");
        TypeBuilder tb = modbuild.DefineType("DecryptionType");
        MethodBuilder somemethod = tb.DefineMethod
            ("DecryptionMethod",
             MethodAttributes.Public | MethodAttributes.Static,
             typeof(string),
             new Type[] { typeof(string)});
        // Define the body of the method to return 0.
        ILGenerator ilg = somemethod.GetILGenerator();
        /* ilg.Emit(OpCodes.Ldarg_0);
         ilg.Emit(OpCodes.Call, typeof(Convert).GetMethod("FromBase64String", new System.Type[] { typeof(string) }));
         ilg.Emit(OpCodes.Stloc_0);
         ilg.Emit(OpCodes.Call, typeof(Encoding).GetMethod("get_UTF8", new System.Type[] {  }));
         ilg.Emit(OpCodes.Ldloc_0);
         ilg.Emit(OpCodes.Callvirt, typeof(Encoding).GetMethod("GetString", new System.Type[] { typeof(byte[]) }));
         ilg.Emit(OpCodes.Ret);*/

        /*    ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Call, typeof(String).GetMethod("ToCharArray", new System.Type[] {  }));
            ilg.Emit(OpCodes.Stloc_0);
            ilg.Emit(OpCodes.Ldloc_0);
            ilg.Emit(OpCodes.Call, typeof(Array).GetMethod("Reverse", new System.Type[] { typeof(Array) }));
            ilg.Emit(OpCodes.Ldloc_0);
            ilg.Emit(OpCodes.Call, typeof(Object).GetMethod("ToString", new System.Type[] {  }));
            ilg.Emit(OpCodes.Ret);*/

        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldc_I4_0);
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Callvirt, typeof(string).GetMethod("get_Length", new System.Type[] {  }));
        ilg.Emit(OpCodes.Ldc_I4_1);
        ilg.Emit(OpCodes.Sub);
        ilg.Emit(OpCodes.Callvirt, typeof(string).GetMethod("Substring", new System.Type[] { typeof(int), typeof(int) }));
        ilg.Emit(OpCodes.Ret);

        Type tbBaked = tb.CreateType();
        string res1 = (string)tbBaked.GetMethod("DecryptionMethod").Invoke(null, new Object[] { "ZWVlZQ==" });
        textBox3.Text = res1;`

Thanks for your help ! `





Aucun commentaire:

Enregistrer un commentaire