C # DES encryption and decryption Methods

Source: Internet
Author: User
1 /// <summary>
2 // perform DES encryption.
3 /// </summary>
4 /// <param name = "pToEncrypt"> string to be encrypted. </Param>
5 /// <param name = "sKey"> key, which must be 8 bits. </Param>
6 /// <returns> the encrypted string returned in Base64 format. </Returns>
7 public string Encrypt (string pToEncrypt, string sKey)
8 {
9 using (DESCryptoServiceProvider des = new DESCryptoServiceProvider ())
10 {
11 byte [] inputByteArray = Encoding. UTF8.GetBytes (pToEncrypt );
12 des. Key = ASCIIEncoding. ASCII. GetBytes (sKey );
13 des. IV = ASCIIEncoding. ASCII. GetBytes (sKey );
14 System. IO. MemoryStream MS = new System. IO. MemoryStream ();
15 using (CryptoStream cs = new CryptoStream (MS, des. CreateEncryptor (), CryptoStreamMode. Write ))
16 {
17 cs. Write (inputByteArray, 0, inputByteArray. Length );
18 cs. FlushFinalBlock ();
19 cs. Close ();
20}
21 string str = Convert. ToBase64String (ms. ToArray ());
22 ms. Close ();
23 return str;
24}
25}
26
27
28 // <summary>
29 // perform DES decryption.
30 // </summary>
31 // <param name = "pToDecrypt"> the Base64 file to be decrypted </param>
32 // <param name = "sKey"> key, which must be 8 bits. </Param>
33 // <returns> decrypted string. </Returns>
34 public string Decrypt (string pToDecrypt, string sKey)
35 {
36 byte [] inputByteArray = Convert. FromBase64String (pToDecrypt );
37 using (DESCryptoServiceProvider des = new DESCryptoServiceProvider ())
38 {
39 des. Key = ASCIIEncoding. ASCII. GetBytes (sKey );
40 des. IV = ASCIIEncoding. ASCII. GetBytes (sKey );
41 System. IO. MemoryStream MS = new System. IO. MemoryStream ();
42 using (CryptoStream cs = new CryptoStream (MS, des. CreateDecryptor (), CryptoStreamMode. Write ))
43 {
44 cs. Write (inputByteArray, 0, inputByteArray. Length );
45 cs. FlushFinalBlock ();
46 cs. Close ();
47}
48 string str = Encoding. UTF8.GetString (ms. ToArray ());
49 ms. Close ();
50 return str;
51}
52}

 

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.