check the string is Base64 encoded in PowerShell

岁酱吖の 提交于 2021-01-19 11:16:46

问题


I am using PowerShell to make a condition selection, need to judge whether the string is Base64 encoded,

What is the easiest and most direct way?

            if ($item -is [?base64])
            {
                # handle strings or characters
            }

回答1:


The following returns $true if $item contains a valid Base64-encoded string, and $false otherwise:

try { $null=[Convert]::FromBase64String($item); $true } catch { $false }
  • The above uses System.Convert.FromBase64String to try to convert input string $item to the array of bytes it represents.

  • If the call succeeds, the output byte array is ignored ($null = ...), and $true is output.

  • Otherwise, the catch block is entered and $false is returned.

Caveat: Even regular strings can accidentally be technically valid Base64-encoded strings, namely if they happen to contain only characters from the Base64 character set and the character count is a multiple of 4. For instance, the above test yields $true for "word" (only Base64 chars., and a multiple of 4), but not for "words" (not multiple of 4 chars.)


For example, in the context of an if statement:

  • Note: In order for a try / catch statement to serve as an expression in the if conditional, $(), the subexpression operator, must be used.
# Process 2 sample strings, one Base64-encoded, the other not.
foreach ($item in 'foo', 'SGFwcHkgSG9saWRheXM=') {

  if ($(try { $null=[Convert]::FromBase64String($item); $true } catch { $false })) {
    'Base64-encoded: [{0}]; decoded as UTF-8: [{1}]' -f
       $item,
       [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($item))
  }
  else {
    'NOT Base64-encoded: [{0}]' -f $item
  }

}

The above yields:

NOT Base64-encoded: [foo]
Base64-encoded: [SGFwcHkgSG9saWRheXM=]; decoded as UTF-8: [Happy Holidays]

It's easy to wrap the functionality in a custom helper function, Test-Base64:

# Define function.
# Accepts either a single string argument or multiple strings via the pipeline.
function Test-Base64 {
  param(
    [Parameter(ValueFromPipeline)] 
    [string] $String
  )
  process {
    try { $null=[Convert]::FromBase64String($String); $true } catch { $false }
  }
}

# Test two sample strings.
foreach ($item in 'foo', 'SGFwcHkgSG9saWRheXM=') {
  if (Test-Base64 $item) {
    "YES: $item"
  }
  else {
    "NO: $item"
  }
}

For information on converting bytes to and from Base64-encoded strings, see this answer.



来源:https://stackoverflow.com/questions/65456657/check-the-string-is-base64-encoded-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!