C# DES 加密、解密

170次阅读
没有评论

共计 1565 个字符,预计需要花费 4 分钟才能阅读完成。

DES 加密、解密
/// <summary>
/// DES 加密字符串
/// </summary>
/// <param name="pToEncrypt"> 待加密的字符串 </param>
/// <param name="sKey"> 加密密钥, 要求为 8 位 </param>
/// <returns> 加密成功返回加密后的字符串,失败返回源串 </returns>
public static string DesEncrypt(string pToEncrypt, string sKey)
{StringBuilder ret = new StringBuilder();
     try
     {DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
         des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         foreach (byte b in ms.ToArray())
         {ret.AppendFormat("{0:X2}", b);
         }
         return ret.ToString();}
     catch
     {return pToEncrypt;}
}
/// <summary>
/// DES 解密字符串
/// </summary>
/// <param name="pToDecrypt"> 待解密的字符串 </param>
/// <param name="sKey"> 解密密钥, 要求为 8 位, 和加密密钥相同 </param>
/// <returns> 解密成功返回解密后的字符串,失败返源串 </returns>
public static string DesDecrypt(string pToDecrypt, string sKey)
{MemoryStream ms = new MemoryStream();
     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(sKey);
         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         return System.Text.Encoding.Default.GetString(ms.ToArray());
     }
     catch
     {return pToDecrypt;}
}

正文完
 0
flames
版权声明:本站原创文章,由 flames 于2021-01-17发表,共计1565字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)