using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace DesDemo
{
public class DESHelper
{
//密钥
public static byte[] _KEY = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
//向量
public static byte[] _IV = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };
///
/// DES加密操作
///
///
///
public string DesEncrypt(string normalTxt)
{
//byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
//byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(_KEY, _IV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(normalTxt);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
return strRet;
}
///
/// DES解密操作
///
/// 加密字符串
///
public string DesDecrypt(string securityTxt)//解密
{
//byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY);
//byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
byte[] byEnc;
try
{
securityTxt.Replace("%", “/”);
securityTxt.Replace("-%-", “#”);
byEnc = Convert.FromBase64String(securityTxt);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(_KEY, _IV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
}}
C#DES加密解密操作
最新推荐文章于 2024-07-18 16:22:57 发布