Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am encrypting simple text files using DES.Eery time it appends extra few special charactes in file and same happens when i decrypt the same file.


C#
static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
        {
            {
                SqlConnection conn = null;
                SqlDataReader rdr = null;
                try
                {
                    conn = new
                    SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
                    SqlCommand cmd = new SqlCommand("my_proc", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    conn.Open();
                    SqlDataReader sqlReader = cmd.ExecuteReader();
                    string suffix = null;
                    string pKey = null;
                    Object xsuffix = new Object();
                    Object ypKey = new Object();
                    while (sqlReader.Read())
                    {
                        ypKey = sqlReader.IsDBNull(sqlReader.GetOrdinal("PrimaryNum"))
                            ? String.Empty
                            : sqlReader.GetValue(sqlReader.GetOrdinal("PrimaryNum"));
                        xsuffix = sqlReader.IsDBNull(sqlReader.GetOrdinal("Suffix"))
                            ? String.Empty
                            : sqlReader.GetValue(sqlReader.GetOrdinal("Suffix"));
                        suffix = xsuffix.ToString();
                        pKey = ypKey.ToString();
                    }
                    sqlReader.Close();
                    byte[] salt = Encoding.ASCII.GetBytes(suffix);
                    FileStream fsInput = new FileStream(sInputFilename,
                          FileMode.Open,
                          FileAccess.Read);
                    byte[] bytearrayinput = new byte[fsInput.Length];
                    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
                    fsInput.Close();
                    FileStream fsEncrypted = new FileStream(sOutputFilename,
                       FileMode.Create,
                       FileAccess.Write);
                    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(pKey, salt);
                    DES.Key = deriveBytes.GetBytes(8);
                    DES.Mode = CipherMode.ECB;
                    DES.Padding = PaddingMode.PKCS7;
                    ICryptoTransform desencrypt = DES.CreateEncryptor();
                    CryptoStream cryptostream = new CryptoStream(fsEncrypted,
                       desencrypt,
                       CryptoStreamMode.Write);

                    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
                    cryptostream.FlushFinalBlock();
                    cryptostream.Close();
                    fsEncrypted.Close();
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                    if (rdr != null)
                    {
                        rdr.Close();
                    }
                }
            }
        }
What could be wrong? i tried different padding mode already. No luck :(
Posted
Comments
[no name] 7-Jul-14 14:07pm    
so what is the exception
gkaila 7-Jul-14 14:33pm    
There is no exception while encryption. but the code is appending some junk characters at the end of the text files. While decryption, it says bad data. if you want i can post my decryption algo as well. Thanks
[no name] 7-Jul-14 14:38pm    
before encryption make it Trim() then do it otherwise it may decryption problem
gkaila 7-Jul-14 15:52pm    
its not just a string.

1 solution

Padding is part of Block cipher implementation.

Refer to
http://msdn.microsoft.com/en-us/library/system.security.cryptography.paddingmode(v=vs.110).aspx[^]

If you are using 8 block cipher,
If you want to encrypt 9 bytes data
FF FF FF FF FF FF Ff Ff FF

Using PaddingMode.ANSIX923
7 bytes will be added so that we have whole number of blocks, ie 2 blocks of 8 bytes

The blocks would be
FF FF FF FF FF Ff Ff Ff FF 00 00 00 00 00 00 07

The right bytes of the appended bytes in the padded block indicates how many byte in the blocks are unused. This will allow such unused padding bytes to be remove in the decryption process.

If you examine the sample in
http://msdn.microsoft.com/en-us/library/0dh224hh(v=vs.110).aspx[^]

the data is "Here is some data to encrypt." , 29 bytes

It gets encrypted to file that has a length of 32 bytes

But, when you decrypts the file, you get back the 29 bytes data.

You may also want to refer to a recent CP article
Swanky encryption/decryption in C#[^]

You will note that the implmentation save encrypted data to file, but then read out the encrypted data to buffer, decrypt to buffer and then save the decrypted data back to file. Note that the saved decrypted file is the same length as the original file. But the encrypted file is always slightly larger ( file length is a multiple of block size ).
 
Share this answer
 
v2

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