DES.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Wpfbinding
{
class DES
{
DESCryptoServiceProvider des;
public DES()
{
des = DESCryptoServiceProvider.Create() as DESCryptoServiceProvider;
des.IV = des.Key;
}
public string Key
{
get { return Convert.ToBase64String(des.Key); }
set { des.Key = Convert.FromBase64String(value); }
}
// 加密字符串
public string Encode(string sInputString)
{
byte[] data = Encoding.UTF8.GetBytes(sInputString);
ICryptoTransform desEncrypt = des.CreateEncryptor();
byte[] result = desEncrypt.TransformFinalBlock(data, , data.Length);
return Convert.ToBase64String(result);
}
// 解密字符串
public string Decode(string sInputString)
{
byte[] data = Convert.FromBase64String(sInputString);
ICryptoTransform desDecrypt = des.CreateDecryptor();
byte[] result = desDecrypt.TransformFinalBlock(data, , data.Length);
return Encoding.UTF8.GetString(result);
}
}
}
.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace Wpfbinding
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{ InitializeComponent();
testc();
}
void testc()
{
DES des = new DES(); string str = "测试,Hello Word";
textBlock1.Text = str;
textBlock2.Text = des.Encode(str);
textBlock3.Text = des.Decode(des.Encode(str));
}
}
}
DES内置key加特殊字符处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Wpfbinding
{
class DES
{
public string strKey = "";
public string strIV = "Edward.K";
public string Encrypt(string _strQ)
{
byte[] buffer = Encoding.UTF8.GetBytes(_strQ);
MemoryStream ms = new MemoryStream();
DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(ms, tdes.CreateEncryptor(Encoding.UTF8.GetBytes(strKey), Encoding.UTF8.GetBytes(strIV)), CryptoStreamMode.Write);
encStream.Write(buffer, , buffer.Length);
encStream.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray()).Replace("+", "%");
}
public string Decrypt(string _strQ)
{
_strQ = _strQ.Replace("%", "+");
byte[] buffer = Convert.FromBase64String(_strQ);
MemoryStream ms = new MemoryStream();
DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(ms, tdes.CreateDecryptor(Encoding.UTF8.GetBytes(strKey), Encoding.UTF8.GetBytes(strIV)), CryptoStreamMode.Write);
encStream.Write(buffer, , buffer.Length);
encStream.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}