![[Image: oKTRsJt.gif]](https://i.imgur.com/oKTRsJt.gif)
Here are 3 of the most common ways to encode/decode a string in powershell. Each example has an encode and decode function, as well as an example to show you how to use it.
[BASE64 ENCODING/DECODING]
Code
function Convert-StringToBase64() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$baseEncoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stringIn))
return $baseEncoded
}
function Convert-Base64ToString() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$decodedString = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($stringIn))
return $decodedString
}
# Usage:
$plainText = 'https://the.earth.li/~sgtatham/putty/latest/w64/putty.exe'
$encodedText = Convert-StringToBase64 $plainText
Write-Host $encodedText
$decodedText = Convert-Base64ToString $encodedText
Write-Host $decodedText[BINARY ENCODING/DECODING]
Code
function Convert-StringToBinary() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$stringBytes = [System.Text.Encoding]::UTF8.GetBytes($stringIn)
$binaryArray = $stringBytes | ForEach-Object {[System.Convert]::ToString($_, 2).PadLeft(8, '0')}
$binaryString = $binaryArray -join('')
return $binaryString
}
function Convert-BinaryToString() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$arrayIndex = 0
$bytesArray = New-Object System.Collections.ArrayList
while($arrayIndex -lt $stringIn.Length) {
$binarySection = $stringIn.Substring($arrayIndex, 8)
$binaryBytes = [System.Convert]::ToByte($binarySection, 2)
$bytesArray.Add($binaryBytes) | Out-Null
$arrayIndex += 8
}
$decodedString = [System.Text.Encoding]::UTF8.GetString($bytesArray.ToArray())
return $decodedString
}
# Usage:
$plainText = 'https://the.earth.li/~sgtatham/putty/latest/w64/putty.exe'
$encodedText = Convert-StringToBinary $plainText
Write-Host $encodedText
$decodedText = Convert-BinaryToString $encodedText
Write-Host $decodedText[HEX ENCODING/DECODING]
Code
function Convert-StringToHex() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$hexEncoded = ''
$stringIn.ToCharArray() | ForEach-Object -Process {
$hexEncoded += '{0:x}' -f [int][char]$_
}
return $hexEncoded
}
function Convert-HexToString() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $rawHexString
)
$decodedString = ''
for($stringIndex = 0; $stringIndex -lt $rawHexString.Length; $stringIndex += 2) {
$decodedString += [char][int]("0x" + $rawHexString.Substring($stringIndex,2))
}
return $decodedString
}
# Usage:
$plainText = 'https://the.earth.li/~sgtatham/putty/latest/w64/putty.exe'
$encodedText = Convert-StringToHex $plainText
Write-Host $encodedText
$decodedText = Convert-HexToString $encodedText
Write-Host $decodedText

![[Image: main.gif]](https://i.ibb.co/W2WKpzj/main.gif)

![[Image: main.gif]](https://i.ibb.co/MZkhhV6/main.gif)