实际上,我正在解密我在 c# 中使用 powershell 创建的字符串。
我使用以下 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]);
}
}
这在两个方向上都可以正常工作,但现在我使用自己的密钥文件在 Powershell 中创建 SecureString:
ConvertTo-SecureString -String "TopSecret" -AsPlainText -Force | ConvertFrom-SecureString -Key $KeyPath
任何想法我必须在 c# 代码中更改以使用特定的密钥文件?