Suppose I have a string:
"password"
And it may be in the form of an encrypted secure string converted to text. This secure string text may be decrypted via ConvertFrom-SecureString
to recover the "password":
"1213132131....1232131" | ConvertFrom-SecureString |%{echo $_}
password
Is there any way to have powershell tell me whether the input string is already decrypted?
Or do I need to devise some other way to tell whether the input string is in plain text or encrypted as a secure string?
Caveat:
[securestring]
in new projects is discouraged, because it offers very little protection on Unix-like platforms and only limited protection on Windows. See this .NET platform-compatibility recommendation and this answer.You can infer whether the string is encrypted or not based on whether applying ConvertTo-SecureString
to it succeeds or not:
# Sample input string, already decrypted.
$str = 'hello'
$isEncrypted =
$null -ne (
$secureString = try { $str | ConvertTo-SecureString -ErrorAction Stop }
catch { }
)
If the string is encrypted - i.e. if it is the serialized form of a [securestring]
instance obtained with ConvertFrom-SecureString
- $secureString
is assigned the deserialized form (i.e. a [securestring]
instance).
Note that - by security-minded design - ConvertTo-SecureString
only works if a given serialized-from-[securestring]
input string was serialized by the same user account.