【PowerShell】PowerShellでAES暗号化・復号化ツールを作る

技術情報
技術情報

※Python版の実装はこちらの記事を参照してください。
Python版(AES暗号化・復号化ツール)

はじめに

本記事では、Windows環境で事前インストール不要で使える PowerShell版 AES 暗号化・復号化ツールを解説します。
Python版との互換性もあり、Pythonで暗号化した文字列をPowerShellで復号することも可能です。

1. 暗号化ツールの仕様

Python版と同様です。

2. 検証環境

  • OS: Windows 11
  • PowerShell: バージョン 5.x 以上(Windows標準搭載)
  • ライブラリ: Windows標準の .NET クラス [System.Security.Cryptography.Aes] を使用
  • 実行方法: コマンドプロンプト、VSCodeターミナル、バッチ実行可
  • 注意点:
    • スクリプトは UTF-8 BOM で保存すること
    • キーや文字列の入力はコンソールから行う

3. PowerShell版のメリット

  • Windows標準搭載の PowerShell で動作するため、Pythonのようなインストールやライブラリ管理が不要
  • バッチファイルからワンクリックで実行可能
  • Python版と同じ OpenSSL互換形式で暗号化・復号化が可能

4. 実装

4.1. PowerShellファイル

encrypt_tool.ps1

# 鍵導出(OpenSSL互換)
function DeriveKeyAndIV {
    param(
        [byte[]]$Salt,
        [string]$Password,
        [int]$KeyLength = 32,
        [int]$IVLength = 16
    )

    $digest = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
    $previous = @()
    $output = @()

    while ($output.Length -lt ($KeyLength + $IVLength)) {
        if ($previous.Length -eq 0) {
            $data = [System.Text.Encoding]::ASCII.GetBytes($Password) + $Salt
        } else {
            $data = $previous + [System.Text.Encoding]::ASCII.GetBytes($Password) + $Salt
        }
        $hash = $digest.ComputeHash($data)
        $output += $hash
        $previous = $hash
    }

    $key = $output[0..($KeyLength-1)]
    $iv  = $output[$KeyLength..($KeyLength+$IVLength-1)]
    return @($key, $iv)
}

function Encrypt-String {
    param(
        [string]$PlainText,
        [string]$Password
    )

    # Salt 8バイト
    $salt = New-Object byte[] 8
    [System.Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($salt)

    # 鍵とIV
    $keyiv = DeriveKeyAndIV -Salt $salt -Password $Password
    $key = $keyiv[0]
    $iv  = $keyiv[1]

    $aes = [System.Security.Cryptography.Aes]::Create()
    $aes.Key = $key
    $aes.IV  = $iv
    $aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
    $aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7

    $encryptor = $aes.CreateEncryptor()
    $plainBytes = [System.Text.Encoding]::UTF8.GetBytes($PlainText)
    $cipherBytes = $encryptor.TransformFinalBlock($plainBytes, 0, $plainBytes.Length)

    # OpenSSL形式 "Salted__" + salt + ciphertext
    $resultBytes = [System.Text.Encoding]::ASCII.GetBytes("Salted__") + $salt + $cipherBytes
    return [Convert]::ToBase64String($resultBytes)
}

function Decrypt-String {
    param(
        [string]$CipherText,
        [string]$Password
    )

    $raw = [Convert]::FromBase64String($CipherText)

    # "Salted__" 8バイト + Salt 8バイト
    $header = $raw[0..7]
    $salt   = $raw[8..15]
    $cipherBytes = $raw[16..($raw.Length-1)]

    # 鍵とIV
    $keyiv = DeriveKeyAndIV -Salt $salt -Password $Password
    $key = $keyiv[0]
    $iv  = $keyiv[1]

    $aes = [System.Security.Cryptography.Aes]::Create()
    $aes.Key = $key
    $aes.IV  = $iv
    $aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
    $aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7

    $decryptor = $aes.CreateDecryptor()
    $plainBytes = $decryptor.TransformFinalBlock($cipherBytes, 0, $cipherBytes.Length)
    return [System.Text.Encoding]::UTF8.GetString($plainBytes)
}

# ----------------------------
# メイン処理
# ----------------------------
$mode = Read-Host "暗号化する場合は e、復号化する場合は d を入力してください"
$password = Read-Host "キーを入力してください"
$target = Read-Host "対象文字列を入力してください"

try {
    if ($mode -eq "e") {
        Write-Host "`n暗号化結果:"
        $encrypted = Encrypt-String -PlainText $target -Password $password
        Write-Host $encrypted
    }
    elseif ($mode -eq "d") {
        Write-Host "`n復号化結果:"
        $decrypted = Decrypt-String -CipherText $target -Password $password
        Write-Host $decrypted
    }
    else {
        Write-Host "e または d を入力してください。"
    }
}
catch {
    Write-Host $("エラー: " + $_.Exception.Message)
}

4.2. Batファイル

run.bat

@echo off
powershell -ExecutionPolicy Bypass -File "%~dp0encrypt_tool.ps1"
pause

5. 実行例

Python版と同様です。

6. まとめ

  • PowerShell版は 事前インストール不要でWindows標準だけで動作
  • Python版と互換性があり、どちらで暗号化しても復号化可能
  • UTF-8 BOM 形式で保存することで、日本語文字列や文字列終端エラーを回避できる
  • バッチファイルと組み合わせるとワンクリックで暗号化・復号化可能

💡 おすすめポイント

  • 環境構築の手間を省きたい場合 → PowerShell版
  • 高度なカスタマイズや他言語との統合 → Python版

タイトルとURLをコピーしました