C# 要解密的数据长度在c中无效#
在解密字符串时,调用FlushFinalBlock函数时,要解密的数据长度无效C# 要解密的数据长度在c中无效#,c#,encryption,C#,Encryption,在解密字符串时,调用FlushFinalBlock函数时,要解密的数据长度无效 key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); Byte[] byteArray = Convert.FromBase64String(text); MemoryStream memoryStream = new MemoryS
key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] byteArray = Convert.FromBase64String(text);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cryptoStream.Write(byteArray, 0, byteArray.Length);
cryptoStream.FlushFinalBlock();
return Encoding.UTF8.GetString(memoryStream.ToArray());
问题是什么以及如何解决?您没有说明字符串是如何加密的,您是否使用相同的密钥和IV等。。。下面是一个完整的工作示例,您可以根据您的场景进行调整:
class Program
{
private static byte[] DESKey = { 200, 5, 78, 232, 9, 6, 0, 4 };
private static byte[] DESInitializationVector = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static void Main()
{
var encrypted = Encrypt("foo bar");
Console.WriteLine(encrypted);
var decrypted = Decrypt(encrypted);
Console.WriteLine(decrypted);
}
public static string Encrypt(string value)
{
using (var cryptoProvider = new DESCryptoServiceProvider())
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(value);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
public static string Decrypt(string value)
{
using(var cryptoProvider = new DESCryptoServiceProvider())
using(var memoryStream = new MemoryStream(Convert.FromBase64String(value)))
using(var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(DESKey, DESInitializationVector), CryptoStreamMode.Read))
using(var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
你能看一下byteArray的长度吗?如果我没记错的话,DES应该是8的倍数。