欢迎光临

木子屋

标题: C#使用DES加密字符串示例

作者: dnawo

日期: 2012-10-08 11:05 AM

分类: Web编程

内容: DES加/解密类EncryptHelpr：
复制内容到剪贴板 程序代码using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Library
{
public class EncryptHelpr
{
private static readonly string key = "1234abcd";
private static readonly string iv = "12345678";
/// <summary>
/// 加密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string Encrypt(string data)
{
return Encrypt(data, Encoding.UTF8);
}
/// <summary>
/// 加密
/// </summary>
/// <param name="data"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Encrypt(string data, Encoding encode)
{
StringBuilder result = new StringBuilder();
byte[] dataByteArray = encode.GetBytes(data);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key);
provider.IV = Encoding.ASCII.GetBytes(iv);
using (MemoryStream memory = new MemoryStream())
{
using (CryptoStream crypto = new CryptoStream(memory, provider.CreateEncryptor(), CryptoStreamMode.Write))
{
crypto.Write(dataByteArray, 0, dataByteArray.Length);
crypto.FlushFinalBlock();
foreach (byte item in memory.ToArray())
{
result.AppendFormat("{0:X2}", item);
}
}
}
return result.ToString();
}
/// <summary>
/// 解密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string Decrypt(string data)
{
return Decrypt(data, Encoding.UTF8);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="data"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Decrypt(string data, Encoding encode)
{
string result = string.Empty;
byte[] dataByteArray = new byte[data.Length / 2];
for (int n = 0; n < dataByteArray.Length; n++)
{
dataByteArray[n] = (byte)Convert.ToInt32(data.Substring(n * 2, 2), 0x10);
}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key);
provider.IV = Encoding.ASCII.GetBytes(iv);
using (MemoryStream memory = new MemoryStream())
{
using (CryptoStream crypto = new CryptoStream(memory, provider.CreateDecryptor(), CryptoStreamMode.Write))
{
crypto.Write(dataByteArray, 0, dataByteArray.Length);
crypto.FlushFinalBlock();
result = encode.GetString(memory.ToArray());
}
}
return result;
}
}
}
调用示例：
复制内容到剪贴板 程序代码string str = EncryptHelpr.Encrypt("http://www.mzwu.com/");
Console.WriteLine(str);
Console.WriteLine(EncryptHelpr.Decrypt(str));
参考资料
[1].[C#.NET]字串及檔案利用DES/AES演算法加解密：http://www.dotblogs.com.tw/yc421206/archive/2012/04/18/71609.aspx

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.852 ms

返回

标题: C#使用DES加密字符串示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.852 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.883 ms

返回