C # Encryption and decryption file gadget implementation Code _c# tutorial

Source: Internet
Author: User
Tags array length exception handling flush hash int size rand
DEBUGLZQ on the Internet search related file encryption program, found that the basic is for "character creation", "text" encryption and decryption. For video files, pictures and other general files encryption and decryption procedures are few, so write down this article, to achieve a general file encryption of small tools.

The main function of the program is that the user selects the file to encrypt by the File selection box-Enter the password for encryption, select the encrypted file, and enter the password for decryption.

The main interface of the program is as follows:

The Click event handler for the three buttons is as follows:
Copy Code code as follows:

private void Btnselectfile_click (object sender, EventArgs e)
{
if (openfiledialog1.showdialog () = = System.Windows.Forms.DialogResult.OK)
{
Txtfilename.text = Openfiledialog1.filename;
}
}
private void Btnencryptfile_click (object sender, EventArgs e)
{
String Infile=txtfilename.text;
string outfile = InFile + ". Dat";
String Password=txtpassword.text;
DESFile.DESFileClass.EncryptFile (inFile, outfile, password)/encrypted file
Delete files before encryption
File.delete (InFile);
Txtfilename.text = string. Empty;
MessageBox.Show ("successful Encryption");
}
private void Btndecryptfile_click (object sender, EventArgs e)
{
string inFile = Txtfilename.text;
string outfile = Infile.substring (0,infile.length-4);
string password = txtPassword.Text;
DESFile.DESFileClass.DecryptFile (inFile, outfile, password);//Decrypt file
Delete a file before decryption
File.delete (InFile);
Txtfilename.text = string. Empty;
MessageBox.Show ("decryption successful");
}

Encrypted decryption Help file source code is as follows:
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Security.Cryptography;
Using System.IO;
Namespace Desfile
{
<summary>
Exception Handling Class
</summary>
public class Cryptohelpexception:applicationexception
{
Public cryptohelpexception (String msg): Base (msg) {}
}
<summary>
Crypthelp
</summary>
public class Desfileclass
{
Private Const ULONG Fc_tag = 0XFC010203040506CF;
Private Const INT BUFFER_SIZE = 128 * 1024;
<summary>
Verify that two byte arrays are the same
</summary>
<param name= "B1" >byte array </param>
<param name= "B2" >byte array </param>
<returns>true-Equal </returns>
private static bool Checkbytearrays (byte[] B1, byte[] B2)
{
if (B1. Length = = B2. Length)
{
for (int i = 0; I < B1. Length; ++i)
{
if (B1[i]!= b2[i])
return false;
}
return true;
}
return false;
}
<summary>
Create DEBUGLZQ, Http://www.cnblogs.com/DebugLZQ
</summary>
<param name= "password" > Password </param>
<param name= "Salt" ></param>
<returns> Encryption Object </returns>
private static SymmetricAlgorithm Createrijndael (string password, byte[] salt)
{
PasswordDeriveBytes pdb = new passwordderivebytes (password, salt, "SHA256", 1000);
SymmetricAlgorithm SMA = Rijndael.create ();
Sma. KeySize = 256;
Sma. Key = pdb. GetBytes (32);
Sma. Padding = PADDINGMODE.PKCS7;
return SMA;
}
<summary>
Random number generation of encrypted files
</summary>
private static RandomNumberGenerator Rand = new RNGCryptoServiceProvider ();
<summary>
Generate a random byte array of the specified length
</summary>
<param name= "Count" >byte array length </param>
<returns> Random byte array </returns>
private static byte[] generaterandombytes (int count)
{
byte[] bytes = new Byte[count];
Rand. GetBytes (bytes);
return bytes;
}
<summary>
Encrypting files
</summary>
<param name= "InFile" > Encrypted file </param>
<param name= "outfile" > Encrypted input file </param>
<param name= "password" > Encrypted password </param>
public static void EncryptFile (String inFile, string outfile, string password)
{
using (FileStream fin = File.openread (inFile),
Fout = File.openwrite (outfile))
{
Long lsize = Fin. Length; Input file length
int size = (int) lsize;
byte[] bytes = new Byte[buffer_size]; Cache
int read =-1; Input file Read quantity
int value = 0;
Get IV and salt
byte[] IV = generaterandombytes (16);
byte[] Salt = generaterandombytes (16);
Creating an Encrypted object
SymmetricAlgorithm SMA = desfileclass.createrijndael (password, salt);
SMA.IV = IV;
Writes IV and salt at the beginning of the output file
Fout. Write (iv, 0, Iv. Length);
Fout. Write (salt, 0, salt. Length);
Create Hash encryption
HashAlgorithm hasher = SHA256. Create ();
using (CryptoStream cout = new CryptoStream (Fout, SMA. CreateEncryptor (), CryptoStreamMode.Write),
Chash = new CryptoStream (Stream.null, Hasher, CryptoStreamMode.Write))
{
BinaryWriter bw = new BinaryWriter (cout);
Bw. Write (lsize);
Bw. Write (Fc_tag);
Read-write byte block to encrypted stream buffer
while (read = Fin. Read (bytes, 0, bytes. Length))!= 0)
{
cout. Write (bytes, 0, read);
Chash. Write (bytes, 0, read);
Value + = read;
}
Turn off the encrypted stream
Chash. Flush ();
Chash. Close ();
Read Hash
Byte[] hash = hasher. Hash;
Input file Write hash
cout. Write (hash, 0, hash.) Length);
Close file stream
cout. Flush ();
cout. Close ();
}
}
}
<summary>
Decrypting files
</summary>
<param name= "InFile" > Pending decryption File </param>
<param name= "outfile" > Decrypted output file </param>
<param name= "password" > decryption password </param>
public static void DecryptFile (String inFile, string outfile, string password)
{
Create Open File stream
using (FileStream fin = File.openread (inFile),
Fout = File.openwrite (outfile))
{
int size = (int) fin. Length;
byte[] bytes = new Byte[buffer_size];
int read =-1;
int value = 0;
int outvalue = 0;
byte[] IV = new BYTE[16];
Fin. Read (IV, 0, 16);
Byte[] Salt = new BYTE[16];
Fin. Read (salt, 0, 16);
SymmetricAlgorithm SMA = desfileclass.createrijndael (password, salt);
SMA.IV = IV;
value = 32;
Long lsize =-1;
Create a Hash object, verify the file
HashAlgorithm hasher = SHA256. Create ();
using (CryptoStream cin = new CryptoStream (FIN, SMA.) CreateDecryptor (), CryptoStreamMode.Read),
Chash = new CryptoStream (Stream.null, Hasher, CryptoStreamMode.Write))
{
Read file length
BinaryReader br = new BinaryReader (CIN);
Lsize = Br. ReadInt64 ();
ULONG tag = br. ReadUInt64 ();
if (Fc_tag!= TAG)
throw new Cryptohelpexception ("File corrupted");
Long numreads = lsize/buffer_size;
Long slack = (long) lsize% Buffer_size;
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;
}
if (Slack > 0)
{
Read = cin. Read (bytes, 0, (int) slack);
Fout. Write (bytes, 0, read);
Chash. Write (bytes, 0, read);
Value + = read;
Outvalue + = read;
}
Chash. Flush ();
Chash. Close ();
Fout. Flush ();
Fout. Close ();
byte[] Curhash = Hasher. Hash;
Getting comparisons and old hash objects
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");
}
if (Outvalue!= lsize)
throw new Cryptohelpexception ("File size mismatch");
}
}
}
}

Encryption/Decryption Result:
To encrypt the 1.avi under D disk For example, the encrypted file is 1.avi.dat, even if the renamed back 1.avi file is still unable to open (file is encrypted).

After the password is decrypted, the file is recovered and decrypted, it can be opened successfully ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.