2015-03-19 62 views
0

我想解密一些文本。 我能夠解密來自文件的文本,但是當我複製該文件的內容並將其直接放入字符串中時,它不起作用,因爲字節數組稍有不同。從字符串vs文件創建字節數組

如何從一個字符串中獲得一個字節數組,該字符串與從包含該字符串的文件中讀取時是相同的字節數組?

這是我的代碼:

$privateKeyFile = [System.IO.FileInfo]'D:\Avanade\CBA\Scripts\Encryption\Keys\cba.private.xml' 
$privateKey = [System.IO.File]::OpenText($($privateKeyFile.FullName)).ReadToEnd() 

$rsaProvider = New-Object System.Security.Cryptography.RSACryptoServiceProvider 
$rsaProvider.FromXmlString($privateKey) 

$encryptedData = 'ꨢﻥ睚紫震እ�풽꞊偓䷨頽ױ㻮앚튛堏焞娌젣래核儝쪅元㝂㢚覰齉c㑥㰺ᨅ㵉ァ鐶鄒꽋荺眢ꢈ쑷絓�ꮹ櫳ハ壠懻惜䡠덟蓩癱㙉ਧ騰י聗�၁틽ᮿ싓㈧ハ腰瑦ꊕ媘겻轄庖甏ܫ桑敘옐餈꿎請쌝⢸蒺銟஦ᩅ캼Շ疑ꊽ�䐼ꀑ醾耣咞䏎帾힆纄܏㎡㨇괎ꆠ䵢싐쇢綻굈ữ禘' 
$encryptedDataAsByteArray1 = [System.Text.Encoding]::UniCode.GetBytes($encryptedData) #this byte array does NOT work 

$FileToDecrypt = [System.IO.FileInfo]'D:\Avanade\CBA\Scripts\Encryption\d.txt.encrypted' #this has the same text as $encryptedData 
$encryptedFile = [System.IO.File]::OpenRead($($FileToDecrypt.FullName)) 
$encryptedDataAsByteArray = New-Object System.Byte[] $encryptedFile.Length #This byte array works 
$encryptedFile.Read($encryptedDataAsByteArray, 0, $encryptedFile.Length) 
$encryptedFile.Close() 

for ($i = 0; $i -lt $encryptedDataAsByteArray1.Count; $i++) 
{ 
    if ($encryptedDataAsByteArray1[$i] -ne $encryptedDataAsByteArray[$i]) 
    { 
     Write-Host "Byte $i is not the same" 
     Write-Host "$($encryptedDataAsByteArray1[$i]) and $($encryptedDataAsByteArray[$i])" 
    } 
} 

$decryptedDataAsByteArray = $rsaProvider.Decrypt($encryptedDataAsByteArray, $false) 

<# 
Comparison of the two byte arrays: 
Byte 12 is not the same 
253 and 47 
Byte 13 is not the same 
255 and 223 
Byte 92 is not the same 
253 and 179 
Byte 93 is not the same 
255 and 223 
Byte 132 is not the same 
253 and 127 
Byte 133 is not the same 
255 and 223 
Byte 204 is not the same 
253 and 67 
Byte 205 is not the same 
#> 

回答

0

應用基64編碼在文件中,例如使用諸如openssl命令行之類的實用程序。然後使用剪貼板將其複製到字符串中。最後,在應用程序中簡單地解碼它。

openssl base64 -in test.bin 

結果:

VGhlIHF1aWNrIGJyb3duIGZveCB3YXMganVtcGVkIGJ5IHRoZSBzbGVhenkgZG9n 
Lg== 

只需將它複製到一個字符串的問題是,你會得到字符編碼的問題。加密的字節可以具有任何值,包括控制字符和其他不可打印的字符。那些複製不好。

以下是如何encode/decode using powershell。請注意,如果(已經)處理字節,則不需要執行字符(UTF-8)編碼/解碼。

+0

謝謝這麼多! 我最終使用.NET中的Convert.ToBase64String,效果很好。 – 2015-03-19 00:57:57

+0

在.NET Convert類上使用openssl有什麼好處嗎? – 2015-03-19 00:58:32

+0

嘿,沒有。我剛剛遇到了這個問題,因爲加密標籤,我目前在Linux上。雖然這個想法是相同的。 – 2015-03-19 01:09:35