C#针对字符串加密解密(对称加密)

具体代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Yasn.Utility
{
    public class DES_StrText
    {
        ///  
        /// 加密 
        ///  
        ///  
        ///  
        public static string Encrypt(string strText)
        {
            Byte[] Iv64 = { 3, 9, 22, 32, 42, 51, 61, 71 };
            Byte[] byKey64 = { 2, 22, 42, 62, 82, 102, 122, 142 };

            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey64, Iv64), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                Utils.WriteLog(Convert.ToBase64String(ms.ToArray()));
                return Convert.ToBase64String(ms.ToArray());
                
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        ///  
        /// 解密 
        ///  
        ///  
        ///  
        public static string Decrypt(string strText)
        {
            Byte[] Iv64 = { 3, 9, 22, 32, 42, 51, 61, 71 };
            Byte[] byKey64 = { 2, 22, 42, 62, 82, 102, 122, 142 };
            Byte[] inputByteArray = new byte[strText.Length];
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey64, Iv64), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                Utils.WriteLog(encoding.GetString(ms.ToArray()));
                return encoding.GetString(ms.ToArray());

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}


你可能感兴趣的:(C#针对字符串加密解密(对称加密))