sealed public class CryptoHelper
{
///
/// Encrypts the specified input.
/// ///
The input.
///
key
///
iv
///
public static string EncryptDes(string input, byte[] key, byte[] iv)
{
if (input == null || input.Length == 0)
return String.Empty;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = null;
CryptoStream encStream = null;
StreamWriter sw = null;
string result = String.Empty;
try
{
ms = new MemoryStream();
// Create a CryptoStream using the memory stream and the
// CSP DES key.
//des.Mode = CipherMode.CBC;
//des.Padding = PaddingMode.PKCS7;
encStream = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
// Create a StreamWriter to write a string
// to the stream.
sw = new StreamWriter(encStream);
// Write the plaintext to the stream.
sw.Write(input);
sw.Flush();
encStream.FlushFinalBlock();
ms.Flush();
result = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length, CultureInfo.InvariantCulture));
}
finally
{
//close objects
if (sw != null)
sw.Close();
if (encStream != null)
encStream.Close();
if (ms != null)
ms.Close();
}
// Return the encrypted string
return result;
}
///
/// Decrypts the specified input.
/// ///
the input.
///
key
///
iv
///
public static string DecryptDes(string input, byte[] key, byte[] iv)
{
byte[] buffer;
try { buffer = Convert.FromBase64String(input); }
catch (System.ArgumentNullException) { return String.Empty; }
// length is zero, or not an even multiple of four (plus a few other cases)
catch (System.FormatException) { return String.Empty; }
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = null;
CryptoStream encStream = null;
StreamReader sr = null;
string result = String.Empty;
try
{
ms = new MemoryStream(buffer);
// Create a CryptoStream using the memory stream and the
// CSP DES key.
encStream = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
sr = new StreamReader(encStream);
// Read the stream as a string.
result = sr.ReadToEnd();
}
finally
{
//close objects
if (sr != null)
sr.Close();
if (encStream != null)
encStream.Close();
if (ms != null)
ms.Close();
}
return result;
}
}
//调用
string key = "abcdefgh";
string iv = "abcdefgh";
string msg="test string";
string rs1 = CryptoHelper.EncryptDes(msg, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));
string rs2 = CryptoHelper.DecryptDes(rs1, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));