Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - FileEncryptDecrypt.jpg

Introduction

This article is an expansion on a few of the articles here on CodeProject. I noticed that there are a lot of articles and posts dealing with Cryptography in the .NET Framework. These were all well and good. They got me started. Then, as I was progressing and using the System.Security.Cryptography namespace, I noticed that if the file was the right size and padded correctly, even using a bad password would output a file. This was not acceptable to me. So, I set out to write a class that would allow me to encrypt and then decrypt/verify that the contents had been written correctly.

Background

These articles started me down the road of .NET Cryptography:

Since none of these verified the output, I wrote a class to fix this.

The Code

The EncryptFile method:

/// <summary>

/// This takes an input file and encrypts it into the output file>

/// </summary>

/// <param name="inFile">the file to encrypt</param>

/// <param name="outFile">the file to write the encrypted data to</param>

/// <param name="password">the password for use as the key</param>

/// <param name="callback">the method to call to notify of progress</param>

public static void EncryptFile(string inFile, string outFile, 
                    string password, CryptoProgressCallBack callback)
{
    using(FileStream fin = File.OpenRead(inFile),
          fout = File.OpenWrite(outFile))
    {
        long lSize = fin.Length; // the size of the input file for storing

        int size = (int)lSize;  // the size of the input file for progress

        byte[] bytes = new byte; // the buffer

        int read = -1; // the amount of bytes read from the input file

        int value = 0; // the amount overall read from the input file for progress


        // generate IV and Salt

        byte[] IV = GenerateRandomBytes(16);
        byte[] salt = GenerateRandomBytes(16);

        // create the crypting object

        SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
        sma.IV = IV;            

        // write the IV and salt to the beginning of the file

        fout.Write(IV,0,IV.Length);
        fout.Write(salt,0,salt.Length);

        // create the hashing and crypto streams

        HashAlgorithm hasher = SHA256.Create();
        using(CryptoStream cout = new CryptoStream(fout,sma.CreateEncryptor(),
            CryptoStreamMode.Write),
              chash = new CryptoStream(Stream.Null,hasher,
                CryptoStreamMode.Write))
        {
            // write the size of the file to the output file

            BinaryWriter bw = new BinaryWriter(cout);
            bw.Write(lSize);

            // write the file cryptor tag to the file

            bw.Write(FC_TAG);

            // read and the write the bytes to the crypto stream 

            // in BUFFER_SIZEd chunks

            while( (read = fin.Read(bytes,0,bytes.Length)) != 0 )
            {
                cout.Write(bytes,0,read);
                chash.Write(bytes,0,read);    
                value += read;
                callback(0,size,value);
            }
            // flush and close the hashing object

            chash.Flush();
            chash.Close();

            // read the hash

            byte[] hash = hasher.Hash;

            // write the hash to the end of the file

            cout.Write(hash,0,hash.Length);

            // flush and close the cryptostream

            cout.Flush();
            cout.Close();
        }
    }
}

What is interesting about this method and makes it different than the other articles' methods, is the fact that I write out the IV and Salt to the beginning of the output file. This adds a little more security to the file. For more information on these terms, check out Ritter's Crypto Glossary. Then after those two arrays are written, I encrypt and write the file size and a special tag (arbitrarily generated by me). These allow for some simple verifications of the file. After this, I do the encryption of the file, while hashing the data. Once the input file is completely encrypted, I encrypt the hash and write it out. By putting the hash at the end, I am able to verify the contents after decryption.

The DecryptFile method:

/// <summary>

/// takes an input file and decrypts it to the output file

/// </summary>

/// <param name="inFile">the file to decrypt</param>

/// <param name="outFile">the to write the decrypted data to</param>

/// <param name="password">the password used as the key</param>

/// <param name="callback">the method to call to notify of progress</param>

public static void DecryptFile(string inFile, string outFile,
            string password, CryptoProgressCallBack callback)
{
    // NOTE:  The encrypting algo was so much easier...


    // create and open the file streams

    using(FileStream fin = File.OpenRead(inFile),
              fout = File.OpenWrite(outFile))
    {
        // the size of the file for progress notification

        int size = (int)fin.Length;
        // byte buffer

        byte[] bytes = new byte;
        int read = -1; // the amount of bytes read from the stream

        int value = 0;
        int outValue = 0; // the amount of bytes written out


        // read off the IV and Salt

        byte[] IV = new byte[16];
        fin.Read(IV,0,16);
        byte[] salt = new byte[16];
        fin.Read(salt,0,16);

        // create the crypting stream

        SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password,salt);
        sma.IV = IV;

        value = 32; // the value for the progress

        long lSize = -1; // the size stored in the input stream


        // create the hashing object, so that we can verify the file

        HashAlgorithm hasher = SHA256.Create();

        // create the cryptostreams that will process the file

        using(CryptoStream cin = new CryptoStream(fin,sma.CreateDecryptor(),
                CryptoStreamMode.Read),
                  chash = new CryptoStream(Stream.Null,hasher,
                    CryptoStreamMode.Write))
        {
            // read size from file

            BinaryReader br = new BinaryReader(cin);
            lSize = br.ReadInt64();
            ulong tag = br.ReadUInt64();

            if(FC_TAG != tag)
                throw new CryptoHelpException("File Corrupted!");

            //determine number of reads to process on the file

            long numReads = lSize / BUFFER_SIZE;

            // determine what is left of the file, after numReads

            long slack = (long)lSize % BUFFER_SIZE;

            // read the buffer_sized chunks

            for(int i = 0; i < numReads; ++i)
            {
                read = cin.Read(bytes,0,bytes.Length);
                fout.Write(bytes,0,read);
                    chash.Write(bytes,0,read);
                value += read;
                outValue += read;
                callback(0,size,value);
            }

            // now read the slack

            if(slack > 0)
            {
                read = cin.Read(bytes,0,(int)slack);
                fout.Write(bytes,0,read);
                chash.Write(bytes,0,read);
                value += read;
                outValue += read;
                callback(0,size,value);
            }
            // flush and close the hashing stream

            chash.Flush();
            chash.Close();

            // flush and close the output file

            fout.Flush();
            fout.Close();

            // read the current hash value

            byte[] curHash = hasher.Hash;

            // get and compare the current and old hash values

            byte[] oldHash = new byte[hasher.HashSize / 8];
            read = cin.Read(oldHash,0,oldHash.Length);
            if((oldHash.Length != read) || (!CheckByteArrays(oldHash,curHash)))
                throw new CryptoHelpException("File Corrupted!");
        }
        
        // make sure the written and stored size are equal

        if(outValue != lSize)
            throw new CryptoHelpException("File Sizes don't match!");
    }
}

During decryption, I reverse the actions of encryption. First, I read both the IV and Salt from the file. I use these to create the SymmetricAlgorithm. Second, I decrypt and read the file size and the tag. This is the first step in verification--if the tag is equal to the const tag in the class, I know the file is so far not corrupted. Now comes the decryption of the file data. This took a little work, because normally I would just keep reading from the file until I could not read anymore. But I put the hash at the end. So, I had to figure out how to read only the amount of data in the file size. I did this by using a little math:

Number of Reads = The File Size / The Buffer Size
Left Over Bytes To Read = The File Size modulo The Buffer Size
NOTE: Both of these are integer math

Now, I use a for loop for reading most of the data, and then read the left over bytes.

During these reads, I hashed the decrypted data.

Then I read off the hash that was written last and compared it to the newly created hash. If they were equal, the file was not corrupted and the correct password was used to decrypt the file. If not, the algorithm has caught the error.

Using the code

This code is pretty easy to use:

using nb;
public class TestClass
{
    string myPassword = "TESTING!@#_123__";
    string myPlainFile = "test.txt";
    string myEncryptedFile = "test.encrypted";
    string myDecryptedFile = "test.decrypted";

    private static void Callback(int min, int max, int value)
    {
        // do something with progress (progress bar or just ignore it)

    }

    [STAThread]
    static void Main()
    {
        CryptoProgressCallBack cb = new CryptoProgressCallBack(Callback);
        //Do the Encryption

        CryptoHelp.EncryptFile(myPlainFile, myEncryptedFile, myPassword, cb);
        //Do the decryption

        CryptoHelp.DecryptFile(myEncryptedFile,myDecryptedFile, myPassword, cb);
    }
}

Points of Interest

The things I learned were how to use the .NET Framework's hashing/crypting algorithms. These classes when used in conjunction allow for some pretty powerful data security and data verification. I was able to verify the files data with a minimum overhead.

I hope that this is a help to others who need to add some security to their applications.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalcan i use this in a Web Application?
suresh_kumar_s
20:21 7 Dec '09  
Hi can i use this in a Web Application?
Thanks
Surez

sureshkumaran

GeneralRe: can i use this in a Web Application?
Nathan Blomquist
12:59 12 Dec '09  
Are you asking if the code will work in a web application? Or are you asking permission?

It should work fine in a web application. Remember, this is just demo code; no guarantee that it won't format your hard drive Laugh .

---------------------------
Hmmm... what's a signature?

GeneralRe: can i use this in a Web Application?
suresh_kumar_s
19:15 13 Dec '09  
mmm...gud reply(!!??) Laugh

sureshkumaran

GeneralSome small bugfixes
Kim Togo
5:28 15 Oct '09  
Hi

Great encryption class!

I got some small bugfixes for the class.

Under EncryptFile in CryptoHelp.cs

Change int size to long size and int value to long value.

Under DecryptFile in CryptoHelp.cs

Change int size to long size, int value to long value and int outValue to long outValue.

And of course change the delegate void CryptoProgressCallBack to long.

This will support encryption and decryption of files larger than 4GB.
QuestionI need help about Encryp and DesEncryp Tiff Files
Diego Maciado
8:44 14 May '09  
Thanks for you code. It´s really good.

I have a problem and I can´t find the solution. Can you help me?

I used the method EncryptFile with a xxx.tiff file and work OK.
Then I used the method DecryptFile with a xxx.tiff.enc file and work OK.

Problem:

When I used the file: tiff´s DecryptFile and try to join to other tiff files (I try to add more tiff to a document to join in a only one m-tiff file), Then I used the method EncryptFile and apparently work OK.

But

When I used the method DecryptFile say that the: File Corrupted!

if(FC_TAG != tag)
throw new CryptoHelpException("File Corrupted!");

the FC_TAG = 18158797384510146255 ulong
the tag = 17843326550202218999 ulong

And I used the same method and TAG flag:
private const ulong FC_TAG = 0xFC010203040506CF; same in decimal 18158797384510146255

Thank for your help

Diego Maciado
GeneralChecking integrity in memory
Luke DeStevens
13:51 9 Jan '09  
Let's assume that I don't want to write a decrypted file to disk but instead want to keep the decrypted data in memory (say, in a Stream object). Do you have any ideas on how to check for integrity in that case?

Luke
GeneralRe: Checking integrity in memory
Nathan Blomquist
18:54 9 Jan '09  
Checkout the MemoryStream class from System.IO.

---------------------------
Hmmm... what's a signature?

GeneralHow does saving the IV and salt make it more secure?
Luke DeStevens
7:54 9 Jan '09  
I'm having a bit of a problem understanding the reasoning behind saving the IV and the salt to the file. You state that saving the IV and the salt actually makes the file MORE secure. How is that so if anyone can simply open and read IV and salt from the file?

The only benefit I see that this system allows is having a different IV and salt for each file, but both are easily visible at the front of the file. Why not instead use a static IV and salt hidden in the software's obfuscated source code (or someplace else more easily obfuscated)?

The way I understand it, the salt is supposed to make a dictionary attack thru the password worthless; a hacker would need to try every possible password modified by every possible salt. If the salt is known, the problem is reduced to a simple dictionary attack.

I realize that either approach is vulnerable to dictionary attack if the hacker has the software that encrypted the file, but in the case where the attacker only has the file, it seems that encoding the salt and IV within the file would be LESS secure.

Am I missing something?

Luke
GeneralRe: How does saving the IV and salt make it more secure?
Nathan Blomquist
12:14 9 Jan '09  
The salt and IV help to get rid of STATIC dictionary attacks.

If the salt and IV are kept in the software, the attacker can generate a dictionary of passwords that will be usable against ALL files encrypted via this software. Obfuscating the software does nothing to help with this. Given enough want and incentive a cracker can get the salt and IV out of the code.

But since the salt and the IV are stored in the file and are different for each file (and different for the same plain text encrypted at different times) the attacker would need to generate a dictionary specifically based on each file.

In the first instance, all files become compromised. In the second instance only one file becomes compromised.

Essentially storing the salt and IV in the code, negates what they were meant to do.

Does this make sense?

---------------------------
Hmmm... what's a signature?

GeneralRe: How does saving the IV and salt make it more secure?
Luke DeStevens
13:47 9 Jan '09  
Good point. That makes excellent sense.

I'm thinking...could a third factor hidden in the code be hashed with the salt and/or IV contained within the file to produce the true IV and salt? An attacker would then need to crack the software as well as get the pre-IV and pre-salt from the file. I guess I'm talking about encrypting the IV and salt before putting it in the file, and placing THAT encryption key in obfuscated code.

Would that be worthwhile? How challenging is it to crack obfuscated code?

Luke
GeneralRe: How does saving the IV and salt make it more secure?
Nathan Blomquist
18:51 9 Jan '09  
"Cracking" the code is not hard even in obfuscated code. C# is easy, trivial, to decompile. Even if the variable names were shortened and the loops all messed up, it still wouldn't be hard. Especially for a motivated person. The same basically goes for any compiled language. People can extract this information from assembled binary files.

Also, since I am putting this code out into the world, obfuscation can't really help.

I suppose if you were to close source your application and NEVER EVER release it to anyone but yourself, that third option may give a minimal amount of extra security. But basically it is just making a second password. The moment you release the code or even a binary to anyone but yourself, the third option because void and useless.

With the code I wrote, I would hope that I did it in a standard enough way, that given this algorithm any other developer could en/decrypt compatibly, in any language.

---------------------------
Hmmm... what's a signature?

GeneralRe: How does saving the IV and salt make it more secure?
Cafechess
5:28 6 Mar '09  
Best is to not store anything but the encrypted file. The symmetric key should be sent separately of the file and it is generally a good practice to use X509 public and private key encryption of the symm.key/symm.iv pair. So if you were sending the file to me; encrypt the keys with my public key; send me the file; send me the encrypted keys; then only I can unencrypt the key/iv pair and finally the file.
GeneralNice work
Josef Meile
3:53 25 Jan '08  
I really liked this. It even works with binary files (ie: Word documents) they won't be corrupted afterwards.

Thanks
Josef
QuestionDecrypt in PHP
raymondk
6:51 21 Nov '07  
Hello,

I am searching for an php decryption function to decrypt the files that are encrypted with the program of this article ?

D'Oh!
NewsTwo other related encryption articles in CodeProject ...
Tony Selke
8:06 27 Sep '07  
You may also be interested in looking at the following, related Code Project articles:

Generic SymmetricAlgorithm Helper[^]
This is a generic helper class that exposes simplified Encrypt and Decrypt functionality for strings, byte arrays and streams for any SymmetricAlgorithm derivative (DES, RC2, Rijndael, TripleDES, etc.).

Making TripleDES Simple in VB.NET and C#[^]
This is a simple wrapper class that provides an easy interface for encrypting and decrypting byte arrays and strings using the 3DES algorithm.

QuestionWrong password
Istvn Pszota
10:05 9 Aug '07  
Hi!

First of all Thank you for this great article!

I have a problem, and hope you can help! I dont know how to check, if the entered password for the decryption is right or wrong?

I realized if the password is wrong an exception is thrown:
CryptoHelpException("File Corrupted!").

If im right how can i catch this exception from my code??
If im wrong what is the other way?

Thank you!!




AnswerRe: Wrong password
Nathan Blomquist
8:36 26 Sep '07  
Wrap your code in a Try/Catch block:

try {
// do something with the cryptohelp classes
}
catch(CryptoHelpException che)
{
// do something with the exception
}


---------------------------
Hmmm... what's a signature?

GeneralPadding is invalid & can not be removed
pomeydey
23:07 5 Jul '07  
Hi,

Please help me on this padding problem. I m facing problem while decrypt of the file after the closing the curly barces of

"using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))"

It works fine when we add something in the encrypted file, but problem arises if i delete something from the encrypted file & tried to decrypt the file again.

Regards
Pomey


public static void DecryptFileOnly(string filename, string filemask, string key, string fileExt)
{
try{
int index;
string outFile;
index = filename.LastIndexOf(fileExt);
outFile = filename.Substring(0, index);
//outFile = filename.Substring(0, filename.LastIndexOf(".")) + ".xml";
//*************************************************************
// create and open the file streams
using (FileStream fin = File.OpenRead(filename), fout = File.OpenWrite(outFile))
{
int size = (int)fin.Length; // the size of the file for progress notification
byte[] bytes = new byte[BUFFER_SIZE]; // byte buffer
int read = -1; // the amount of bytes read from the stream

// read off the IV and Salt
byte[] IV = new byte[16];
fin.Read(IV, 0, 16);
byte[] salt = new byte[16];
fin.Read(salt, 0, 16);

// create the crypting stream
SymmetricAlgorithm sma = CreateAlgo(key, salt);
sma.IV = IV;

long lSize = -1; // the size stored in the input stream

// create the hashing object, so that we can verify the file
HashAlgorithm hasher = SHA256.Create();

// create the cryptostreams that will process the file
using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
// read size from file
BinaryReader br = new BinaryReader(cin);
lSize = br.ReadInt64();
ulong tag = br.ReadUInt64();

if (FC_TAG != tag)
throw new EncryptDecryptHelpException("File Corrupted!");

//determine number of reads to process on the file
long numReads = lSize / BUFFER_SIZE;

// determine what is left of the file, after numReads
long slack = (long)lSize % BUFFER_SIZE;

// read the buffer_sized chunks
for (int i = 0; i < numReads; ++i)
{
read = cin.Read(bytes, 0, bytes.Length);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);

}

// now read the slack
if (slack > 0)
{
read = cin.Read(bytes, 0, (int)slack);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);

}

// flush and close the hashing stream
chash.Flush();
chash.Close();

// flush and close the output file
fout.Flush();
fout.Close();

// read the current hash value
byte[] curHash = hasher.Hash;

// get and compare the current and old hash values
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash, 0, oldHash.Length);


}

}

//**************************************
//File.Delete(filename);
}

catch(Exception ex)
{

}

}

GeneralPadding is invalid and cannot be removed
Maranello1983
14:48 9 Feb '07  
I get this error when i decrypt. I use this algorithm on xml files, this happens when i remove a node from the xml file. Any ideas?
QuestionPadding error using other hashing algorithm
mschu82
19:38 20 Dec '06  
I am trying to build a cryptography program using HMACSHA256 as the verification technique. I edited the code to use HMACSHA256 instead as well as C++. Upon decryption using the incorrect password, I will encounter this error.


An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll

Additional information: Padding is invalid and cannot be removed.


Below is my code and the error occurs at this line
while ( (bytesInCurrentBlock = cin->Read(buffer, 0, buffer->Length)) != 0 )
in the DecryptFile function. I would be grateful if someone could point out my mistake here.

PS: I am suppose to be expecting the hmacsha256 mismatch error to throw instead



void CryptoData::EncryptFile(String^ inFile, String^ outFile, String^ password, int keySize,
                                          CryptoProgressCallBack^ callback)
{
      FileStream^ fin = gcnew FileStream(inFile, FileMode::Open, FileAccess::Read);
      FileStream^ fout = gcnew FileStream(outFile, FileMode::OpenOrCreate, FileAccess::Write);

      fout->SetLength(0);

      array<Byte>^ buffer = gcnew array<Byte>(BUFFER_SIZE);
      int bytesInCurrentBlock;
      long long bytesProcessed = 0;                             
      long long fileLength = fin->Length;
      long progress;

      // generate IV and Salt
      array<Byte>^ IV = GenerateRandomBytes(16);
      array<Byte>^ salt = GenerateRandomBytes(16);

      // create the crypting object
      SymmetricAlgorithm^ sma = CreateRijndaelManaged(password, keySize, IV, salt);
     
      // write the IV and salt to the beginning of the file
      fout->Write(IV, 0, IV->Length);
      fout->Write(salt, 0, salt->Length);

      // Initialize the keyed hash object.
      HashAlgorithm^ hmacsha256 = gcnew HMACSHA256(sma->Key);
      // Compute the hash of the input file.
      array<Byte>^ hashValue = hmacsha256->ComputeHash(fin);
      // Reset fin to the beginning of the file.
      fin->Position = 0;
      // Write the computed hash value to the output file.
      fout->Write(hashValue, 0, hashValue->Length);

      // create the cryptostream
      CryptoStream^ cout = gcnew CryptoStream(fout, sma->CreateEncryptor(), CryptoStreamMode::Write);

      // read and write the bytes to the crypto stream in BUFFER_SIZE chunks
      while ( (bytesInCurrentBlock = fin->Read(buffer, 0, buffer->Length)) != 0 )
      {
            cout->Write(buffer, 0, bytesInCurrentBlock);
            bytesProcessed += bytesInCurrentBlock;
            progress = (int)((bytesProcessed / fileLength) * 100);
            callback(0, 100, progress);
      }

      // clear the hashing object
      hmacsha256->Clear();

      // flush and close the cryptostream
      cout->Flush();
      cout->Close();

      // close the input file
      fin->Close();
}

void CryptoData::DecryptFile(String^ inFile, String^ outFile, String^ password, int keySize,
                                          CryptoProgressCallBack^ callback)
{
      FileStream^ fin = gcnew FileStream(inFile, FileMode::Open, FileAccess::Read);
      FileStream^ fout = gcnew FileStream(outFile, FileMode::OpenOrCreate, FileAccess::Write);

      fout->SetLength(0);

      array<Byte>^ buffer = gcnew array<Byte>(BUFFER_SIZE);
      int bytesInCurrentBlock;
      long long bytesProcessed = 0;
      long long fileLength = fin->Length;
      int progress;

      // read the IV and Salt
      array<Byte>^ IV = gcnew array<Byte>(16);
      fin->Read(IV, 0, 16);
      array<Byte>^ salt = gcnew array<Byte>(16);
      fin->Read(salt, 0, 16);

      // create the crypting object
      SymmetricAlgorithm^ sma = CreateRijndaelManaged(password, keySize, IV, salt);

      // Initialize the keyed hash object.
      HashAlgorithm^ hmacsha256 = gcnew HMACSHA256(sma->Key);
      // Create an array to hold the keyed hash value read from the file.
      array<Byte>^ storedHash = gcnew array<Byte>(hmacsha256->HashSize / 8);
      // Read in the storedHash.
      fin->Read(storedHash, 0, storedHash->Length);
      bytesProcessed = 64;

      // create the cryptostream that will process the file
      CryptoStream^ cin = gcnew CryptoStream(fin, sma->CreateDecryptor(), CryptoStreamMode::Read);

      // read the BUFFER_SIZE chunks
while ( (bytesInCurrentBlock = cin->Read(buffer, 0, buffer->Length)) != 0 )
      {
            fout->Write(buffer, 0, bytesInCurrentBlock);
            bytesProcessed += bytesInCurrentBlock;
            progress = (int)((bytesProcessed / fileLength) * 100);
            callback(0, 100, progress);
      }

      // Reposition the file to compute the hash of the output file.
      fout->Position = 0;
     
      array<Byte>^ computedHash = hmacsha256->ComputeHash(fout);

      if (!ByteArrayEqual(computedHash, storedHash)) {
            throw gcnew CryptoDataException("hmacsha256 mismatch");
      }
     
      // flush and close the cryptostream
      cin->Flush();
      cin->Close();

      // close the output file
      fout->Close();
}
GeneralGetting error while decrypting a file
chandu.sanka
0:10 30 Nov '06  
Hi

I am getting error while calling the decrypting function in a loop.The error is "Padding is invalid and cannot be removed".


I am getting this exception at this line

if (FC_TAG != tag)
throw new CryptoHelpException("File Corrupted!");

Thanks in Advance

Regards
Chandu.Sanka
GeneralRe: Getting error while decrypting a file
Nathan Blomquist
5:54 30 Nov '06  
Hello,

I think I need more information on what you are trying to do. The methods that I created do input file to output file all in one step. This for both variants--encrypt and decrypt.

Are you encrypting more than one file in a loop? Are you then trying to decrypt those newly encrypted files?

Can you post a very simple example code that shows your problem?

Thank you,
Nathan

---------------------------
Hmmm... what's a signature?

GeneralRe: Getting error while decrypting a file
chandu.sanka
4:25 7 Dec '06  
Hi

Actually while I am using this code,in some cases only I am getting exception at the following code

if (FC_TAG != tag)
throw new CryptoHelpException("File Corrupted!");

I mean the values of FC_TAG and tag are generating different values and this is resulting in throwing an exception.

Almost in all the cases I am getting the value of FC_TAG is 18158797384510146255.

Can you please tell me what might be the problem and how to resolve it.

Thanks in Advance
Chandu.Sanka

GeneralRe: Getting error while decrypting a file
Nathan Blomquist
5:18 7 Dec '06  
chandu.sanka wrote:
Almost in all the cases I am getting the value of FC_TAG is 18158797384510146255.

Actually, I hope the FC_TAG == 18158797384510146255 ALL the time. If not your computer has more problems (like memory corruption or something). FC_TAG is defined in hexadecimal--not decimal. The number you stated is in decimal.

FC_TAG is a constant defined at the top of CryptoHelp class. This constant is used just as a verification that the file is being decrypted right and that this file was encrypted by the EncryptFile method.

If tag is coming back not equal to FC_TAG, then the file that you encrypted has become corrupt. I guess I would need an example file that encrypts and then fails to decrypt so that I could check my code for errors.

---------------------------
Hmmm... what's a signature?

GeneralRe: Getting error while decrypting a file
EmersioN
23:43 30 Dec '08  
Hi, Nathan Blomquist
Nice Article...
Even I am getting the same error "Invalid Padding..."
When i try to process bunch of files in loop
i.e.

for each(string filename in filenamesStringArray){

EncryptorDecryptor.CryptoHelp.EncryptFile(filename,encryptedfilename , "password",cb);
EncryptorDecryptor.CryptoHelp.DecryptFile(encryptedfilename, decryptedFileName, "password",cb);
}
i face the exception just after 2 or 3 files !

EmersioN


Last Updated 22 Oct 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010