0

Ok so I have a small program that I built in C# winforms that is basically using security cryptology and I am trying to figure out what I did wrong in the code. It will encrypt the text file fine. However, when I paste the encrypted file in the textbox and hit Decrypt, it does not decrypt the file but encrypts it again.

I am wondering if I did something wrong with the code.

namespace Encrypted
{
    class Encryptor
    {
        public static string IV = "1a1a1a1a1a1a1a1a";
        public static string Key = "1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a";

        public static string Encrypt (string decrypted)
        {
            byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(decrypted);
            AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
            endec.BlockSize = 128;
            endec.KeySize = 256;
            endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
            endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            endec.Padding = PaddingMode.PKCS7;
            endec.Mode = CipherMode.CBC;
            ICryptoTransform icrypt = endec.CreateEncryptor(endec.Key, endec.IV);
            byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
            icrypt.Dispose();
            return Convert.ToBase64String(enc);
        }

        public static string Decrypted(string encrypted)
        {
            byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(encrypted);
            AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
            endec.BlockSize = 128;
            endec.KeySize = 256;
            endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
            endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            endec.Padding = PaddingMode.PKCS7;
            endec.Mode = CipherMode.CBC;
            ICryptoTransform icrypt = endec.CreateEncryptor(endec.Key, endec.IV);
            byte[] enc = icrypt.TransformFinalBlock(textbytes, 0,     textbytes.Length);
            icrypt.Dispose();
            return ASCIIEncoding.ASCII.GetString(enc);
        }
    }
 }

This is the class above and below is the Form1:

namespace Encrypted
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            string dir = textBox1.Text;
            Directory.CreateDirectory("data\\" + dir);

            var sw = new StreamWriter("data\\" + dir + "data.ls");

            string enctxt = Encryptor.Encrypt(textBox1.Text);

            sw.WriteLine(enctxt);

            sw.Close();
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            string dir = textBox2.Text;
            Directory.CreateDirectory("data\\" + dir);

            var sw = new StreamWriter("data\\" + dir + "data.ls");

            string enctxt = Encryptor.Decrypted(textBox2.Text);

            sw.WriteLine(enctxt);

            sw.Close();
        }
    }

In the Decrypt button do I need to use StreamReader or StreamWriter. Once the encrypted file is in the data.ls I copy it and paste it into the text box for decrypt. However is does not decrypt, it only re-encrypts the file. Is there something I am doing wrong?

12
  • So the Decrypted method should be calling CreateDecryptor (not CreateEncryptor), correct? Jun 17, 2016 at 2:40
  • well when I call the CreateDecryptor it throws an error, saying that the block is not a full block
    – campnerd
    Jun 17, 2016 at 3:01
  • The next most obvious problem is that you are not using the same encoding on the encrypted string. You return a base-64 string from encrypt but then you are using ASCII when encoding in Decrypted. You should be encoding using Convert.FromBase64String to get textbytes. Jun 17, 2016 at 3:17
  • @mike now it throws an error Exception thrown: 'System.ArgumentException' in mscorlib.dll Additional information: Illegal characters in path.
    – campnerd
    Jun 17, 2016 at 3:29
  • You are using the input data to create a directory. If that data has characters that can't be used in a path you are out of luck. The way I would design this would be to ask the user for the input data and a file name. FWIW, the Encryptor class works fine for me if I make the two changes I suggested. Jun 17, 2016 at 3:49

3 Answers 3

4

This is because you are using the Decrypted() also for encrypting the input file by Creating Encryptor. It should Create a Decryptor to perform the Decryption operation. This single word change will reverse the process. the CreateDecryptor Method (Byte[], Byte[]) of AesCryptoServiceProvider class will Creates a symmetric AES decryptor object using the specified key and initialization vector (IV).

ie. Change the following line in the Decrypted() method,

  ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV);

Here is a Reference example from MSDN and you can see a Working example here

8
  • when I do it this way it throws this error An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in System.Core.dll Additional information: The input data is not a complete block.
    – campnerd
    Jun 17, 2016 at 2:48
  • when I use it the way I had it it does not throw any errors
    – campnerd
    Jun 17, 2016 at 2:48
  • this is what I have, I changed it like your answer but it does not work. ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV);
    – campnerd
    Jun 17, 2016 at 2:55
  • @campnerd : See this reference msdn.microsoft.com/en-us/library/… Jun 17, 2016 at 3:01
  • the samples on MSDN shows it in a console app. So they are using CryptoStreamMode.Writer. Now if I look at my code I am using stream writer. Is there a difference? Also, MSDN show the code using static string methods, versus I am using public static string methods. Could this be calling the error. Everything I have done lines up with MSDN but when I follow your sample and instructions I get an error. However before the program ran with no errors.
    – campnerd
    Jun 17, 2016 at 3:21
0

It's not only the mistake of not using CreateDecryptor. You also have to decode the ciphertext string from base64, which is what your encrypt returns.

You are doing this:

  1. take string, decode from ASCII to plaintext bytes

  2. take plaintext bytes, encrypt to ciphertext bytes

  3. take ciphertext bytes, convert to base64 string

Then you do this:

  1. take string, decode from ASCII to ciphertext bytes <-- your mistake!

instead:

  1. take string, decode from base64 to ciphertext bytes

  2. take ciphertext bytes, decrypt to plaintext bytes

  3. take plaintext bytes, encode to ASCII.

string -> bytes -> encrypted bytes -> base64 -> encrypted bytes -> bytes -> string

1
  • 1
    Ok now that makes more sense than what the other guy was saying.. So basically I have the code right just in the wrong order. When I get back home I will see what changes I made. This works perfect on the encryption side. However I got to put the correct order of code for decryption. I thought I done that. I guess I did not eat enough sweet-tarts when I started this..lol
    – campnerd
    Jun 18, 2016 at 3:44
0

I searched for it and made a program that worked fine with me :) So...

This is the class

   class Encryptor
{
    public static string IV = "1a1a1a1a1a1a1a1a";
    public static string Key = "1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a13";

    public static string Encrypt(string decrypted)
    {
        byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(decrypted);
        AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
        endec.BlockSize = 128;
        endec.KeySize = 256;
        endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        endec.Padding = PaddingMode.PKCS7;
        endec.Mode = CipherMode.CBC;
        ICryptoTransform icrypt = endec.CreateEncryptor(endec.Key, endec.IV);
        byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
        icrypt.Dispose();
        return Convert.ToBase64String(enc);
    }

    public static string Decrypted(string encrypted)
    {
        byte[] textbytes = Convert.FromBase64String(encrypted);
        AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
        endec.BlockSize = 128;
        endec.KeySize = 256;
        endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        endec.Padding = PaddingMode.PKCS7;
        endec.Mode = CipherMode.CBC;
        ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV);
        byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
        icrypt.Dispose();
        return System.Text.ASCIIEncoding.ASCII.GetString(enc);
    }
}

...................................

and this is the form`

        private void button1_Click(object sender, EventArgs e)
    {
        string dir = textBox1.Text;
        Directory.CreateDirectory("data\\" + dir);

        var sw = new StreamWriter("data\\" + dir + "data.ls");

        string enctxt = Encryptor.Encrypt(textBox1.Text);

        sw.WriteLine(enctxt);

        sw.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string dir = textBox2.Text;

        StreamReader sr = new StreamReader(Application.StartupPath +"\\data\\"+ dir + "data.ls");
        string line = sr.ReadLine();

        textBox1.Text = Encryptor.Decrypted(Convert.ToString(line));
    }

........................

Best regards !

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.