How to get original data before decryption ?

ahmed salah 3,216 Reputation points
2021-12-13T00:07:07.967+00:00

I work on csharp I need to get data before decryption
but i don't know how to do that
data decrypted on file as below :

 ˆU*o" ى,be~ùث »وچٍ­اàےي¾أ(هشْé Pشم¢×l. ZS’ى² N· ¾«é¬Q غتُ ’ذi,اGNِء”©¢¼î¨C2‡ ùu35Yôy ¾إ ً¼@پ6¹qv¹آœإûج 4 Hu؟¼إ‘{‏]…J î‚üد*ڈ ئل x, KiئإUچ ¥.®_™ù

expected result i need to reach is
Serial Machine :xxxx
Computer Name :dddd
User Name :ahmedsa
Start Date :2021/12/13
Period :30

so i need to create variiable name string originaldata
and get data above on it
so how to do that please
source code

public static string GetMACAddress()
    {
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        String sMacAddress = string.Empty;
        foreach (NetworkInterface adapter in nics)
        {
            if (sMacAddress == String.Empty)// only return MAC Address from first card
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                sMacAddress = adapter.GetPhysicalAddress().ToString();
            }
        }
        return sMacAddress;
    }
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;
        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                    cs.Close();
                }
                encryptedBytes = ms.ToArray();
            }
        }

        return encryptedBytes;
    }
    public static void EncryptFile(string file, string password)
    {

        byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);


        passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

        byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

        File.WriteAllBytes(file, bytesEncrypted);
        var licenseFile =
       Path.Combine(Environment.GetFolderPath(
       Environment.SpecialFolder.LocalApplicationData), "Secret", "Something.License");
        System.IO.File.Move(file, licenseFile);


    }
    public static void licenseCreator(string password)
    {
        string path = "//license.txt";
        string fullpath = Application.StartupPath + path;

        string[] lines = { password };
        System.IO.File.WriteAllLines(fullpath, lines);

    }
    private void Button1_Click(object sender, EventArgs e)
    {

        string finalTextLicense = "Serial Machine :" + textBox1.Text + System.Environment.NewLine + "Computer Name :" + textBox2.Text + System.Environment.NewLine + "User Name :" + textBox3.Text + System.Environment.NewLine + "Start Date :" + (textBox6.Text + "/" + textBox5.Text + "/" + textBox4.Text) + System.Environment.NewLine + "Period :" + textBox7.Text + System.Environment.NewLine + "End Date :" + (textBox10.Text + "/" + textBox9.Text + "/" + textBox8.Text);

        licenseCreator(finalTextLicense);

        if (File.Exists("License.txt"))
        {
            var validExtensions = new[]
        {
            ".txt"
        };

            string[] files = Directory.GetFiles(Application.StartupPath);

            for (int i = 0; i < files.Length; i++)
            {
                string extension = Path.GetExtension(files[i]);
                if (validExtensions.Contains(extension))
                {
                    EncryptFile(files[i], finalTextLicense);
                }
            }

        }

    }

    private void CreateLicense_Load(object sender, EventArgs e)
    {
        textBox1.Text = GetMACAddress();
        textBox2.Text = System.Net.Dns.GetHostName();
        textBox7.Text = "30";
        String sDate = DateTime.Now.ToString();
        DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));

        textBox4.Text = datevalue.Day.ToString();
        textBox5.Text = datevalue.Month.ToString();
        textBox6.Text = datevalue.Year.ToString();
        DateTime EndDate = Convert.ToDateTime(sDate).AddDays(Convert.ToInt32(textBox7.Text));

        textBox8.Text = EndDate.Day.ToString();
        textBox9.Text = EndDate.Month.ToString();
        textBox10.Text = EndDate.Year.ToString();


    }
    public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {

                AES.KeySize = 256;
                AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                    cs.Close();
                }
                decryptedBytes = ms.ToArray();


            }
        }

        return decryptedBytes;
    }
    public void DecryptFile(string file, string password)
    {
        try
        {
            byte[] bytesToBeDecrypted = File.ReadAllBytes(file);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

            byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
            for (int i = 0; i < bytesDecrypted.Length; i++)
            {

            }

            MessageBox.Show("good license!");


        }
        catch (Exception ex)
        {
            MessageBox.Show("wrong license!" + ex.Message);
        }


    }
    private void Button2_Click(object sender, EventArgs e)
    {
        string finalTextLicense = "Serial Machine :" + textBox1.Text + System.Environment.NewLine + "Computer Name :" + textBox2.Text + System.Environment.NewLine + "User Name :" + textBox3.Text + System.Environment.NewLine + "Start Date :" + (textBox6.Text + "/" + textBox5.Text + "/" + textBox4.Text) + System.Environment.NewLine + "Period :" + textBox7.Text + System.Environment.NewLine + "End Date :" + (textBox10.Text + "/" + textBox9.Text + "/" + textBox8.Text);
        var licenseFile =
    Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), "Secret", "Something.License");

        if (File.Exists(licenseFile))
        {
            var validExtensions = new[]
        {
            ".License"
        };

            string[] files = Directory.GetFiles(Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), "Secret"));
            for (int i = 0; i < files.Length; i++)
            {
                string extension = Path.GetExtension(files[i]);
                if (validExtensions.Contains(extension))
                {
                    DecryptFile(files[i], finalTextLicense);
                }
            }
        }
        if (!File.Exists("something.license"))
        {
            MessageBox.Show("license not found!");
        }
    }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,387 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,266 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,526 Reputation points
    2021-12-17T21:29:24.25+00:00

    the password is just a red herring (and there is no particular reason to hash it, but it doesn't matter).

    the big flaw in the code is that Rfc2898DeriveBytes() generates a new random key when called. calling twice with the same inputs will return different keys. so the encrypted data can not be decrypted, because the decryption code has no access to the key used for encryption.

    note: the tutorial samples using Rfc2898DeriveBytes() use the same generated key instance for encrypt and decrypt.


3 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,526 Reputation points
    2021-12-15T16:31:10.81+00:00

    the hash is just on the password used as an input to the cipher, so both hashes return the same value (a rather pointless step, but not fatal). the issue, is that Rfc2898DeriveBytes() generates a new unique key every time it is called. you must save this key if you want to decode later.


  2. P a u l 10,406 Reputation points
    2021-12-16T01:45:20.06+00:00

    I'm just looking at your Button2_Click method where you're calling this:

    DecryptFile(files[i], finalTextLicense);
    

    The second argument of DecryptFile should be the password, but you're passing what looks like the data itself. You haven't posted where you're called EncryptFile from, but the password you're passing to that method is what you need to pass to DecryptFile.


  3. AgaveJoe 26,136 Reputation points
    2021-12-16T21:11:51.777+00:00

    As far as I can tell, your code just does not work due to logical errors. The results of CreateLicense_Load() event changes daily due to DateTime.Now. The data generated from CreateLicense_Load() is hashed and used as a password. As stated above, hashing is a one way operation. Once data is hashed you cannot get it back. You need the original hash source to recreate the hash. Again, as far as I can tell, that's not possible because the DateTime is different every day.

    I agree with Paul, it seems like the hashed data is the actual data you want to get back and you are using it as a password to encrypt/decrypt other files on the system???

    Can you explain the general design? Then maybe the community can provide guidance.

    Another option is using the Visual Studio debugger to step through the code. I'm pretty sure you'll be able to find the bugs if you pay attention to the data.

    Edit: while the logic is difficult to understand, your code works as long as the day has not changed.

    public void DecryptFile(string file, string password)
    {
        try
        {
            byte[] bytesToBeDecrypted = File.ReadAllBytes(file);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
    
            byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
            //for (int i = 0; i < bytesDecrypted.Length; i++)
            //{
    
            //}
    
            string text = System.Text.Encoding.UTF8.GetString(bytesDecrypted);
            MessageBox.Show(text);
            MessageBox.Show("good license!");
        }
        catch (Exception ex)
        {
            MessageBox.Show("wrong license!" + ex.Message);
        }
    }
    

    You have a bug that always shows license not found! because the file is located in another directory. The fix is below.

    if (!File.Exists(licenseFile))
    {
        MessageBox.Show("license not found!");
    }