对同一个字符串加解密时,密钥要相同
//加密,其中,encryptString:代表要加密的字符串,encryptKey:相当于密匙,就是8个数字的组合
public string EncryptDES(string encryptString, string encryptKey)
{try
{
byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] rgbKey = System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(encryptString);
System.Security.Cryptography.DESCryptoServiceProvider dCSP = new System.Security.Cryptography.DESCryptoServiceProvider();
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch (Exception ex)
{
return encryptString;
}
}
//解密密,其中,encryptString:代表要解密的字符串,encryptKey:相当于密匙,就是8个数字的组合
{
if (decryptString == "")
return "";
try
{
byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] rgbKey = System.Text.Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
System.Security.Cryptography.DESCryptoServiceProvider DCSP = new System.Security.Cryptography.DESCryptoServiceProvider();
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return System.Text.Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return "";
}
}