8位秘钥的des加密解密

 

public static string Encrypt(string str, string sKey, string iv)
{
string result = string.Empty;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(str);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(iv);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder sb = new StringBuilder();
foreach (byte b in ms.ToArray())
{
sb.AppendFormat("{0:X2}", b);
}
result = sb.ToString();
}
catch (Exception ex)
{

}
return result;
}

 

 


public static string Decrypt(string str, string sKey, string iv)
{
string result = string.Empty;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[str.Length / 2];
for (int x = 0; x < str.Length / 2; x++)
{
int i = (Convert.ToInt32(str.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(iv);
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();
result = Encoding.Default.GetString(ms.ToArray());
}
catch (Exception ex)
{

}
return result;
}

posted @ 2021-01-12 14:25  心随风动-  阅读(924)  评论(0)    收藏  举报