2017-07-07 25 views
-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; 
    } 
} 

}

+0

好讓你檢查你傳遞的字符串?據推測,這不是有效的base64 ...我的猜測是,這不是以前調用'passwordEncrypt'的結果。 (我強烈建議你重新審視你的異常處理,順便說一句...這不是在C#中處理異常的慣用方法。) –

+0

https://stackoverflow.com/questions/11743160/how-do-i-encode -and-decode-a-base64-string –

+2

請發佈[mcve]以及您嘗試加密/解密的確切字符串。 –

回答

1

使用在下面的鏈接的簡單的解決方案解決了 How do I encode and decode a base64 string?

還在編碼函數中添加了一些代碼,以確保純文本字符串將被轉換爲有效長度的base64字符串。

代碼:

public static string Base64Encode(string plainText) 
{ 

      //check plain text string and pad if needed 
      int mod4 = plainText.Length % 4; 
      if (mod4 > 0) 
      { 
       plainText += new string('=', 4 - mod4); 
      } 

      //convert to base64 and return 
      var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); 
      return System.Convert.ToBase64String(plainTextBytes); 
     } 

     public static string Base64Decode(string base64EncodedData) 
     {   
      //decode base64 and return as string 
      var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); 
      return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); 
     } 
相關問題