Created
October 21, 2024 14:59
-
-
Save shiguruikai/d1da664085b01095104341fe052fe28d to your computer and use it in GitHub Desktop.
Windowsユーザーの資格情報を使用して暗号化/復号を行うPowerShellのサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$rawText = "パスワード" | |
Add-Type -AssemblyName System.Security | |
$SALT_LEN = 16 # 128bit | |
$SALT_BASE64_LEN = 24 | |
function ConvertTo-EncryptedString { | |
param( | |
[string]$text | |
) | |
$txtBytes = [System.Text.Encoding]::Unicode.GetBytes($text) | |
$salt = [System.Security.Cryptography.RandomNumberGenerator]::GetBytes($SALT_LEN) | |
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser | |
$encryptedTextBytes = [System.Security.Cryptography.ProtectedData]::Protect($txtBytes, $salt, $scope) | |
$encryptedTextWithSalt = [System.Convert]::ToBase64String($salt) + [System.Convert]::ToBase64String($encryptedTextBytes) | |
return $encryptedTextWithSalt | |
} | |
function ConvertFrom-EncryptedString { | |
param( | |
[string]$text | |
) | |
$salt = [System.Convert]::FromBase64String($text.Substring(0, $SALT_BASE64_LEN)) | |
$encryptedTextBytes = [System.Convert]::FromBase64String($text.Substring($SALT_BASE64_LEN)) | |
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser | |
$rawTextBytes = [System.Security.Cryptography.ProtectedData]::UnProtect($encryptedTextBytes, $salt, $scope) | |
return [System.Text.Encoding]::Unicode.GetString($rawTextBytes) | |
} | |
Write-Output "Raw Text: $rawText" | |
$encryptedTextWithSalt = ConvertTo-EncryptedString $rawText | |
Write-Output "Encrypted Text: $encryptedTextWithSalt" | |
$decryptedText = ConvertFrom-EncryptedString $encryptedTextWithSalt | |
Write-Output "Decrypted Text: $decryptedText" | |
# 出力例 | |
# Raw Text: パスワード | |
# Encrypted Text: rwv/ViQOPXaD0jH99ovNwA==AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAx8tGJnXnzUy6zFSaW+UPXQAAAAACAAAAAAAQZgAAAAEAACAAAAB47LtO7NgZbSwYIFeGOOnsID6qadfoHyUiesUNWhxa9AAAAAAOgAAAAAIAACAAAABi2QvOBRS2uoLd9aNNbrpQ/CxtpdjhOun60ChZ+YZdchAAAABaKC1V5F8sKj+CTH1p1kThQAAAAApxObcuaR+wZUg27FtRYYBILeOswvjfM9B5MjTWVOH+5wQCmTmcUu0Ip/qvECjCW+h82yRwCxn01WoiA9sanJo= | |
# Decrypted Text: パスワード |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment