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;
}
}
}
}
}
.NET 加/解密
最新推荐文章于 2019-09-30 16:24:00 发布