.NET 加/解密

来源:互联网 发布:php集成开发工具 编辑:程序博客网 时间:2024/05/22 10:41
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Security.Cryptography;using System.IO;using System.Text;namespace Ciphertext{    public class Des    {        static string key = "XXX", iv = "YYY";        /// <summary>        /// 加密        /// </summary>        /// <param name="sourceString"></param>        /// <returns></returns>        public static string Encrypt(string sourceString)        {            try            {                DESCryptoServiceProvider des = new DESCryptoServiceProvider();                using (MemoryStream ms = new MemoryStream())                {                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);                    try                    {                        using (CryptoStream cs = new CryptoStream(                            ms                            , des.CreateEncryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv))                            , CryptoStreamMode.Write))                        {                            cs.Write(inData, 0, inData.Length);                            cs.FlushFinalBlock();                        }                        return Convert.ToBase64String(ms.ToArray());                    }                    catch                    {                        return sourceString;                    }                }            }            catch (Exception ex)            {                return "DES加密出错: " + ex.Message;            }        }        /// <summary>        /// 解密        /// </summary>        /// <param name="encryptedString"></param>        /// <returns></returns>        public static string Decrypt(string encryptedString)        {            DESCryptoServiceProvider des = new DESCryptoServiceProvider();            using (MemoryStream ms = new MemoryStream())            {                byte[] inData = Convert.FromBase64String(encryptedString);                try                {                    using (CryptoStream cs = new CryptoStream(                        ms                        , des.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv))                        , CryptoStreamMode.Write))                    {                        cs.Write(inData, 0, inData.Length);                        cs.FlushFinalBlock();                    }                    return Encoding.UTF8.GetString(ms.ToArray());                }                catch (Exception ex)                {                    return "DES解密出错: " + ex.Message;                }            }        }    }}


                                             
0 0
原创粉丝点击