解密数据的长度是在C#无效 [英] length of the data to decrypt is invalid in c#
本文介绍了解密数据的长度是在C#无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在解密的字符串我得到的数据的长度来解密无效错误,当我打电话FlushFinalBlock功能
While decrypting a string I am getting length of the data to decrypt is invalid error when i call FlushFinalBlock function
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());
什么问题,如何解决?
what is the issue and how to resolve it?
推荐答案
,你没有表现出你是否使用相同的密钥和IV等字符串的加密方式......这是一个完整的工作例如,你可以适应您的方案
You didn't show how is the string encrypted, whether you are using the same keys and IV, etc... Here's a full working example you could adapt to your scenario:
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();
}
}
}
这篇关于解密数据的长度是在C#无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文