Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to encrypt/Decrypt .xlsx/.doc files with C#
    text
    copied!<p>I'm writing an application to Encrtpt/Decrypt files and using <a href="http://support.microsoft.com/kb/307010" rel="nofollow">DESCryptoServiceProvider</a> for this purpose. This seems to work for text files but when I use the same application for .xlsx file, the resulting encrypted file and the decrypted file get corrupted and I'm not able to open that any more. is there any way I can encryt / decrypt different kinds of file like .doc..xls etc.</p> <p>update : added code for encryption/decryption</p> <pre><code>public static void EncryptFile(string filepath,string fileOutput, string key) { FileStream fsInput = new FileStream(filepath, FileMode.Open, FileAccess.Read); FileStream fsEncrypted = new FileStream(fileOutput, FileMode.Create, FileAccess.Write); DESCryptoServiceProvider DESc = new DESCryptoServiceProvider(); DESc.Key = ASCIIEncoding.ASCII.GetBytes(key); DESc.IV = ASCIIEncoding.ASCII.GetBytes(key); ICryptoTransform desEncrypt = DESc.CreateEncryptor(); CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desEncrypt, CryptoStreamMode.Write); byte[] byteArrayInput = new byte[fsInput.Length - 1]; fsInput.Read(byteArrayInput, 0, byteArrayInput.Length); cryptoStream.Write(byteArrayInput, 0, byteArrayInput.Length); cryptoStream.Close(); fsInput.Close(); fsEncrypted.Close(); } public static void DecryptFile(string filepath, string fileOutput, string key) { DESCryptoServiceProvider DESc = new DESCryptoServiceProvider(); DESc.Key = ASCIIEncoding.ASCII.GetBytes(key); DESc.IV = ASCIIEncoding.ASCII.GetBytes(key); FileStream fsread = new FileStream(filepath, FileMode.Open, FileAccess.Read); ICryptoTransform desDecrypt = DESc.CreateDecryptor(); CryptoStream cryptoStreamDcr = new CryptoStream(fsread, desDecrypt, CryptoStreamMode.Read); StreamWriter fsDecrypted = new StreamWriter(fileOutput); fsDecrypted.Write(new StreamReader(cryptoStreamDcr).ReadToEnd()); fsDecrypted.Flush(); fsDecrypted.Close(); } static void Main(string[] args) { EncryptFile(@"C:\test1.xlsx", @"c:\test2.xlsx", "ABCDEFGH"); DecryptFile(@"C:\test2.xlsx", @"c:\test3.xlsx", "ABCDEFGH"); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload