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

时间:2015-03-19 02:50:52

标签: powershell encryption unicode encoding ascii

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

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

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

2 个答案:

答案 0 :(得分:3)

咨询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(不是空格)。

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

答案 1 :(得分:2)

在行中:

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

您正在将未加密的字节数组设置为Unicode字符串。这意味着对于字符串中的每个字符,数组中有2个字节。当它稍后被解密时,每个字符仍然是2个字节。

您需要以相反的顺序对其进行解密。首先,将其解密回Unicode。然后,如果您需要转到ASCII,请使用.Net Encoding.Convert方法之一。

相关问题