C # encryption/Decryption class

Source: Internet
Author: User
What I wrote in the previous two years is now sorted out! In the past, the company needed to do WebService and encrypted the soapheader of WebService, So we wrote this stuff! Key management is required to use this class! Data Encryption is often required to ensure data security, but one of the disadvantages of encryption is that Program So my idea was to encrypt the user's login information (username and password! Data is transmitted in plain text. If user information verification fails, no data is transmitted.

In actual network communication, the key-secret method is not impeccable. If a hacker can capture the Information encrypted with the key, the user will verify the information and then make a simulated request, send a request to the server that provides WebService, or you can obtain the request data! So I used the IP address or domain name binding method again! After all, WebService is not directly provided to end users! Therefore, even if the attackers attempt to obtain the services provided by WebService in illegal ways, they will pay more for them!

Another security suggestion is to regularly change the key. In this example, we use symmetric encryption, which is consistent with the key of the encryption party and the decryption party! Regular key replacement can improve security!

For better methods or suggestions, please leave a message to discuss them! Improve together!

CodeAs follows:

Using system;
Using system. Security. cryptography;
Using system. text;
Using system. IO;

Namespace SEDO
{
/// <Summary>
/// Summary of SEDO.
/// SEDO implements a component that encapsulates four symmetric encryption methods (DES, RC2, Rijndael, and tripledes ).
///
/// Note:
/// 1: tripledes and Rijndael encrypt/decrypt the object using a 16-or 24-bit byte key
/// 2: Rijndael can only use a 16-bit initialization vector IV
/// 3: des and RC2 both use the eight-byte key and IV
/// 4: The method used for encoding/decoding the data stream to be encrypted/decrypted, which is determined by the user who calls the component.
/// 5: the key and initialization vector IV are defined by the user.
// Programmer: Wang Haibo hwnanghb@21cn.com
/// </Summary>

// Defines the encryption type enumeration.
Public Enum encryptionalgorithm {des = 1, RC2, Rijndael, tripledes };

// Define the Encryption Class
Internal class encrypttransformer
{
Private encryptionalgorithm algorithmid;
Private byte [] initvec;
Private byte [] enckey;

Internal encrypttransformer (encryptionalgorithm algid)
{
// Save the algorithm being used.
Algorithmid = algid;
}

Internal icryptotransform getcryptoserviceprovider (byte [] byteskey)
{
// When the data key or initialization vector IV is empty, the key automatically generated by the encryption object or the initialization vector IV will be used
Switch (algorithmid)
{
Case encryptionalgorithm. Des:
{
Des = new descryptoserviceprovider ();
Des. mode = ciphermode. CBC;

// See if a key was provided
If (null = byteskey)
{
Enckey = des. Key;
}
Else
{
Des. Key = byteskey;
Enckey = des. Key;
}
// See if the client provided an initialization Vector
If (null = initvec)
{// Have the algorithm create one
Initvec = des. IV;
}
Else
{// No, give it to the algorithm
Des. IV = initvec;
}
Return des. createencryptor ();
}
Case encryptionalgorithm. tripledes:
{
Tripledes des3 = new tripledescryptoserviceprovider ();
Des3.mode = ciphermode. CBC;
// See if a key was provided
If (null = byteskey)
{
Enckey = des3.key;
}
Else
{
Des3.key = byteskey;
Enckey = des3.key;
}
// See if the client provided an iv
If (null = initvec)
{// Yes, have the ALG create one
Initvec = des3.iv;
}
Else
{// No, give it to the ALG.
Des3.iv = initvec;
}
Return des3.createencryptor ();
}
Case encryptionalgorithm. RC2:
{
RC2 RC2 = new rc2cryptoserviceprovider ();
Rc2.mode = ciphermode. CBC;
// Test to see if a key was provided
If (null = byteskey)
{
Enckey = rc2.key;
}
Else
{
Rc2.key = byteskey;
Enckey = rc2.key;
}
// See if the client provided an iv
If (null = initvec)
{// Yes, have the ALG create one
Initvec = rc2.iv;
}
Else
{// No, give it to the ALG.
Rc2.iv = initvec;
}
Return rc2.createencryptor ();
}
Case encryptionalgorithm. Rijndael:
{
Rijndael = new rijndaelmanaged ();
Rijndael. mode = ciphermode. CBC;
// Test to see if a key was provided
If (null = byteskey)
{
Enckey = Rijndael. Key;
}
Else
{
Rijndael. Key = byteskey;
Enckey = Rijndael. Key;
}
// See if the client provided an iv
If (null = initvec)
{// Yes, have the ALG create one
Initvec = Rijndael. IV;
}
Else
{// No, give it to the ALG.
Rijndael. IV = initvec;
}
Return Rijndael. createencryptor ();
}
Default:
{
Throw new cryptographicexception ("algorithm id'" +
Algorithmid +
"'Not supported .");
}
}
}

// Encrypted offset Vector
Internal byte [] IV
{
Get {return initvec ;}
Set {initvec = value ;}
}
// Encrypted Key
Internal byte [] Key
{
Get {return enckey ;}
Set {enckey = value ;}
}

}

// Define the decryption class
Internal class decrypttransformer
{
Private encryptionalgorithm algorithmid;
Private byte [] initvec;
Private byte [] enckey;

Internal decrypttransformer (encryptionalgorithm decryptid)
{
Algorithmid = decryptid;
}

// Encrypted offset Vector
Internal byte [] IV
{
Get {return initvec ;}
Set {initvec = value ;}
}

// Encrypted Key
Internal byte [] Key
{
Get {return enckey ;}
Set {enckey = value ;}
}

Internal icryptotransform getcryptoserviceprovider (byte [] byteskey)
{
// When the data key or initialization vector IV is empty, the key automatically generated by the encryption object or the initialization vector IV will be used
Switch (algorithmid)
{
Case encryptionalgorithm. Des:
{
Des = new descryptoserviceprovider ();
Des. mode = ciphermode. CBC;
Des. Key = byteskey;
Des. IV = initvec;
Return des. createdecryptor ();
}
Case encryptionalgorithm. tripledes:
{
Tripledes des3 = new tripledescryptoserviceprovider ();
Des3.mode = ciphermode. CBC;
Return des3.createdecryptor (byteskey, initvec );
}
Case encryptionalgorithm. RC2:
{
RC2 RC2 = new rc2cryptoserviceprovider ();
Rc2.mode = ciphermode. CBC;
Return rc2.createdecryptor (byteskey, initvec );
}
Case encryptionalgorithm. Rijndael:
{
Rijndael = new rijndaelmanaged ();
Rijndael. mode = ciphermode. CBC;
Return Rijndael. createdecryptor (byteskey, initvec );
}
Default:
{
Throw new cryptographicexception ("algorithm id'" +
Algorithmid +
"'Not supported .");
}
}
} // End getcryptoserviceprovider

}

// Define the Encryption Class
Public class encryptor
{
Private encrypttransformer transformer;
Private byte [] initvec;
Private byte [] enckey;

Public encryptor (encryptionalgorithm algid)
{
Transformer = new encrypttransformer (algid );
}

Public byte [] encrypt (byte [] bytesdata, byte [] byteskey, byte [] bytesiv)
{
// Set the stream object to save the encrypted data byte stream.
Memorystream memstreamencrypteddata = new memorystream ();

Transformer. IV = bytesiv;
Transformer. Key = byteskey;

Icryptotransform transform = transformer. getcryptoserviceprovider (byteskey );
Cryptostream encstream = new cryptostream (memstreamencrypteddata, transform, cryptostreammode. Write );

Try
{
// Write encrypted data into the stream object
Encstream. Write (bytesdata, 0, bytesdata. Length );
}
Catch (exception ex)
{
Throw new exception ("an error occurred during data encryption! Error message: \ n "+ ex. Message );
}

// Set the Encrypted Key and initial vector IV attributes
Enckey = transformer. Key;
Initvec = transformer. IV;

Encstream. flushfinalblock ();
Encstream. Close ();

// Send the data back.
Return memstreamencrypteddata. toarray ();
}

Public byte [] IV
{
Get {return initvec ;}
Set {initvec = value ;}
}

Public byte [] Key
{
Get {return enckey ;}
Set {enckey = value ;}
}

}

// Define the decryption class
Public class decryptor
{
Private decrypttransformer transformer;
Private byte [] initvec;
Private byte [] enckey;

Public decryptor (encryptionalgorithm algid)
{
Transformer = new decrypttransformer (algid );
}

Public byte [] decrypt (byte [] bytesdata, byte [] byteskey, byte [] bytesiv)
{
// Set the stream object to save and decrypt the data byte stream.
Memorystream memstreamdecrypteddata = new memorystream ();

// Pass in the initialization vector.
Transformer. IV = bytesiv;
Transformer. Key = byteskey;

Icryptotransform transform = transformer. getcryptoserviceprovider (byteskey );
Cryptostream decstream = new cryptostream (memstreamdecrypteddata, transform, cryptostreammode. Write );

Try
{
Decstream. Write (bytesdata, 0, bytesdata. Length );
}
Catch (exception ex)
{
Throw new exception ("an error occurred during data decryption! Error message: \ n "+ ex. Message );
}
Decstream. flushfinalblock ();
Decstream. Close ();
// Return the decrypted data.
Return memstreamdecrypteddata. toarray ();
}

Public byte [] IV
{
Get {return initvec ;}
Set {initvec = value ;}
}

Public byte [] Key
{
Get {return enckey ;}
Set {enckey = value ;}
}

}

// Class description: file encryption/Decryption class
Public class securityfile
{
Private decrypttransformer dec_transformer; // decryption Converter
Private encrypttransformer enc_transformer; // encryption Converter
Private byte [] initvec;
Private byte [] enckey;

Public securityfile (encryptionalgorithm algid)
{
Dec_transformer = new decrypttransformer (algid );
Enc_transformer = new encrypttransformer (algid );
}

// Encrypted offset Vector
Internal byte [] IV
{
Get {return initvec ;}
Set {initvec = value ;}
}
// Encrypted Key
Internal byte [] Key
{
Get {return enckey ;}
Set {enckey = value ;}
}

// Function Description: encrypt a file
Public void encryptfile (string infilename, string outfilename, byte [] byteskey, byte [] bytesiv)
{
Try
{
Filestream fin = new filestream (infilename, filemode. Open, fileaccess. Read );
Filestream fout = new filestream (outfilename, filemode. openorcreate, fileaccess. Write );
Fout. setlength (0 );

// Create variables to help with read and write.
Byte [] bin = new byte [100]; // This is intermediate storage for the encryption.
Long rdlen = 0; // This is the total number of bytes written.
Long totlen = fin. length; // This is the total length of the input file.
Int Len; // This is the number of bytes to be written at a time.

Enc_transformer.iv = bytesiv;
Enc_transformer.key = byteskey;

Icryptotransform transform = enc_transformer.getcryptoserviceprovider (byteskey );
Cryptostream encstream = new cryptostream (fout, transform, cryptostreammode. Write );

// Read from the input file, then encrypt and write to the output file.
While (rdlen <totlen)
{
Len = fin. Read (bin, 0,100 );
Encstream. Write (bin, 0, Len );
Rdlen = rdlen + Len;
}

Encstream. Close ();
Fout. Close ();
Fin. Close ();
}
Catch (exception ex)
{
Throw new exception ("an error occurred during file encryption! Error message: \ n "+ ex. Message );
}
}

// Function Description: decrypt a file
Public void decryptfile (string infilename, string outfilename, byte [] byteskey, byte [] bytesiv)
{
Try
{
Filestream fin = new filestream (infilename, filemode. Open, fileaccess. Read );
Filestream fout = new filestream (outfilename, filemode. openorcreate, fileaccess. Write );
Fout. setlength (0 );

// Create variables to help with read and write.
Byte [] bin = new byte [100]; // This is intermediate storage for the encryption.
Long rdlen = 0; // This is the total number of bytes written.
Long totlen = fin. length; // This is the total length of the input file.
Int Len; // This is the number of bytes to be written at a time.

Dec_transformer.iv = bytesiv;
Dec_transformer.key = byteskey;

Icryptotransform transform = dec_transformer.getcryptoserviceprovider (byteskey );
Cryptostream encstream = new cryptostream (fout, transform, cryptostreammode. Write );

// Read from the input file, then encrypt and write to the output file.
While (rdlen <totlen)
{
Len = fin. Read (bin, 0,100 );
Encstream. Write (bin, 0, Len );
Rdlen = rdlen + Len;
}

Encstream. Close ();
Fout. Close ();
Fin. Close ();
}
Catch (exception ex)
{
Throw new exception ("an error occurred during file encryption! Error message: \ n "+ ex. Message );
}
}

}

}

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.