File encryption and decryption under. Net

Source: Internet
Author: User
Tags base64 bool key words
Encryption | decryption key words:. NET the Framework of the "data" encryption and decryption file body: When you use an XML file to record configuration information, Sometimes you don't want people to see the content of the configuration information. How to achieve it. Here are some common encryption and decryption algorithms. The framework of these algorithms is already encapsulated. We don't have to pay attention to the actual implementation, just need to use on the line.
Using System;
Using System.Security.Cryptography;
Using System.IO;
Using System.text;namespace coder
{
<summary>
Summary description of the Symmcrypto.
The Symmcrypto class implements the encryption and decryption services under the. NET Framework.
Original Author: Frank fang:fangfrank@hotmail.com
Modified By: ligang:nkligang@163.com
</summary>
public class Symmcrypto
{
public enum Symmprovenum:int
{
DES, RC2, Rijndael
Private SymmetricAlgorithm Mobjcryptoservice; <remarks>
constructors that use the. Net SymmetricAlgorithm class.
</remarks>
Public Symmcrypto (Symmprovenum netselected)
{
Switch (netselected)
{
Case Symmprovenum.des:
Mobjcryptoservice = new DESCryptoServiceProvider ();
Break
Case SYMMPROVENUM.RC2:
Mobjcryptoservice = new Rc2cryptoserviceprovider ();
Break
Case Symmprovenum.rijndael:
Mobjcryptoservice = new RijndaelManaged ();
Break
}
}///<remarks>
Use the constructor of the custom SymmetricAlgorithm class.
</remarks>
Public Symmcrypto (SymmetricAlgorithm serviceprovider)
{
Mobjcryptoservice = serviceprovider;
}///<remarks>
Depending on the legal key size limitations of
A specific Cryptoservice provider and length of
The private key provided, padding the secret key
With spaces character to meet the legal size of the algorithm.
</remarks>
Private byte[] Getlegalkey (string Key)
{
String stemp;
if (MobjCryptoService.LegalKeySizes.Length > 0)
{
int lesssize = 0, moresize = mobjcryptoservice.legalkeysizes[0]. MinSize;
Key sizes are in bits
while (Key.length * 8 > Moresize)
{
Lesssize = moresize;
Moresize + = Mobjcryptoservice.legalkeysizes[0]. Skipsize;
}
Stemp = Key.padright (MORESIZE/8, ");
}
Else
Stemp = Key; Convert the secret key to byte array
Return ASCIIEncoding.ASCII.GetBytes (stemp);
Public byte[] Encrypting (byte[] bytin, string Key)
{//Create a MemoryStream so, the process can be done without I/O files
System.IO.MemoryStream ms = new System.IO.MemoryStream ();            byte[] Bytkey = Getlegalkey (Key); Set the private key
Mobjcryptoservice.key = Bytkey;
MOBJCRYPTOSERVICE.IV = Bytkey; Create a encryptor from the Provider Service instance
ICryptoTransform encrypto = Mobjcryptoservice.createencryptor (); Create Crypto stream that transforms a stream using the encryption
CryptoStream cs = new CryptoStream (MS, Encrypto, CryptoStreamMode.Write); Write out encrypted content into MemoryStream
Cs. Write (bytin, 0, bytin.length);
Cs.            FlushFinalBlock (); Get the output and trim the ' bytes '
Byte[] Bytout = Ms.            GetBuffer (); return bytout;
Public byte[] Decrypting (byte[] bytin, string Key)
{
Create a MemoryStream with the input
System.IO.MemoryStream ms = new System.IO.MemoryStream (bytin, 0, bytin.length);            byte[] Bytkey = Getlegalkey (Key); Set the private key
Mobjcryptoservice.key = Bytkey;
MOBJCRYPTOSERVICE.IV = Bytkey; Create a decryptor from the Provider Service instance
ICryptoTransform encrypto = Mobjcryptoservice.createdecryptor (); Create Crypto stream that transforms a stream using the decryption
CryptoStream cs = new CryptoStream (MS, Encrypto, CryptoStreamMode.Write);
read out of the result from the Crypto Stream
Cs. Write (bytin, 0, bytin.length);
Cs.            Flush (); Return Ms. ToArray ();
}
}
Examples of specific uses are given below: //Codingpublic bool Encoding (string inputfile,string outputfile)
{
byte[] buffer = new byte[1024];
byte[] buf = new byte[1032]; int temp;
Coder. Symmcrypto coding = new Symmcrypto (coder. SymmCrypto.SymmProvEnum.DES);
if (System.IO.File.Exists (inputfile))
{
// definition file Read class
Stream instream = File.Open (Inputfile,filemode.open);
Stream OutStream = file.create (outputfile);
// reading Files
Todo
{
temp = instream.read (buffer, 0, 1024);
BUF = coding. Encrypting (Buffer, "12345678");
if (Temp > 0)
{
Outstream.write (buf, 0, temp+8);
}
Else
Break
}
while (true); // Releasing Flow Resources
Instream.close ();
Outstream.close ();
return true;
} //decodingpublic bool Decoding (string inputfile, String outputfile)
{
byte[] buffer = new byte[1032];
byte[] buf = new byte[1024];
int temp;
Coder. Symmcrypto coding = new Symmcrypto (coder. SymmCrypto.SymmProvEnum.DES);
if (System.IO.File.Exists (inputfile))
{
Stream instream = File.Open (Inputfile, FileMode.Open);
Stream OutStream = file.create (outputfile);
Todo
{
temp = instream.read (buffer, 0, 1032);
BUF = coding.                    Decrypting (buffer, "12345678"); if (Temp > 0)
{
Outstream.write (buf, 0, temp-8);
}
Else
Break
}
while (true); Instream.close ();
Outstream.close ();
return true;
A few questions to explain: 1. This procedure is applicable to the encryption and decryption of files. Source author's encryption and decryption program for binary files and even text file read and write is the problem of 2. This program removes the base64 encoding and decoding process in the source program. Because of this problem, Character 0 (ASCII) may appear after encrypting the contents of the file. This particular character is problematic in base64 coding. The Base64 encoding function would assume that 0 is the end and fill in some of the characters in the future. 3. For file input and output buffer size issues. Consider the number of characters to be increased by 8 after encryption. The read buffer should be less than the written buffer when encrypted 8 , but the decryption section does not take a 8-character read buffer size over the size of the buffer, but it is recommended to follow this scenario.


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.