Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am new to C# and I am trying to encrypt data to a file and later use that data for licencing purpose. I am using visual studio documentation example for encryption and decryption purposes.

EncryptTextToFile() is used to encrypt text to file. Later DecryptTextFromFile() is used to decrypt from file. Now what happens is that first function creates the file and then when it is red by DecryptTextFromFile() it shows exactly what was initially stored.

When EncryptTextToFile() is commented and only decrypting function is used to decrypted an already stored file following error occured:
An error occurred: Padding is invalid and cannot be removed.


Here is the code:

C#
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class RijndaelSample
{

    static void Main()
    {
        try
        {
            // Create a new Rijndael object to generate a key
            // and initialization vector (IV).
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a string to encrypt.
            string sData = "BFEBFBFF00020652#0000";
            string FileName = "system.txt";

            // Encrypt text to a file using the file name, key, and IV.
            //EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV);

            // Decrypt the text from a file using the file name, key, and IV.
            string Decrypted_text = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV);
            char []computer_id=new char[16];
            for (int K = 0; K < 16; K++)
            {
                computer_id[K] = Decrypted_text[K];
            }
           Int64 counts = 1000 * (Convert.ToInt64(Decrypted_text[17]) -48)+ 100 * (Convert.ToInt64(Decrypted_text[18])-48) + 10 * (Convert.ToInt64(Decrypted_text[19])-48) + (Convert.ToInt64(Decrypted_text[20])-48);
                    
                // Display the decrypted string to the console.
           Console.WriteLine(Decrypted_text);
Console.WriteLine(counts);
           Console.WriteLine(Convert.ToInt64(Decrypted_text[17]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[18]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[19]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[20]));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }

    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter(cStream);

            try
            {
                // Write the data to the stream 
                // to encrypt it.
                sWriter.WriteLine(Data);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {
                // Close the streams and
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
        }

    }

    public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file. 
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateDecryptor(Key, IV),
                CryptoStreamMode.Read);

            // Create a StreamReader using the CryptoStream.
            StreamReader sReader = new StreamReader(cStream);

            string val = null;

            try
            {
                // Read the data from the stream 
                // to decrypt it.
                val = sReader.ReadLine();
               // val = sReader.ReadToEnd();
            


            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {

                // Close the streams and
                // close the file.
                sReader.Close();
                cStream.Close();
                fStream.Close();
            }
           
            // Return the string. 
            return val;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
    }
}


Kindly help me solve this problem.
Posted
Updated 26-Oct-11 0:40am
v2
Comments
Slacker007 26-Oct-11 6:41am    
Edit: readability and some formatting.

The problem is (I suppose) the line
C#
Rijndael RijndaelAlg = Rijndael.Create();

It generates a fresh key everytime is called. When you need to decrypt a previously encrypted file you must provide exactly the same key used for encrypting it.
 
Share this answer
 
Comments
BobJanova 26-Oct-11 8:41am    
Good catch
CPallini 26-Oct-11 9:07am    
Thank you.
Hi,

at the start of your program you create a new Rijndael-instance and use it's key and iv for en-/decryption. Thus, when you go through both functions in THE SAME run, you use THE SAME key/iv-pair for en- and for decryption.

If you go through them separately, you use different key/iv-pairs, as Rijndael.Create() creates random values each time, you call it. Save both key and vector on the first run and load them on subsequent runs and all will be fine.

Cheers
Jürgen

--
If this saved you some time, give some it back by voting
 
Share this answer
 
Comments
BobJanova 26-Oct-11 8:41am    
Good catch.
Thanks to both of you. The problem is resolved.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900