8位秘钥的des加密解密

 

/// <summary>
/// 八位秘钥加密方法
/// </summary>
/// <param name="pToEncrypt"></param>
/// <param name="sKey"></param>
/// <param name="iv"></param>
/// <returns></returns>

public static string Encrypt(string pToEncrypt, string sKey, string iv)
{
string result = string.Empty;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
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;
}

 

 

/// <summary>
/// 八位秘钥解密方法
/// </summary>
/// <param name="pToDecrypt"></param>
/// <param name="sKey"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string Decrypt(string pToDecrypt, string sKey, string iv)
{
string result = string.Empty;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.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;
}

上一篇:Crypto++ 开源加密使用笔记(1)(DES、AES、RSA、SHA-256)


下一篇:5.1 DES加密解密 -python 实现