C#公共类
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.9 KiB

using System;
using System.IO;
using System.Security.Cryptography;
namespace Common.Helper.Encryption
{
public class DesHelper
{
private const string Key = "Blue2021";
private const string Iv = "Flag2021";
/// <summary>
/// DES加密
/// </summary>
/// <param name="data">加密数据</param>
/// <returns></returns>
public static string DesEncrypt(string data)
{
var byKey = System.Text.Encoding.ASCII.GetBytes(Key);
var byIv = System.Text.Encoding.ASCII.GetBytes(Iv);
var cryptoProvider = new DESCryptoServiceProvider();
var ms = new MemoryStream();
var cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIv), CryptoStreamMode.Write);
var sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="data">解密数据</param>
/// <returns></returns>
public static string DesDecrypt(string data)
{
var byKey = System.Text.Encoding.ASCII.GetBytes(Key);
var byIv = System.Text.Encoding.ASCII.GetBytes(Iv);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
var cryptoProvider = new DESCryptoServiceProvider();
var ms = new MemoryStream(byEnc);
var cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIv), CryptoStreamMode.Read);
var sr = new StreamReader(cst);
return sr.ReadToEnd();
}
}
}