如何在C#中解密使用PowerShell加密的字符串

13

在C#中是否有可能解密通过PowerShell加密的字符串,如何实现?

以下是通过PowerShell加密的字符串:

$pw = read-host "Enter Password" –AsSecureString

ConvertFrom-SecureString $pw | out-file "C:\file.txt"

要使用PowerShell将其转换回来,我可以使用调用C#类System.Runtime.InteropServices.Marshal的这些命令。

$pwdSec = Get-Content "C:\file.txt" | ConvertTo-SecureString

$bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwdSec)

$pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd)

文件包含已转换为加密标准的字符串string("hello")

因此,如果打开file.txt文件,它看起来类似于:

01000000d08c9ddf0115d1118c7a00c04fc297eb0100000052ded6c2db80e748933432e19b9de8b10000
000002000000000003660000c00000001000000016dc35885d76d07bab289eb9927cfc1e000000000480
0000a0000000100000003106cde553f45b08d13d89d11336170b280000005cc865c1ee1b57e84ed3d1a2
d3f2d0ec0f189b532e61c18d1f31444d6f119a1e8368477fd2d81f54140000000cb0262e58b08ae14f37
22c14c69684841b6b21c

可能是How can I use ConvertTo-SecureString的重复问题。 - Yeldar Kurmangaliyev
2个回答

16

你拥有的 ConvertFrom-SecureString 的输出文件是一个用 ProtectedData.Protect 保护的 UTF-16(密码)字符串,以十六进制转储的形式存储。

要还原编码,请使用:

// Read file to string
string exportedData = File.ReadAllText(@"file.txt");

// 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)
{
    var chunk = exportedData.Substring(2 * index, 2);
    encryptedData[index] =
        byte.Parse(chunk, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}

// Decrypt the byte array to Unicode byte array
byte[] data = ProtectedData.Unprotect(
    encryptedData, (byte[])null, DataProtectionScope.CurrentUser);

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

当您不使用 ConvertFrom-SecureString-Key 选项时,上述代码可以正常运行。此时,安全字符串会受到 Windows 数据保护 API (DPAPI) 的保护。因此,在相同的计算机和账户上对其进行编码和解码。


1

我有一个要求,需要在PowerShell中加密字符串并在.Net中解密。请使用以下函数来加密任何字符串。这里的(1..16)是一个字节数组

function EncriptStringData {
[CmdletBinding()]
param (
    [string] $PlainText        
)
$someSecureString = $PlainText | ConvertTo-SecureString -AsPlainText -Force
$encryptedTextThatIcouldSaveToFile =  ConvertFrom-SecureString -key (1..16) -SecureString $someSecureString

return $encryptedTextThatIcouldSaveToFile
}

现在,我已经将这个加密字符串输出作为我的.Net程序的输入,并且得到了相同的明文作为我的.Net程序的输出。请查看下面的函数。
using System;    
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;

namespace MyNameSpace
{
    public class DecryptStringData
    {
        public string GetDecryptString(string EncriptData)
        {
            try
            {
                byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            byte[] asBytes = Convert.FromBase64String(EncriptData);
            string[] strArray = Encoding.Unicode.GetString(asBytes).Split(new[] { '|' });

            if (strArray.Length != 3) throw new InvalidDataException("input had incorrect format");

            byte[] magicHeader = HexStringToByteArray(EncriptData.Substring(0, 32));
            byte[] rgbIV = Convert.FromBase64String(strArray[1]);
            byte[] cipherBytes = HexStringToByteArray(strArray[2]);

            SecureString str = new SecureString();
            SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create(); //This for .Net 4.5
//Use this for .Net core //  AesManaged algorithm = new AesManaged();
            ICryptoTransform transform = algorithm.CreateDecryptor(key, rgbIV);
            using (var stream = new CryptoStream(new MemoryStream(cipherBytes), transform, CryptoStreamMode.Read))
            {
                int numRed = 0;
                byte[] buffer = new byte[2]; // two bytes per unicode char
                while ((numRed = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    str.AppendChar(Encoding.Unicode.GetString(buffer).ToCharArray()[0]);
                }
            }

            string secretvalue = convertToUNSecureString(str);
            return secretvalue;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }

    }


    public static byte[] HexStringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);

        return bytes;
    }

    public static string convertToUNSecureString(SecureString secstrPassword)
    {
        IntPtr unmanagedString = IntPtr.Zero;
        try
        {
            unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secstrPassword);
            return Marshal.PtrToStringUni(unmanagedString);
        }
        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
        }
    }

}

}


你真棒。这确实很复杂,但它能工作。 - Cameron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接