0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

与えられた文字列がbase64でエンコードされたデータか調べるPowershellスクリプト

Posted at

元ネタ: Base64 かどうか判定する

ちなみに、これはChatGPDに投げたら作ってくれたものかつ、動作は適当にしか確認してないです。参考までに。

isBase64Stringl.ps1
# PowerShell版のB64Util
$decodeTable = @(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, # 00-0f
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, # 10-1f
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, # 20-2f + - /
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, # 30-3f 0-9
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, # 40-4f A-O
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, # 50-5f P-Z _
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, # 60-6f a-o
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51                      # 70-7a p-z
)

$b64pattern = "^[a-z0-9A-Z/\\+]+={1,2}$"

function isBase64Byte($octet) {
    return ($octet -eq 61) -or ($octet -ge 0 -and $octet -lt $decodeTable.Length -and $decodeTable[$octet] -ne -1)
}

function isWhiteSpace($byteToCheck) {
    return ($byteToCheck -eq [byte]' ') -or ($byteToCheck -eq [byte]'\n') -or ($byteToCheck -eq [byte]'\r') -or ($byteToCheck -eq [byte]'\t')
}

function isBase64([byte[]]$array) {
    if ($array -eq $null) { return $false }
    if ($array.Length -lt 1) { return $false }

    foreach ($byte in $array) {
        if (-not (isBase64Byte $byte) -and -not (isWhiteSpace $byte)) {
            return $false
        }
    }
    return $true
}

function isBase64String($str) {
    if ($str -eq $null) { return $false }
    return (isBase64 -array ($str.ToCharArray() | ForEach-Object { [byte]$_ })) -and ($str -match $b64pattern)
}

# 使用例
$base64Str = "ChlJrYAyuNdhGGARbBYOMDc4P7M=="
if (isBase64String($base64Str)) {
    Write-Host "与えられた文字列はBase64です。"
} else {
    Write-Host "与えられた文字列はBase64ではありません。"
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?