2016-09-03 93 views
0

实际上,我正在解密使用c#中的powershell创建的字符串。使用自定义密钥解密SecureString

我创建了SecureString的以下PowerShell命令:

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

我解密SecureString的使用下面的C#代码:

 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使用System.Security.Cryptography.Aes类加密,而不是ProtectedData,因此您需要进行一些更改。

如果通过使用密钥或SecureKey 参数指定的加密密钥,高级加密标准(AES)加密 算法。指定的密钥长度必须为128,192, 或256位,因为这些密钥是AES 加密算法所支持的密钥长度。如果未指定密钥,则使用Windows Data Protection API(DPAPI)加密标准字符串 表示法。

ConvertFrom-SecureString @ TechNet

就个人而言,我会使用ConvertTo-SecureString -cmdlet在C#中,以避免重新发明轮子。

请参阅Aes Constructor @ MSDN和这previous SO-question为C#解决方案。

相关问题