我们有一些加密的xml文件,其中包含以下字符,例如: $¹QƨJiå•Á@ ܶĺµé)‰ï¦MSš¨íÄ;GfóûÇsHte;2Ð_。 谁能指导我们如何使用C#中的TripleDes算法解密此类文件内容。
答案 0 :(得分:0)
已经使用DES加密而不是三重DES,希望有帮助
提醒一下,DES是对称加密,这意味着单个密钥可用于加密和解密数据。 下面是如何使用DES加密和解密
创建资源文件并将其命名为CryptoKeys
将以下字符串添加到CryptoKeys文件中
DesVector:0x11, 0x45, 0x47, 0x61, 0x12, 0xbc, 0xad 0xfc:;
DesKey:0xff, 0x12, 0x63, 0xa, 0x16 0xcf, 0xaf, 0xfb;
创建静态类来管理加密和解密
public static class CryptoHelper
{
//Init the key and Vector
public static void InitDESKeys()
{
try
{
MemoryStream tempStream = new MemoryStream();
string[] charkey = Resources.CryptoKeys.DesKey.Split(',');
string[] chariv = Resources.CryptoKeys.DesVector.Split(',');
MemoryStream MemoryStreamkey = new MemoryStream(DesKey);
MemoryStream MemoryStreamiv = new MemoryStream(DesVector);
foreach (string item in charkey)
{
MemoryStreamkey.WriteByte(Convert.ToByte(item, 16));
}
foreach (string item in chariv)
{
MemoryStreamiv.WriteByte(Convert.ToByte(item, 16));
}
}
catch (Exception ex)
{
}
}
//Create function DESEncrypt to manage the encryption
public static string DESEncrypt(string sourceData)
{
try
{
byte[] sourceDataBytes = System.Text.Encoding.Unicode.GetBytes(sourceData);
MemoryStream tempStream = new MemoryStream();
DESCryptoServiceProvider encryptor = new DESCryptoServiceProvider();
CryptoStream encryptionStream = new CryptoStream(tempStream, encryptor.CreateEncryptor(DesKey, DesVector), CryptoStreamMode.Write);
encryptionStream.Write(sourceDataBytes, 0, sourceDataBytes.Length);
encryptionStream.FlushFinalBlock();
byte[] encryptedDataBytes = tempStream.GetBuffer();
return Convert.ToBase64String(encryptedDataBytes, 0, (int)tempStream.Length);
}
catch (Exception ex)
{
throw new Exception("Unable to encrypt data.");
}
}
//Create function DESDecrypt to manage the decryption
public static string DESDecrypt(string sourceData)
{
try
{
byte[] encryptedDataBytes = Convert.FromBase64String(sourceData);
MemoryStream tempStream = new MemoryStream(encryptedDataBytes, 0, encryptedDataBytes.Length);
DESCryptoServiceProvider decryptor = new DESCryptoServiceProvider();
CryptoStream decryptionStream = new CryptoStream(tempStream, decryptor.CreateDecryptor(DesKey, DesVector), CryptoStreamMode.Read);
byte[] bytesCryptedData = new byte[tempStream.Length];
decryptionStream.Read(bytesCryptedData, 0, (int)tempStream.Length);
var CryptedDataText = System.Text.Encoding.Unicode.GetString(bytesCryptedData);
return CryptedDataText;
}
catch (Exception ex)
{
throw new Exception("Unable to encrypt data.");
}
}
}
在主类中调用加密
static void Main(string[] args)
{
CryptoHelper.InitDESKeys();
string strText==Strin.Empty();
strText="Text to decrypt";
string encryptedText=CryptoHelper.DESEncrypt(strText);
string decryptedText=Strin.Empty();
decryptedText=CryptoHelper.DESDecrypt(strText);
}