从字符串创建字节数组与从文件创建字节数组

Creating byte array from string vs from file

我正在尝试解密一些文本。 我能够从文件中解密文本,但是当我复制该文件的内容并将其直接放入字符串中时,它不起作用,因为字节数组略有不同。

如何从字符串中获取字节数组,该字节数组与从包含该字符串的文件中读取时的字节数组相同?

这是我的代码:

$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
#>

对文件应用 base 64 编码,例如使用诸如 openssl 命令行之类的实用程序。然后使用剪贴板将其复制到字符串中。最后,只需在应用程序中对其进行解码即可。

openssl base64 -in test.bin

结果:

VGhlIHF1aWNrIGJyb3duIGZveCB3YXMganVtcGVkIGJ5IHRoZSBzbGVhenkgZG9n
Lg==

仅将其复制到字符串中的问题是您会遇到字符编码问题。加密字节可以有任何值,包括控制字符和其他不可打印的字符。那些不会很好地复制。

encode/decode using powershell 的方法如下。请注意,如果您(已经)处理字节,则不需要执行字符 (UTF-8) encoding/decoding。