Skip to content

Instantly share code, notes, and snippets.

@luggesexe
Forked from geekman/get-password.ps1
Last active May 6, 2025 22:07
Show Gist options
  • Save luggesexe/bf4e98384c0acfdb95392c067cc8bad2 to your computer and use it in GitHub Desktop.
Save luggesexe/bf4e98384c0acfdb95392c067cc8bad2 to your computer and use it in GitHub Desktop.
minimal PowerShell code to retrieve passwords from Windows Credentials
#
# PowerShell script to read out generic Windows Credentials
# this is kinda like macOS Keychain, but for Windows
#
# darell tan 2021.04.08
# Lukas Adrian Kron 2025.05.07
#
param (
[Parameter(Mandatory = $true)]
[string]$Target
)
[String] $CredNativeCode = @"
using System;
using System.Runtime.InteropServices;
public class CredMan {
[DllImport("Advapi32.dll", SetLastError=true, EntryPoint="CredReadW", CharSet=CharSet.Unicode)]
private static extern bool CredReadW([In] string target, [In] uint type, [In] int flag, out IntPtr credential);
[DllImport("Advapi32.dll", SetLastError=true, EntryPoint="CredFree")]
private static extern void CredFree([In] IntPtr cred);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
private struct Credential {
public uint Flags;
public uint Type;
public IntPtr TargetName;
public IntPtr Comment;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
public UInt32 CredentialBlobSize;
public IntPtr CredentialBlob;
public UInt32 Persist;
public UInt32 AttributeCount;
public IntPtr Attributes;
public IntPtr TargetAlias;
public IntPtr UserName;
}
public static string GetCredPassword(string target) {
IntPtr p;
string password = null;
if (CredReadW(target, /*GENERIC type*/ 1, 0, out p)) {
Credential c = (Credential) Marshal.PtrToStructure(p, typeof(Credential));
password = Marshal.PtrToStringUni(c.CredentialBlob, (int) (c.CredentialBlobSize / 2));
CredFree(p);
}
return password;
}
}
"@
Add-Type $CredNativeCode
$CredMan = [CredMan]
Write-Output $CredMan::GetCredPassword($Target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment