1
1

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 3 years have passed since last update.

Powershellでの暗号化・復号化を行う関数

Posted at

Powershellでの暗号化・復号化を行う関数

業務では、Windows Powershellにて自動化することが多いです。
自動化の中でサーバー構築から、運用保守のツール作成までを行っています。
そこで、管理者権限を持ったユーザーでリモート処理などを行うのですが、
設定ファイルにパスワードをそのまま記載するわけにはいかないため、
簡易的に設定ファイルを見ただけではわからないようにパスワードを暗号化して、
ツール内で復号するような作りをしています。
関数にしてあるので使いやすくなっているかと思います。
みなさんは自動化ツールなどで使っているパスワードなどはどのように管理していますか?

対象者

  • 設定ファイル等にパスワードはそのまま記載したくない
  • キーワードを使ったパスワードを使っていない($$とか)

暗号化

function Restore-Encrypt {
  [CmdletBinding()]
  param(
    [parameter(Mandatory=$TRUE)]
    [string]$PassWdStr
  )
  # Convert to base64
  $StringToByte = [System.Text.Encoding]::UTF8.GetBytes($PassWdStr)
  $Base64String = [System.Convert]::ToBase64String($StringToByte)

  # Encryption Byte Array
  [byte[]]$PasswdKey = (1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,99,99,99,99,99,99)

  # Convert the string to be encrypted
  $SecurePW = ConvertTo-SecureString -String $Base64String -AsPlainText -Force -ErrorAction stop
  $EncryptString = ConvertFrom-SecureString -SecureString $SecurePW -key $PasswdKey

  # Return after encryption
  return $EncryptString
}

復号化

function Restore-Decrypt {
  [CmdletBinding()]
  param(
    [parameter(Mandatory=$TRUE)]
    [string]$PassWdStr
  )
  # Byte array for decoding
  [byte[]]$PasswdKey = (1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,99,99,99,99,99,99)

  # Convert encrypted strings
  $ImportSecureString = $PassWdStr | ConvertTo-SecureString -Key $PasswdKey
  $SecureStringToBSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ImportSecureString)
  $ToString = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($SecureStringToBSTR)

  # Convert encrypted strings
  $PasswordToByte = [System.Convert]::FromBase64String($ToString)
  $DecryptString = [System.Text.Encoding]::UTF8.GetString($PasswordToByte)

  # Return of decryption
  return $DecryptString
}

カスタマイズするところ

[byte[]]$PasswdKeyについては、配列数を変えなければ中身の数字を好きに変えていただき、
自分のオリジナルのキー配列にしていただいて構いません。
また、その外出しにしてアレンジしてみてください。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?