C # encryption and decryption

Source: Internet
Author: User

Using system. Security. cryptography;

# Region RC2
/// <Summary>
/// Perform RC2 encryption.
/// </Summary>
/// <Param name = "ptoencrypt"> string to be encrypted. </Param>
/// <Param name = "skey"> initialization vector </param>
/// <Param name = "IV"> The key must be 8 bits. </Param>
/// <Returns> the encrypted string returned in base64 format. </Returns>
Public static string encrypt (string ptoencrypt, byte [] key, byte [] IV)
{
// Create UTF-16 encoding for conversion between byte [] and string
System. Text. unicodeencoding textconverter = new unicodeencoding ();
Byte [] inputbytearray = encoding. utf8.getbytes (ptoencrypt );
Using (rc2cryptoserviceprovider rc2csp = new rc2cryptoserviceprovider ())
{
System. Security. cryptography. icryptotransform encryptor = rc2csp. createencryptor (Key, IV );

system. io. memorystream MS = new system. io. memorystream ();
using (cryptostream cs = new cryptostream (MS, encryptor, cryptostreammode. write)
{< br> CS. write (inputbytearray, 0, inputbytearray. length);
CS. flushfinalblock ();
CS. close ();
}< br> string STR = convert. tobase64string (Ms. toarray ();
MS. close ();
return STR;
}< BR >}

///


/// decrypt RC2.
///
/// base64
// initialization vector
// key, it must be 8 bits.
// decrypted string.
Public static string decrypt (string ptodecrypt, byte [] key, byte [] IV)
{< br> byte [] inputbytearray = convert. frombase64string (ptodecrypt);
using (rc2cryptoserviceprovider rc2csp = new rc2cryptoserviceprovider ()
{< br> system. security. cryptography. icryptotransform encryptor = rc2csp. createdecryptor (Key, iv);
system. io. memorystream MS = new system. io. memorystream ();
using (cryptostream cs = new cryptostream (MS, encryptor, cryptostreammode. write)
{< br> CS. write (inputbytearray, 0, inputbytearray. length);
CS. flushfinalblock ();
CS. close ();
}< br> string STR = encoding. utf8.getstring (Ms. toarray ();
MS. close ();
return STR;
}< BR >}

# Endregion

# Region RSA

/// <Summary>
/// RSA Encryption
/// </Summary>
/// <Param name = "datatoencrypt"> </param>
/// <Param name = "dooaeppadding"> </param>
/// <Returns> </returns>
Static public byte [] rsaencrypt (byte [] datatoencrypt, bool dooaeppadding)
{
Try
{
Rsacryptoserviceprovider RSA = new rsacryptoserviceprovider ();

Streamreader reader = new streamreader (@ "D: \ publickey. xml ");
String pkey = reader. readtoend ();
RSA. fromxmlstring (pkey );
Reader. Close ();

Return RSA. Encrypt (datatoencrypt, dooaeppadding );
}
Catch (cryptographicexception E)
{
Console. writeline (E. Message );

Return NULL;
}

}

/// <Summary>
/// RSA decryption
/// </Summary>
/// <Param name = "datatodecrypt"> </param>
/// <Param name = "dooaeppadding"> </param>
/// <Returns> </returns>
Static public byte [] rsadecrypt (byte [] datatodecrypt, bool dooaeppadding)
{
Try
{
Rsacryptoserviceprovider RSA = new rsacryptoserviceprovider ();

Streamreader reader = new streamreader (@ "D: \ publicandprivatekey. xml ");
String ppkey = reader. readtoend ();
RSA. fromxmlstring (ppkey );
Reader. Close ();

Return RSA. decrypt (datatodecrypt, dooaeppadding );
}
Catch (cryptographicexception E)
{
Console. writeline (E. tostring ());

Return NULL;
}

}

# Endregion

# Region des

///


/// perform DES encryption.
///
/// string to be encrypted.
// The key must be 8 bits.
// the encrypted string returned in base64 format.
Public static string encrypt (string ptoencrypt, string skey)
{< br> using (descryptoserviceprovider des = new descryptoserviceprovider ())
{< br> byte [] inputbytearray = encoding. utf8.getbytes (ptoencrypt);
des. key = asciiencoding. ASCII. getbytes (skey);
des. IV = asciiencoding. ASCII. getbytes (skey);
system. io. memorystream MS = new system. io. memorystream ();
using (cryptostream cs = new cryptostream (MS, Des. createencryptor (), cryptostreammode. write)
{< br> CS. write (inputbytearray, 0, inputbytearray. length);
CS. flushfinalblock ();
CS. close ();
}< br> string STR = convert. tobase64string (Ms. toarray ();
MS. close ();
return STR;
}< BR >}

/// <Summary>
/// Perform des decryption.
/// </Summary>
/// <Param name = "ptodecrypt"> the base64 file to be decrypted </param>
/// <Param name = "skey"> The key must be 8 bits. </Param>
/// <Returns> decrypted string. </Returns>
Public static string decrypt (string ptodecrypt, string skey)
{
Byte [] inputbytearray = convert. frombase64string (ptodecrypt );
Using (descryptoserviceprovider des = new descryptoserviceprovider ())
{
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );
System. Io. memorystream MS = new system. Io. memorystream ();
Using (cryptostream cs = new cryptostream (MS, Des. createdecryptor (), cryptostreammode. Write ))
{
CS. Write (inputbytearray, 0, inputbytearray. Length );
CS. flushfinalblock ();
CS. Close ();
}
String STR = encoding. utf8.getstring (Ms. toarray ());
Ms. Close ();
Return STR;
}
}

# Endregion

# Region MD5

[Test]
Public void testmd5 ()
{
Console. writeline (this. encodepassword ("1 "));
}

String encodepassword (string originalpassword)
{
// Declarations
Byte [] originalbytes;
Byte [] encodedbytes;
MD5 MD5;

// Instantiate md5cryptoserviceprovider, get bytes for original password and compute Hash (encoded password)
MD5 = new md5cryptoserviceprovider ();
Originalbytes = asciiencoding. Default. getbytes (originalpassword );
Encodedbytes = md5.computehash (originalbytes );

// Convert encoded bytes back to a 'readable' string
Return bitconverter. tostring (encodedbytes );
}

# Endregion

# Region RC4

/// <Summary>
/// Encrypt or decrypt (symmetric)
/// </Summary>
/// <Param name = "data"> plaintext or ciphertext </param>
/// <Param name = "pass"> key </param>
/// <Returns> ciphertext or plaintext </returns>
Public byte [] encryptex (byte [] data, string pass)
{
If (Data = NULL | pass = NULL) return NULL;
Byte [] Output = new byte [data. Length];
Int64 I = 0;
Int64 J = 0;
Byte [] mbox = getkey (encoding. UTF-8 getbytes (PASS), 256 );

// Encryption
For (int64 offset = 0; offset <data. length; offset ++)
{
I = (I + 1) % mbox. length;
J = (J + mbox [I]) % mbox. length;
Byte temp = mbox [I];
Mbox [I] = mbox [J];
Mbox [J] = temp;
Byte A = data [offset];
// Byte B = mbox [(mbox [I] + mbox [J] % mbox. Length) % mbox. Length];
// Mbox [J] Must be smaller than mbox. Length and does not need to be Modulus
Byte B = mbox [(mbox [I] + mbox [J]) % mbox. Length];
Output [offset] = (byte) (int32) a ^ (int32) B );
}

Return output;
}

/// <Summary>
/// Decrypt
/// </Summary>
/// <Param name = "data"> </param>
/// <Param name = "pass"> </param>
/// <Returns> </returns>
Public byte [] decryptex (byte [] data, string pass)
{
Return encryptex (data, pass );
}

/// <Summary>
/// Disrupt the password
/// </Summary>
/// <Param name = "pass"> password </param>
/// <Param name = "klen"> Password box length </param>
/// <Returns> the disrupted password </returns>
Static private byte [] getkey (byte [] Pass, int32 klen)
{
Byte [] mbox = new byte [klen];

For (int64 I = 0; I <klen; I ++)
{
Mbox [I] = (byte) I;
}
Int64 J = 0;
For (int64 I = 0; I <klen; I ++)
{
J = (J + mbox [I] + pass [I % pass. Length]) % klen;
Byte temp = mbox [I];
Mbox [I] = mbox [J];
Mbox [J] = temp;
}
Return mbox;
}

# Endregion

# Region AES

/// <Summary>
/// Obtain the key
/// </Summary>
Private Static string key
{
Get {return @ ") O [Nb] 6, YF} + efcaj {+ oesb9d8> Z 'e9m ";}
}

/// <Summary>
/// Obtain the Vector
/// </Summary>
Private Static string IV
{
Get {return @ "L + \~ F4, IR) B $ = PKF ";}
}

/// <Summary>
/// AES Encryption
/// </Summary>
/// <Param name = "plainstr"> plaintext string </param>
/// <Param name = "returnnull"> whether to return NULL if encryption fails. If false, String. Empty is returned. </param>
/// <Returns> ciphertext </returns>
Public String aesencrypt (string plainstr, bool returnnull)
{
String encrypt = aesencrypt (plainstr );
Return returnnull? Encrypt: (encrypt = NULL? String. Empty: encrypt );
}

/// <Summary>
/// AES Encryption
/// </Summary>
/// <Param name = "plainstr"> plaintext string </param>
/// <Returns> ciphertext </returns>
Public String aesencrypt (string plainstr)
{
Byte [] bkey = encoding. utf8.getbytes (key );
Byte [] BIV = encoding. utf8.getbytes (IV );
Byte [] bytearray = encoding. utf8.getbytes (plainstr );

String encrypt = NULL;
Rijndael AES = Rijndael. Create ();
Try
{
Using (memorystream mstream = new memorystream ())
{
Using (cryptostream cstream = new cryptostream (mstream, AES. createencryptor (bkey, BIV), cryptostreammode. Write ))
{
Cstream. Write (bytearray, 0, bytearray. Length );
Cstream. flushfinalblock ();
Encrypt = convert. tobase64string (mstream. toarray ());
}
}
}
Catch {}
AES. Clear ();

Return encrypt;
}

/// <Summary>
/// AES decryption
/// </Summary>
/// <Param name = "encryptstr"> ciphertext string </param>
/// <Param name = "returnnull"> whether to return NULL if decryption fails. If false, String. Empty is returned. </param>
/// <Returns> plaintext </returns>
Public String aesdecrypt (string encryptstr, bool returnnull)
{
String decrypt = aesdecrypt (encryptstr );
Return returnnull? Decrypt: (decrypt = NULL? String. Empty: decrypt );
}

/// <Summary>
/// AES decryption
/// </Summary>
/// <Param name = "encryptstr"> ciphertext string </param>
/// <Returns> plaintext </returns>
Public String aesdecrypt (string encryptstr)
{
Byte [] bkey = encoding. utf8.getbytes (key );
Byte [] BIV = encoding. utf8.getbytes (IV );
Byte [] bytearray = convert. frombase64string (encryptstr );

String decrypt = NULL;
Rijndael AES = Rijndael. Create ();
Try
{
Using (memorystream mstream = new memorystream ())
{
Using (cryptostream cstream = new cryptostream (mstream, AES. createdecryptor (bkey, BIV), cryptostreammode. Write ))
{
Cstream. Write (bytearray, 0, bytearray. Length );
Cstream. flushfinalblock ();
Decrypt = encoding. utf8.getstring (mstream. toarray ());
}
}
}
Catch {}
AES. Clear ();

Return decrypt;
}

# Endregion

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.