我需要在 power shell 中加密字符串并在 .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);
}
}
}
}