用 PowerShell 加密用 C# 解密

Powershell, SecureString, Secure String, ProtectData,

引言

使用 PowerShell 在本機進行加解密。過程中使用 SecureString 結構存儲存與交換;其基底是 ProtectedData 類別。SecureString 是用本機的秘密金鑰加解密,故換主機後會無效。

circle-exclamation
circle-exclamation

加密

$plainText = 'YourDataBaseConnString'
$secureString = ConvertTo-SecureString -String $plainText -AsPlainText -Force
$encryptedString = ConvertFrom-SecureString -SecureString $secureString
$encryptedString

解密

$decryptedString = ConvertTo-SecureString -String $encryptedString
$Marshal = [System.Runtime.InteropServices.Marshal]
$Bstr = $Marshal::SecureStringToBSTR($decryptedString)
$decryptedText = $Marshal::PtrToStringAuto($Bstr)
$Marshal::ZeroFreeBSTR($Bstr)
$decryptedText

解密 with ASP.NET Core

安裝套件

加解密

參考文章

完整原始碼

補充 on 2024-10-04

明文加密再 AES128 加密後才 base64 編碼。

明文加密後用 base64 編碼。

Last updated