2015-03-19 63 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