|
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
|
|
|
|
|
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
|
|
|
|
|
Checkout the MemoryStream class from System.IO.
---------------------------
Hmmm... what's a signature?
|
|
|
|
|
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
|
|
|
|
|
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?
|
|
|
|
|
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
|
|
|
|
|
"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?
|
|
|
|
|
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.
|
|
|
|
|
I really liked this. It even works with binary files (ie: Word documents) they won't be corrupted afterwards.
Thanks
Josef
|
|
|
|
|
Hello,
I am searching for an php decryption function to decrypt the files that are encrypted with the program of this article ?
|
|
|
|
|
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.
|
|
|
|
|
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!!
|
|
|
|
|
Wrap your code in a Try/Catch block:
try<br />
{<br />
}<br />
catch(CryptoHelpException che)<br />
{<br />
}
---------------------------
Hmmm... what's a signature?
|
|
|
|
|
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)
{
}
}
|
|
|
|
|
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?
|
|
|
|
|
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();
}
|
|
|
|
|
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
|
|
|
|
|
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?
|
|
|
|
|
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
|
|
|
|
|
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?
|
|
|
|
|
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
|
|
|
|
|
First to Nathan, MANY thanks for contributing your code to the .Net developer community. You've saved me hours of work.
I am currently working on a project that needs to work with encrypted xml files. For security reasons, I didn't want to write out to a temporary decrypted file, therefore I modified Nathan's Decrypt method to return a string. Here is the result:
public static string DecryptFile(string inFile, string password)
{
StringBuilder sb = new StringBuilder();
// create and open the file streams
using(FileStream fin = File.OpenRead(inFile))
{
long lSize = -1;
int read = -1;
int value = 32;
int outValue = 0;
byte[] bytes = new byte[BUFFER_SIZE];
byte[] IV = new byte[16];
byte[] salt = new byte[16];
fin.Read(IV,0,16);
fin.Read(salt,0,16);
SymmetricAlgorithm sma;
HashAlgorithm hasher = SHA256.Create();
sma = CryptoHelp.CreateRijndael(password,salt);
sma.IV = IV;
using(CryptoStream cin = new CryptoStream(fin,sma.CreateDecryptor(),CryptoStreamMode.Read), chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
{
BinaryReader br;
ulong tag;
br = new BinaryReader(cin);
lSize = br.ReadInt64();
if((tag = br.ReadUInt64()) != FC_TAG)
{
throw new CryptoHelpException("File Corrupted!");
}
ASCIIEncoding enc = new System.Text.ASCIIEncoding();
long numReads = lSize / BUFFER_SIZE;
long slack = (long)lSize % BUFFER_SIZE;
for( int i = 0; i < numReads; ++i )
{
string s;
read = cin.Read( bytes, 0, bytes.Length );
s = enc.GetString( bytes, 0, read );
sb.Append( s );
chash.Write( bytes, 0, read );
value += read;
outValue += read;
}
// now read the slack
if( slack > 0 )
{
string s;
read = cin.Read(bytes,0,(int)slack);
s = enc.GetString( bytes, 0, read );
sb.Append( s );
chash.Write(bytes,0,read);
value += read;
outValue += read;
}
// flush and close the hashing stream
chash.Flush();
chash.Close();
byte[] curHash = hasher.Hash;
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash,0,oldHash.Length);
if((oldHash.Length != read) || (CheckByteArrays(oldHash, curHash)) == false )
{
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!");
}
return sb.ToString();
}
}
|
|
|
|
|
Hello!
I tried to path the encrypted file within Socket Connection. The Decryption proccess didn't show any problems, but after creating I couldn't open the decrypted file (that was originally in .jpg format).
What could be a reson?
Eli Kremer
|
|
|
|
|
Eli,
I am not sure I understand what you mean. Did you encrypt the file into another file and then try to send that file across a socket connection? If your socket connection is working for every other type of file you are sending that would be weird. I would need to see code to help.
Later,
Nathan
---------------------------
Hmmm... what's a signature?
|
|
|
|
|
Nathan,Thanks for your answer,
Yes, I encrypted file into another, and sent it across the socket connection:
Does the file corrupts when I open it for writing into networkstream on Server side and reading on client side? What is the simple way to avoid this ?
RECEIVING (Client Side):
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
private void GetFile(string FileName, Socket sock )
{
string FileEncryptedName;
NetworkStream nfs = null;
FileStream fout=null;
receiveDone.WaitOne(5000,false);
FileEncryptedName = FileName+".fcfe";
try
{
FileInfo fi = new FileInfo(PathToPlaceFiles+ "/" + FileEncryptedName);
fout = new FileStream(fi.FullName , FileMode.Create, FileAccess.Write) ;
nfs = new NetworkStream(sock) ;
}
catch (Exception ex)
{
this.clientLog.Text += " There may be problems with requested file" ;
}
int i=1; // Number of bytes to get from buffer in each cycle
double duration=0; // transfer speed
int rby=0 ; // Total number of bytes
byte[] buffer;
try
{
do
{
CurrentTime = DateTime.Now;
TimeSpan timeLeft = (CurrentTime-StartTime );
labelDurationDetails.Text = timeLeft.TotalSeconds.ToString("F3") ;
buffer = new byte[1024] ;
//Read from the Network Stream
if(nfs.CanRead)
i = nfs.Read(buffer,0,buffer.Length) ;
if(i>0)
{
fout.Write(buffer,0,i) ;
rby=rby+i ;
if(CurrentTime.Second > 0)
duration = rby/CurrentTime.Second;
duration/=1024;
pBar.PerformStep();
labelRateDetails.Text = duration.ToString("F3");
this.clientLog.Text += "";
}
}while( rby<this.pbar.maximum);
="" }catch(exception="" ed)
="" {
="" messagebox.show("problem="" in="" file="" accept"+ed.message);
="" }
="" try
="" filename+=".fcfd" ;
="" fileinfo="" finput="new" fileinfo(pathtoplacefiles+="" "="" +="" fileencryptedname);
fileinfo="" foutput="new" filename);
=""
cryptoprogresscallback="" cb="new" cryptoprogresscallback(this.progresscallbackdecrypt);
cryptoprogresscallback(this.progresscallbackdecrypt);
cryptohelp.decryptfile(finput.fullname,foutput.fullname,"1",cb);
="" }
catch="" (exception="" ed)
{
="" messagebox.show("error="" decryption"+ed.message);
}
="" sending="" (server="" side)
=""
public="" void="" readcallback(iasyncresult="" ar)=""
{="" i="" perform="" some="" validation="" –="" xml="" “dialog”="" between="" client="" and="" server="" by="" “3-="" way="" handshake”="" that="" the="" needed="" exists="" before="" file
="" stateobject="" state="(StateObject)" ar.asyncstate;
="" socket="" handler="state.workSocket;
" int="" bytesread="handler.EndReceive(ar);
" string="" content="Encoding.Unicode.GetString(state.buffer,0,bytesRead);
" getting="" name="" of="" requested="" if="" (content.indexof("<="">") > -1)
{
//Getting the source file
FileInfo file_info=LocateFile(content,1);
CryptoProgressCallBack cb = new
CryptoProgressCallBack(this.ProgressCallBackEncrypt);
CryptoHelp.EncryptFile(file_info.FullName,file_info.FullName+".fcfe","1",cb);
//Getting the encrypted file
file_info = LocateFile(content,2);
if( FileMessage(content) && file_info!=null )
{
SendFile(file_info,handler);
}
}
private FileInfo LocateFile(string content,int time)
{
//………………………
else if(time==2) {
if(file.Name.Equals(doc.SelectSingleNode("//FileName").InnerText+".fcfe" ))
return file;
}
//………………………….
}
private void SendFile(FileInfo file_info, Socket handler)
{
// Writes file_info into Network Stream
}
Eli
|
|
|
|
|