misc/Messin_with_dpapi.ps1

$ncryptDef = @'
[DllImport("Ncrypt.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int NCryptCreateProtectionDescriptor (
    [MarshalAs(UnmanagedType.LPWStr)] string pwszDescriptorString,
    int dwFlags,
    ref IntPtr phDescriptor);
 
[DllImport("Ncrypt.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int NCryptProtectSecret (
    IntPtr hDescriptor,
    int dwFlags,
    ref byte[] pbData,
    ulong cbData,
    byte[] ppbProtectedBlob,
    IntPtr pcbProtectedBlob);
'@

## Refs: https://learn.microsoft.com/en-us/windows/win32/api/ncryptprotect/nf-ncryptprotect-ncryptprotectsecret
## C# impl of ncrypt https://github.com/microsoft/referencesource/blob/master/System.Core/System/Security/Cryptography/NCryptNative.cs
## Intro to types in pwsh https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/
## PInvoke dpapi http://www.pinvoke.net/default.aspx/ncrypt.NCryptOpenKey
## Example of using DPAPI in Powershell: https://www.sysadmins.lv/blog-en/retrieve-cng-key-container-name-and-unique-name.aspx
## Laps4Linux: https://github.com/schorschii/LAPS4LINUX/blob/master/laps-runner.py#L242
### Major help on powershell: https://www.insecurity.be/blog/2020/12/24/dpapi-in-depth-with-tooling-standalone-dpapi/
## Code from MS Azure: https://raw.githubusercontent.com/Azure/ArcEnabledServersGroupPolicy/main/AzureArcDeployment.psm1
$ncrypt = add-type -memberDefinition $ncryptDef -name 'nCryptProtect' -namespace 'nCryptProtect' -PassThru
$myhandle = 0
$SecretText = "Secret Text"
$textBytes = [System.text.Encoding]::UTF8.getBytes($SecretText)
$blob = [System.text.Encoding]::UTF8.getBytes($SecretText)
$blobSize = 0
$mySID = [System.Security.Principal.WindowsIdentity]::GetCurrent().user.value
$ncrypt::NCryptCreateProtectionDescriptor("SID=$mySID", 0, [ref]$myHandle)
#$ncrypt::NCryptProtectSecret($myHandle,0,$textBytes,$textBytes.length, [ref]$blob, [ref]$blobsize) ## WHY DOES THIS CRASH??????? Is it corrupting memory?????
$ncrypt::NCryptProtectSecret($myHandle, 0, [ref]$textBytes, $textBytes.length, [ref]$blob, [ref]$blobsize)

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# C# code to call into CNG DPAPI