Base64 is a transport encoding that is used to represent binary data and therefore any (relatively simple) data type.
Base64 is particularly useful when storing complex strings in files, or in text-based transport protocols such as SMTP.
The .NET class System.Convert contains static methods that can be used to work with base64:
- ToBase64String
- FromBase64String
Two further methods exist to work with character arrays, these are not discussed here.
The ToBase64String method takes an array of bytes and converts it into a string. For example, a simple byte array may be converted:
PS> [Byte[]]$bytes = 97, 98, 99, 100, 101
[Convert]::ToBase64String($bytes)
YWJjZGU=
A more meaningful byte sequence can be made from a few words by getting the byte values for each character:
PS> $bytes = [System.Text.Encoding]::ASCII.GetBytes('Hello world')
[Convert]::ToBase64String($bytes)
SGVsbG8gd29ybGQ=
The text encoding type used here is ASCII (1 byte per character), UTF16 text encoding will result in a longer Base64 string as each character is stored in two bytes:
PS> $bytes = [System.Text.Encoding]::Unicode.GetBytes('Hello world')
[Convert]::ToBase64String($bytes)
SABlAGwAbABvACAAdwBvAHIAbABkAA==
Converting from a base64 string to a sequence of bytes, then to a string may be achieved as follows:
PS> $base64String = 'YWJjZGU='
$bytes = [Convert]::FromBase64String($base64String)
[System.Text.Encoding]::ASCII.GetString($bytes)
abcde
Base64 may be a handy format for storing items such as keys (normally a set of bytes) for use with the ConvertTo-SecureString command. For example:
# Create a 16-byte key [Byte[]]$key = 1..16 | ForEach-Object { Get-Random -Minimum 0 -Maximum 256 } # Convert the key to a string and save it in a file [Convert]::ToBase64String($key) | Out-File 'KeepThisSafe.txt' # Create a secure string (from plain text) to encrypt $secure = ConvertTo-SecureString -String 'Secure text' -AsPlainText -Force # Encrypt the password using the key (from the file) $encrypted = ConvertFrom-SecureString -SecureString $secure -Key ([Convert]::FromBase64String((Get-Content .KeepThisSafe.txt))) # Decrypt the password using the same key $secure = ConvertTo-SecureString -String $encrypted -Key ([Convert]::FromBase64String((Get-Content .KeepThisSafe.txt))) # Show the original password (New-Object PSCredential('.', $secure)).GetNetworkCredential().Password