TripleDES加解密,解决解密后字符缺失问题
不然解密后字符和加密前的字符可能存在不一致
using System.Security.Cryptography;
using System.Text;
namespace TripleDES.Expand
{
public static class TripleDESClass
{
const string defaultKey = "*************************";
const string defaultIV = "********";
/// <summary>
/// 加密
/// </summary>
/// <param name="text"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string EncryptText(string text, string key = defaultKey, string iv = defaultIV)
{
try
{
var data = EncryptTextToMemory(text, Convert.FromBase64String(key), Convert.FromBase64String(iv));
return Convert.ToBase64String(data);
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="text"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string DecryptText(string text, string key = defaultKey, string iv = defaultIV)
{
try
{
var array = Convert.FromBase64String(text);
return DecryptTextFromMemory(array, Convert.FromBase64String(key), Convert.FromBase64String(iv));
}
catch (Exception )
{
return string.Empty;
}
}
public static void Sample()
{
try
{
// Create a new TripleDES object to generate a key
// and initialization vector (IV). Specify one
// of the recognized simple names for this
// algorithm.
TripleDES TripleDESalg = TripleDES.Create("TripleDES");
// Create a string to encrypt.
string sData = "Here is some data to encrypt.";
// Encrypt the string to an in-memory buffer.
byte[] Data = EncryptTextToMemory(sData, TripleDESalg.Key, TripleDESalg.IV);
// Decrypt the buffer back to a string.
string Final = DecryptTextFromMemory(Data, TripleDESalg.Key, TripleDESalg.IV);
// Display the decrypted string to the console.
Console.WriteLine(Final);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
// Create a new TripleDES object.
TripleDES tripleDESalg = TripleDES.Create();
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(mStream,
tripleDESalg.CreateEncryptor(Key, IV),
CryptoStreamMode.Write);
// Convert the passed string to a byte array.
byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
// 不足8个字节倍数补空字节,预防不足8字节倍数解码后缺失数据问题
var flushLength = toEncrypt.Length % 8;
if (flushLength != 0)
{
var toEncryptList = toEncrypt.ToList();
toEncryptList.AddRange(new byte[8 - flushLength]);
toEncrypt = toEncryptList.ToArray();
}
// Write the byte array to the crypto stream and flush it.
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
private static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream(Data);
// Create a new TripleDES object.
TripleDES tripleDESalg = TripleDES.Create();
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
tripleDESalg.CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[Data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
// Close the streams.
csDecrypt.Close();
msDecrypt.Close();
//Convert the buffer into a string and return it.
//移除空白字节
return new ASCIIEncoding().GetString(fromEncrypt).TrimEnd('\0');
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
}
}