C#DES加密类,16位的加密。

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#DES加密类,16位的加密。

这个加密类是与java写的DES加密不同时,⾃⼰写的,最后与Java的加密相同了,解决了加密后不同的问题。

可以直接调⽤⾥⾯的加密和解密的⽅法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EallNum.Helper
{
public class FI_DesTools
{
private FI_DesTools()
{
}
private static string key = "×××××";
///<summary>
///对称加密解密的密钥
///</summary>
public static string Key
{
get
{
return key;
}
set
{
key = value;
}
}
///<summary>
/// DES加密
///</summary>
///<param name="encryptString"></param>
///<returns></returns>
public static string DesEncrypt(string strEncryptString)
{
StringBuilder strRetValue = new StringBuilder();
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(strEncryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Mode = CipherMode.ECB;//兼容其他语⾔的Des加密算法
provider.Padding = PaddingMode.Zeros;//⾃动补0
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
//不使⽤base64编码
//return Convert.ToBase64String(mStream.ToArray());
//组织成16进制字符串
foreach (byte b in mStream.ToArray())
{
strRetValue.AppendFormat("{0:X2}", b);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return strRetValue.ToString();
}
///<summary>
/// DES解密
///</summary>
///<param name="decryptString"></param>
///<returns></returns>
public static string DesDecrypt(string strDecryptString)
{
string strRetValue = "";
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
//不使⽤base64解码
//byte[] inputByteArray = Convert.FromBase64String(decryptString);
//16进制转换为byte字节
byte[] inputByteArray = new byte[strDecryptString.Length / 2];
for (int x = 0; x < strDecryptString.Length / 2; x++)
{
int i = (Convert.ToInt32(strDecryptString.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Mode = CipherMode.ECB;//兼容其他语⾔的Des加密算法
provider.Padding = PaddingMode.Zeros;//⾃动补0
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
//需要去掉结尾的null字符
//strRetValue = Encoding.UTF8.GetString(mStream.ToArray());
strRetValue = Encoding.UTF8.GetString(mStream.ToArray()).TrimEnd('\0');
}
catch (Exception e)
{
Console.WriteLine(e);
}
return strRetValue;
}
}
}。

相关文档
最新文档