当我尝试解密我的加密密钥时,我收到一条错误消息,说明它的数据/数据不正确。试图搜索一会儿没有任何结果。这是加密代码和解密代码。 indata是用于加密的MAC地址,用于解密的indata是从文本文件中读取的。
public string encryptMAC(string indata)
{
byte[] resultCrypt;
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
byte[] encrypt = utf8.GetBytes(indata);
try
{
ICryptoTransform encryptor = tdes.CreateEncryptor();
resultCrypt = encryptor.TransformFinalBlock(encrypt, 0, encrypt.Length);
}
finally
{
tdes.Clear();
}
return Convert.ToBase64String(resultCrypt);
}
public string decryptMAC(string indata)
{
byte[] resultDecrypt;
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
byte[] decrypt = Convert.FromBase64String(indata);
try
{
ICryptoTransform decryptor = tdes.CreateDecryptor();
resultDecrypt = decryptor.TransformFinalBlock(decrypt, 0, decrypt.Length);
}
catch (CryptographicException ex)
{
Console.WriteLine(ex);
}
finally
{
tdes.Clear();
}
return utf8.GetString(decrypt);
}
答案 0 :(得分:0)
TripleDESCryptoServiceProvider
会为您生成一个密钥。如果您没有自己设置或在加密期间检索它,那么您将不能够解密密文。
我建议您为方法添加一个密钥,并使用相同的密钥进行加密和解密:
public string encryptMAC(string indata, byte[] key)
{
byte[] resultCrypt;
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
tdes.Key = key;
byte[] encrypt = utf8.GetBytes(indata);
try
{
ICryptoTransform encryptor = tdes.CreateEncryptor();
resultCrypt = encryptor.TransformFinalBlock(encrypt, 0, encrypt.Length);
}
finally
{
tdes.Clear();
}
return Convert.ToBase64String(resultCrypt);
}
public string decryptMAC(string indata, byte[] key)
{
byte[] resultDecrypt = new byte[0];
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
tdes.Key = key;
byte[] decrypt = Convert.FromBase64String(indata);
try
{
ICryptoTransform decryptor = tdes.CreateDecryptor();
resultDecrypt = decryptor.TransformFinalBlock(decrypt, 0, decrypt.Length);
}
catch (CryptographicException ex)
{
Console.WriteLine(ex);
}
finally
{
tdes.Clear();
}
return utf8.GetString(resultDecrypt);
}
请记住,DES有一小组弱键,因此您应该使用TripleDESCryptoServiceProvider
为您生成一个键,用于过滤掉这些弱键。您可以(new TripleDESCryptoServiceProvider()).Key
生成有效密钥。