ConvertTo SecureString - PowerShell
Overview
ConvertTo-SecureString converts a plaintext string into a secure string object. Secure strings are commonly used to store sensitive data, such as passwords and other credentials, in a secure manner within PowerShell scripts and sessions.
Syntax
ConvertTo-SecureString [-String] <string> [-AsPlainText] [-Force] [-Key <byte[]>]
Options/Flags
- -String: Specifies the plaintext string to convert into a secure string. Required.
- -AsPlainText: Returns the secure string as a plaintext string. Use with caution as this exposes sensitive data.
- -Force: Suppresses any error messages if the input string is invalid.
- -Key: Specifies an optional byte array to use as the encryption key. If not specified, a random key is generated.
Examples
Simple Conversion
$securePwd = ConvertTo-SecureString -String "MySuperSecretPassword"
Using -AsPlainText
Warning: Only use -AsPlainText
if necessary as it exposes the secure string.
$plaintextPwd = ConvertTo-SecureString -String "MyPassword" -AsPlainText
Suppressing Errors
# Convert an invalid string without displaying errors
ConvertTo-SecureString -String "Invalid String" -Force
Using Custom Encryption Key
# Generate a random byte array for the encryption key
$key = [Convert]::FromBase64String((New-Object Byte[] 32).ToString())
# Convert the string using the custom key
$securePwd = ConvertTo-SecureString -String "EncryptedPassword" -Key $key
Common Issues
- Invalid Input: Input must be a string. Non-string input will result in an error. Use
-Force
to suppress errors if necessary. - Key Length Errors: The
-Key
parameter requires a byte array of length 32. Using an incorrect length will cause an error.
Integration
ConvertTo-SecureString can be used with other PowerShell commands and tools to enhance data security. For example:
- Write-Output: Write the secure string to the console without revealing its plaintext value.
ConvertTo-SecureString -String "MyPassword" | Write-Output
- Set-Content: Write the secure string to a file, encrypted using the specified key.
ConvertTo-SecureString -String "MyPassword" -Key $key | Set-Content -Path "MySecureFile.txt"
Related Commands
- ConvertFrom-SecureString: Converts a secure string back to a plaintext string.
- Set-Credential: Creates a new credential object with a secure password.