Last active
May 6, 2025 22:03
-
-
Save geekman/6a9fedc599911f4af99c33cc9cae4887 to your computer and use it in GitHub Desktop.
minimal PowerShell code to retrieve passwords from Windows Credentials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # PowerShell script to read out generic Windows Credentials | |
| # this is kinda like macOS Keychain, but for Windows | |
| # | |
| # darell tan 2021.04.08 | |
| # | |
| [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 "password" $CredMan::GetCredPassword("git:https://geekman@github.com") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment