check the string is Base64 encoded in PowerShell

后端 未结 1 775
温柔的废话
温柔的废话 2021-01-17 02:25

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?

              


        
相关标签:
1条回答
  • 2021-01-17 03:07

    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.

    0 讨论(0)
提交回复
热议问题