解码/解密期间Base-64字符数组的长度无效

问:我面临以下大问题:

从时间到另一个我发现以下exception:

Base-64 char数组的长度无效

我使用加密和解密:

public static string Encrypt(string text) { try { key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); Byte[] byteArray = Encoding.UTF8.GetBytes(text); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream,des.CreateEncryptor(key, IV), CryptoStreamMode.Write); cryptoStream.Write(byteArray, 0, byteArray.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(memoryStream.ToArray()); } catch (Exception ex) { string message = ex.Message; } return string.Empty; } public static string Decrypt(string text) { try { key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); text = text.Replace(" ", "+") 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()); } catch (Exception ex) { string message = ex.Message; } 

我读了许多关于这个问题的文章,一些post谈论的解决方案是:

text = text.Replace(" ", "+")这根本不能解决我的问题

我的字符串是: 3DZF/NZpp0yuQ=3D请我需要帮助来解决这个问题。

编辑

  • 如果对本课程进行任何修改或改进以使其更好或更安全或避免任何可能的问题,我将不胜感激。
  • 如果有交替的课程而不是这个,更安全,不会出现这些问题,我将不胜感激。
  • 我在用于validation邮件的小应用程序中使用此类。

编辑:

 Decoding the querystring values is done already when it's parsed into the Request. 

https://stackoverflow.com/a/10879400/418343

要解决所需的问题,请先编码然后解码所有就绪的encode-base64字符串,这取决于您使用它的位置。

例如,如果您在url(或查询)上使用它,可能这是您要使用的地方,那么您需要在使用之前对URL进行编码,在获取URL之前对其进行解码。 原因是您需要避免将URL用作代码字符的相同字符与加密字符混合使用。

无论如何这里是解决你的问题的代码(我使用相同的原因):

 public static string encodeSTROnUrl(string thisEncode) { if (null == thisEncode) return string.Empty; return HttpUtility.UrlEncode(Encrypt(thisEncode)); } public static string decodeSTROnUrl(string thisDecode) { return Decrypt(HttpUtility.UrlDecode(thisDecode)); } 

ps我有同样的问题,并尝试替换’+’和其他,但最后这是它的工作原理。

不要忘记从代码中删除text = text.Replace(“”,“+”)和其他加密操作,只需加密和解密即可。

 string imag = img; imag = imag.Replace("\", ""); int c = imag.Length % 4; if ((c) != 0) imag = imag.PadRight((imag.Length + (4 - c)), "="); [] converted = Convert.FromBase64String(imag); using (System.IO.MemoryStream vstream = new System.IO.MemoryStream(converted)) { return Image.FromStream(vstream); }