-1
我試圖使用base64加密和解密一個字符串,但我收到一個當我嘗試解密字符串。c#base64 encrpytion。 decrpytion上的無效長度錯誤
我收到的錯誤是:
{System.FormatException:用於基本-64字符數組或串無效長度。
在這條線在下面的解密函數:
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
Encrpyt /解密功能:
//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(inString);
sw.Flush();
cs.FlushFinalBlock();
sw.Flush();
outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
return false;
}
}
//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;};
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
outstring = sr.ReadToEnd();
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
return false;
}
}
}
好讓你檢查你傳遞的字符串?據推測,這不是有效的base64 ...我的猜測是,這不是以前調用'passwordEncrypt'的結果。 (我強烈建議你重新審視你的異常處理,順便說一句...這不是在C#中處理異常的慣用方法。) –
https://stackoverflow.com/questions/11743160/how-do-i-encode -and-decode-a-base64-string –
請發佈[mcve]以及您嘗試加密/解密的確切字符串。 –