Unicode 到 ASCII 在字符之间放置空格

Unicode to ASCII is putting spaces in between chars

我有这个脚本来加密和解密文本。

为什么将解密的文本字节数组转换为ASCII时,每个字符之间有一个space?

#Encrypt:

$unencryptedData = "passwordToEncrypt"

$pfxPassword = "P@ssw0rd1"
$certLocation = "D:\Ava\CA\Scripts\Encryption\PFXfiles\f-signed.pfx"
$cert = New-Object 'System.Security.Cryptography.X509Certificates.X509Certificate2'($certLocation, $pfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$publicKey = $cert.PublicKey.Key.ToXmlString($false)
$privateKey = $cert.PrivateKey.ToXmlString($true)

$unencryptedDataAsByteArray = [System.Text.Encoding]::Unicode.GetBytes($unencryptedData)

$keySize = 16384
$rsaProvider = New-Object System.Security.Cryptography.RSACryptoServiceProvider($keySize)
$rsaProvider.FromXmlString($publicKey)

$encryptedDataAsByteArray = $rsaProvider.Encrypt($unencryptedDataAsByteArray, $false)

$encryptedDataAsString = [System.Convert]::ToBase64String($encryptedDataAsByteArray)
Write-Host "Encrypted password = $encryptedDataAsString"

#Decrypt:
$rsaProvider.FromXmlString($privateKey)
$encryptedDataAsByteArray = [System.Convert]::FromBase64String($encryptedDataAsString)
$decryptedDataAsByteArray = $rsaProvider.Decrypt($encryptedDataAsByteArray, $false)
$decryptedDataAsString = [System.Text.Encoding]::ASCII.GetString($decryptedDataAsByteArray) 
###### "p a s s w o r d T o E n c r y p t " ###### 
#$decryptedDataAsString = [System.Text.Encoding]::Unicode.GetString($decryptedDataAsByteArray) 
###### "passwordToEncrypt" ###### 

Write-Host "Decrypted password = $decryptedDataAsString"

咨询Character Encodings in the .NET Framework[System.Text.Encoding]::Unicode 是 UTF-16LE,因此字符 A 被编码为 16 位值 0x0041,字节 0x41 0x00[System.Text.Encoding]::ASCII 是一种 8 位编码,因此当您使用 ASCII 解码 0x41 0x00 时,您会得到字符 ANUL(不是 space).

您必须使用与编码相同的编码对字节数组进行解码。

行中:

$unencryptedDataAsByteArray = [System.Text.Encoding]::Unicode.GetBytes($unencryptedData)

您正在将未加密的字节数组设置为 Unicode 字符串。这意味着字符串中的每个字符在数组中占 2 个字节。后面解密的时候,还是2个字节一个字符。

你需要逆序解密回来。首先,将其解密回 Unicode。然后,如果您需要转到 ASCII,请使用 .Net Encoding.Convert 方法之一。