LoginSignup
6
2

More than 5 years have passed since last update.

ConvertTo-SecureString使ったら「指定された状態で使用するには無効なキーです。」と怒られた

Last updated at Posted at 2016-09-13

JenkinsでPowerShellスクリプトのテストをしようと試みたけど、こんな形で怒られた

ConvertTo-SecureString : 指定された状態で使用するには無効なキーです。
発生場所 C:\Program Files (x86)\Jenkins\workspace\TOOL\sample.ps1:17 
:31
+ $secpasswd = cat .\passwordfile.txt| ConvertTo-SecureString
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString]Cr 
   yptographicException
    + FullyQualifiedErrorId : ImportSecureString_InvalidArgument_Cryptographic 
   Error,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

原因

ググってもいい感じの答えが載ったページがなかったけど、原因としては

  • ConvertFrom-SecureStringで暗号化した際のユーザが異なると  復号化ができない
  • Jenkins/PowerShell Pluginで動く実行ユーザはauthority\system なので、  基本、実行ユーザが違う形になる

この条件が組み合わさった結果っぽい。

解決法

サービスが実行するとか、実行ユーザが違う場合のために 暗号化キーを渡すことができる。
書き方は試しに流した感じでは以下のような形でOKだった

>Read-Host -AsSecureString | ConvertFrom-SecureString -Key (1..16)

ただしこれはあくまでサンプル。
16/24/32長のバイト型を流してやればいいので、
しっかりやるならもっとうまくやること。

ConvertTo-SecureString側でも同じキーを指定してやる

>***** | ConvertTo-SecureString -key (1..16)

もっと厳重にやるならSecureKeyなんてオプションもあるけど
いったん内部で動けばいいレベルなので割愛します

6
2
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
6
2