2015-05-21 83 views
0

我正在嘗試從Web服務讀取文件。該文件被加密,並且解密函數期望輸入(密文)作爲基本64編碼的字符串。下面的代碼執行,但我無法解密結果字符串。使用HttpWebResponse讀取文件數據

var request = (HttpWebRequest) WebRequest.Create(new Uri(_targetUrl)); 

request.Method = "GET"; 
request.ContentType = "text/plain"; 
request.ContentLength = 0; 
request.UseDefaultCredentials = true; 
request.Headers.Add("Ent-APRF:FileIdentifier"); 

var cfsResponse = (HttpWebResponse) request.GetResponse(); 

using (var rawResponseStream = cfsResponse.GetResponseStream()) 
{ 
if (rawResponseStream != null) 
    using (var content = new StreamReader(rawResponseStream, Encoding.GetEncoding(1252))) 
    { 
     using (var ms = new MemoryStream()) 
     { 
      content.BaseStream.CopyTo(ms); 
      var myBytes = ms.ToArray(); 

      var encrypteddata = Convert.ToBase64String(myBytes); 

      // call decrypt function suppling encrypted string 
     }   
    } 
} 

在該公司提供的Web服務的支持人員也給我發電子郵件相同的文件,我可以成功讀取文件和解密,使用下面的代碼。

using (StreamReader myFile = new StreamReader(@"C:\Encrypted_TEST", Encoding.GetEncoding(1252))) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     myFile.BaseStream.CopyTo(ms); 
     var myBytes = ms.ToArray(); 

     var encrypteddata = Convert.ToBase64String(myBytes); 

     // call decrypt function suppling encrypted string 
    } 
} 

我想知道如果編碼可能是問題,因爲當我打開通過電子郵件在記事本++編碼默認爲ANSI發送的文件。但是,如果我將Web調用的響應字節寫入文件並使用Notepad ++打開,則編碼默認爲帶有BOM的UTF-8。

我還包括經由的Fiddler捕獲完整性請求和響應..

請求

GET https://url HTTP/1.1 
Ent-APRF: FileIdentifier 
Host: hostName 
Connection: Keep-Alive

響應

HTTP/1.1 200 OK 
Date: Wed, 20 May 2015 23:51:17 GMT 
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 
Content-Length: 5767 
Set-Cookie: ssnid=1b7eea90ff4b11e48bb9dd1cd2992cd2; path=/; HttpOnly 
Keep-Alive: timeout=5, max=100 
Connection: Keep-Alive 

0�w *�H�� 
��h0�d1��0���0/0'1 
0 UUS10U 
...additional content body not included...

任何幫助或建議將不勝感激。

+0

其中顯示了您成功解密的代碼?..還顯示解密不成功的輸出在哪裏? – tharif

+0

第二個代碼塊顯示讀取電子郵件文件並導致成功解密。解密函數在一個單獨的C DLL中,所以我在其中包含註釋「//調用解密函數提供加密的字符串」是函數被調用的地方。當對該函數的調用不成功時,將返回一個空字符串。 – Mike

+0

實際上我在問輸出在哪裏顯示? – tharif

回答

0

提供服務的公司對文件生成和編碼進行了調整。我現在可以使用原始代碼獲取和解密。

var request = (HttpWebRequest) WebRequest.Create(new Uri(_targetUrl)); 

request.Method = "GET"; 
request.ContentType = "text/plain"; 
request.ContentLength = 0; 
request.UseDefaultCredentials = true; 
request.Headers.Add("Ent-APRF:FileIdentifier"); 

var cfsResponse = (HttpWebResponse) request.GetResponse(); 

using (var rawResponseStream = cfsResponse.GetResponseStream()) 
{ 
    if (rawResponseStream != null) 
    using (var content = new StreamReader(rawResponseStream, Encoding.GetEncoding(1252))) 
    { 
     using (var ms = new MemoryStream()) 
     { 
      content.BaseStream.CopyTo(ms); 
      var myBytes = ms.ToArray(); 

      var encrypteddata = Convert.ToBase64String(myBytes); 

      // call decrypt function suppling encrypted string 
     }   
    } 
}