tags:

views:

438

answers:

4

Hi,

I am using 'RijndaelManaged' and 'CryptoStream' classes in C# to encrypt files. Before encrypting the files, i want to check whether the file is already encrypted or not.

I tried using File.GetAttributes() method to check for Encryption but it is not working.

I need some tips on ways i can check whether the file is already Encrypted or not.

A: 

If the file is encrypted it will appear as a stream of random bytes. You can:

  • Attempt to open the file and/or confirm that it is of the expected format (JPG, ZIP, whatever). If the file matches a known format then you know it is decrypted.

  • Attempt to decrypt the file if you have the key, then repeat the previous step. If it now matches a known format then you know it is (was?) encrypted.

Justin Ethier
Define what you mean by "if decryption works". The only way to check is to have extra information about the plaintext, perhaps by having an extra field in the file format.
GregS
Good point; I just updated the answer.
Justin Ethier
+1  A: 

You have to inspect the file and look for structures, or byte strings that would not be there if the file is encrypted. You would need a separate test for every type of file you are dealing with.

mikerobi
+2  A: 

Without any sort of custom headers, the only way to be absolutely sure the file is encrypted is to attempt to decrypt it.

If you attempt to compress the file and it gets smaller, then it is extremely unlikely to be encrypted. If there is a non-uniform distribution of byte values (including plain text!), then it is unlikely to be encrypted.

Those heuristics depend on proper execution of the encryption. If AES is applied to a file one block at time, then patters can emerge in the result, but since you are using CryptoStream this shouldn't be a problem.

If your own code will always be used to encrypt and decrypt the files, then you should consider adding a custom header that indicates it is an encrypted file.

Jeffrey L Whitledge
Adding a custom header seems like a good idea :) will give it a try
Mako
+3  A: 

Suppose I have a file F containing ciphertext X, which is the enciphering of plaintext Y with key Z.

I wish to ensure that the plaintext Y can only be determined by someone who possesses both key Z and key Q. (I can think of a number of reasons why I might wish to do this.)

I therefore wish to encrypt the already-encrypted file with key Q.

You're telling me that your system wishes to detect that F is already encrypted, and then refuse to encrypt it with key Q?

That seems like a bad idea. I might want to encrypt the file with key Q irrespective of whether it is already encrypted with key Z or not.

Eric Lippert
I agree with you that multiple Encryption is a good idea. But i just wanted to see if there is any way through which we can find whether a file has been encrypted or not.
Mako