DES加密解密

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
string text = "我爱你";
Console.WriteLine("加密前的明文:" + text);
string s = EnCrypt(text, "19491001");
Console.WriteLine("加密后:{0},解密后的字符串为:{1}",s, Decrypt(s,"19491001"));
Console.ReadLine();

}
//DES加密
public static string EnCrypt(string text ,string key)
{
StringBuilder ret = new StringBuilder();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputbyteArray = Encoding.GetEncoding("UTF-8").GetBytes(text);
des.Key = ASCIIEncoding.ASCII.GetBytes(key);
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputbyteArray,0 ,inputbyteArray.Length);
cs.FlushFinalBlock();
foreach (byte m in ms.ToArray())
{
ret.AppendFormat("{0:X2}", m);////将第一个参数转换为十六进制数,长度为2,不足前面补0
}
return ret.ToString();
}
//DES解密
public static string Decrypt(string cyphertext, string key)
{
if (string.IsNullOrEmpty(cyphertext))
return string.Empty;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

byte[] inputByteArray = new byte[cyphertext.Length / 2];
for (int x = 0; x < cyphertext.Length / 2; x++)
{
int i = (Convert.ToInt32(cyphertext.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}

des.Key = ASCIIEncoding.ASCII.GetBytes(key);
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();

StringBuilder ret = new StringBuilder();

return System.Text.Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
}
}
}

 

posted @ 2017-03-31 10:37  软件开发总结  阅读(289)  评论(0编辑  收藏  举报