2016-09-03 5 views
0

実際に私はC#でpowershellで作成した文字列を解読しています。カスタムキーでSecureStringを復号する

私はPowerShellのコマンド次のようにSecureStringを作成します。

ConvertTo-SecureString -String "TopSecret" -AsPlainText -Force | ConvertFrom-SecureString 

私は、次のC#コードでSecureStringを解読:

 string exportedData = string.Empty; 
     bool SecureStringOK = true; 

     try 
     { 
      // Read args[0] to string 
      exportedData = args[0]; 
     } 
     catch (System.IndexOutOfRangeException) 
     { 
      Console.WriteLine("NO_SECURESTRING"); 
      Debug.WriteLine("NO_SECURESTRING"); 
      SecureStringOK = false; 
     } 

     if (SecureStringOK) 
     { 

      // Decrypt the byte array to Unicode byte array 
      try 
      { 
       // Remove all new-lines 
       exportedData = exportedData.Replace(Environment.NewLine, ""); 

       // Convert the hex dump to byte array 
       int length = exportedData.Length/2; 
       byte[] encryptedData = new byte[length]; 
       for (int index = 0; index < length; ++index) 
       { 
        encryptedData[index] = byte.Parse(exportedData.Substring(2 * index, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); 
       } 

       byte[] data = ProtectedData.Unprotect(encryptedData, (byte[])null, DataProtectionScope.CurrentUser); 

       // Convert Unicode byte array to string 
       string password = Encoding.Unicode.GetString(data); 

       // Write Output 
       Console.WriteLine(password); 
       Debug.WriteLine(password); 
      } 
      catch (System.Security.Cryptography.CryptographicException) 
      { 
       Console.WriteLine("WRONG_SECURESTRING: " + args[0]); 
       Debug.WriteLine("WRONG_SECURESTRING: " + args[0]); 
      } 
      catch (System.FormatException) 
      { 
       Console.WriteLine("WRONG_SECURESTRING_FORMAT: " + args[0]); 
       Debug.WriteLine("WRONG_SECURESTRING_FORMAT: " + args[0]); 
      } 

     } 

これは、両方の方向で正常に動作しますが、今私は中SecureStringを作成Powershellで自分のキーファイルを使用:

ConvertTo-SecureString -String "TopSecret" -AsPlainText -Force | ConvertFrom-SecureString -Key $KeyPath 

特定のキーファイルを使用するためにC#コードを変更する必要がありますか?

答えて

0

キーを指定すると、PowerShellはProtectedDataの代わりにSystem.Security.Cryptography.Aesクラスを使用して暗号化するため、かなりの変更が必要です。

暗号化キーは、キーまたはSecureKey パラメータ、 アルゴリズムが使用されているのAdvanced Encryption Standard(AES)暗号化を使用して指定された場合。指定されたキーの長さは、AES 暗号化アルゴリズムでサポートされているキー長であるため、長さは128,192, または256ビットでなければなりません。キーを指定しない場合、Windowsデータ プロテクションAPI(DPAPI)を使用して、標準文字列 の表現が暗号化されます。個人的に

ConvertFrom-SecureString @ TechNet

、私は車輪の再発明を避けるためにC#でConvertTo-SecureString -cmdletを使用します。

Aes Constructor @ MSDNおよびprevious SO-question(C#-solutions)を参照してください。

関連する問題