Applications frequently need to store credentials to communicate with external services, databases, APIs, network resources, and remote servers. These credentials may include usernames, passwords, API keys, access tokens, or other sensitive information.
A common approach is to store these values in application configuration files, environment variables, or local databases. However, storing sensitive information directly in configuration files can introduce security risks, especially when files are shared, copied, or accidentally committed to source control.
Windows provides a built-in feature called Credential Manager that allows applications to store and retrieve credentials through native Windows APIs.
For C# developers building Windows desktop applications, command-line tools, or background applications, integrating with Windows Credential Manager provides a practical way to use the operating system's credential storage capabilities.
In this article, we will explore how Windows Credential Manager works, how to access it using C# and Platform Invocation Services (P/Invoke), and how to implement secure credential storage, retrieval, and deletion.
Understanding Windows Credential Manager
Windows Credential Manager is a Windows feature that stores credentials for applications, websites, and network resources.
Instead of requiring every application to implement its own credential storage mechanism, developers can use the Windows Credentials API to manage application-specific credentials.
For example, a desktop application that communicates with a private REST API can store its API credentials in Windows Credential Manager and retrieve them whenever authentication is required.
The stored credentials are associated with the Windows user's credential set and protected by Windows.
Windows Credential Manager supports different credential types, including:
Generic credentials: Used by applications to store application-defined credentials such as API keys, passwords, and tokens.
Domain credentials: Used with Windows authentication mechanisms such as Kerberos and NTLM.
Certificate-based credentials: Used for authentication scenarios involving certificates.
For most custom C# applications that need to store API keys or application passwords, generic credentials are the appropriate choice.
Why Use Windows Credential Manager in C# Applications?
Developers sometimes store credentials directly in application configuration files.
Consider the following example:
{
"ApiSettings": {
"BaseUrl": "https://api.example.com",
"ApiKey": "my-secret-api-key"
}
}Although this approach is simple, it creates problems when configuration files are copied between environments, committed to source control, or exposed through deployment packages.
Windows Credential Manager provides an alternative.
The application stores the credential in the Windows credential vault and retrieves it when required.
Some important advantages include:
Credentials are stored through Windows-managed credential storage.
Applications do not need to implement their own encryption and decryption mechanism.
Credentials can be associated with individual Windows user accounts.
Applications can update or remove stored credentials.
Users can manage saved credentials through the Windows Credential Manager interface.
However, Credential Manager is not a replacement for every secret-management solution. Applications running across multiple servers or cloud environments may need a centralized secret vault instead.
Understanding the Native Windows Credential APIs
Windows exposes several functions for managing credentials through the Windows Credentials API.
The most commonly used functions are:
Windows API | Purpose |
|---|---|
CredWrite | Creates or updates a credential |
CredRead | Retrieves a stored credential |
CredDelete | Deletes a stored credential |
CredEnumerate | Retrieves matching credentials |
CredFree | Releases memory allocated by credential retrieval functions |
C# applications can access these native functions using P/Invoke.
P/Invoke allows managed .NET code to call functions implemented in unmanaged Windows libraries.
The functions required for credential management are available through Advapi32.dll.
Integrating Windows Credential Manager With C#
Let's create a reusable C# implementation that supports saving, retrieving, and deleting application credentials.
For this example, we will build a small credential storage service that can be reused across different Windows applications.
Step 1: Create a C# Project
Create a console application:
dotnet new console -n WindowsCredentialDemoMove into the project directory:
cd WindowsCredentialDemoThe implementation uses native Windows APIs directly, so an additional NuGet package is not required.
This example targets Windows and can be used with modern .NET applications.
Step 2: Define the Native Credential Structure
The Windows Credential API uses a native structure called CREDENTIALW.
C# must represent this structure correctly before calling the native functions.
Create a file named NativeCredential.cs:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NativeCredential
{
public uint Flags;
public uint Type;
public IntPtr TargetName;
public IntPtr Comment;
public System.Runtime.InteropServices.ComTypes.FILETIME
LastWritten;
public uint CredentialBlobSize;
public IntPtr CredentialBlob;
public uint Persist;
public uint AttributeCount;
public IntPtr Attributes;
public IntPtr TargetAlias;
public IntPtr UserName;
}The structure contains information about the credential, including its target name, username, credential data, and persistence settings.
Some fields are represented as IntPtr because the original Windows structure contains pointers to unmanaged memory.
The structure layout and field order must match the native Windows definition. Incorrect structure definitions can cause memory corruption or unexpected API failures.
Step 3: Declare the Native Windows Functions
Next, create a file named CredentialNativeMethods.cs.
We need to declare the native functions that will save, retrieve, and delete credentials.
using System.Runtime.InteropServices;
public static class CredentialNativeMethods
{
[DllImport(
"Advapi32.dll",
EntryPoint = "CredWriteW",
CharSet = CharSet.Unicode,
SetLastError = true)]
public static extern bool CredWrite(
ref NativeCredential credential,
uint flags);
[DllImport(
"Advapi32.dll",
EntryPoint = "CredReadW",
CharSet = CharSet.Unicode,
SetLastError = true)]
public static extern bool CredRead(
string target,
uint type,
uint flags,
out IntPtr credential);
[DllImport(
"Advapi32.dll",
EntryPoint = "CredDeleteW",
CharSet = CharSet.Unicode,
SetLastError = true)]
public static extern bool CredDelete(
string target,
uint type,
uint flags);
[DllImport(
"Advapi32.dll",
EntryPoint = "CredFree",
SetLastError = false)]
public static extern void CredFree(
IntPtr credential);
}These declarations connect managed C# code with the Windows Credential API.
SetLastError allows the application to retrieve the Windows error code when a native operation fails.
CredFree is particularly important because CredRead returns a pointer to memory allocated by Windows. That memory must be released using CredFree rather than Marshal.FreeHGlobal.
Step 4: Implement the Credential Storage Service
Now create a reusable class named WindowsCredentialStore.
This class will provide methods for saving, retrieving, and deleting generic credentials.
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
public class WindowsCredentialStore
{
private const uint GenericCredential = 1;
private const uint LocalMachinePersistence = 2;
private const uint MaximumCredentialSize = 2560;
public void Save(
string target,
string username,
string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
if (passwordBytes.Length > MaximumCredentialSize)
{
throw new ArgumentException(
"Credential exceeds the supported size.");
}
IntPtr targetPtr = IntPtr.Zero;
IntPtr usernamePtr = IntPtr.Zero;
IntPtr blobPtr = IntPtr.Zero;
try
{
targetPtr = Marshal.StringToHGlobalUni(target);
usernamePtr = Marshal.StringToHGlobalUni(username);
blobPtr = Marshal.AllocHGlobal(
passwordBytes.Length);
Marshal.Copy(
passwordBytes,
0,
blobPtr,
passwordBytes.Length);
var credential = new NativeCredential
{
Type = GenericCredential,
TargetName = targetPtr,
UserName = usernamePtr,
CredentialBlob = blobPtr,
CredentialBlobSize =
(uint)passwordBytes.Length,
Persist = LocalMachinePersistence
};
if (!CredentialNativeMethods.CredWrite(
ref credential, 0))
{
throw new Win32Exception(
Marshal.GetLastWin32Error());
}
}
finally
{
if (blobPtr != IntPtr.Zero)
{
Marshal.WriteByte(
blobPtr,
0);
Marshal.FreeHGlobal(blobPtr);
}
if (targetPtr != IntPtr.Zero)
Marshal.FreeHGlobal(targetPtr);
if (usernamePtr != IntPtr.Zero)
Marshal.FreeHGlobal(usernamePtr);
CryptographicOperations.ZeroMemory(
passwordBytes);
}
}
}The Save method performs several important operations.
First, it converts the password into UTF-8 bytes because the credential blob contains binary data rather than a null-terminated string.
Next, it allocates unmanaged memory for the credential information.
The method creates a native credential structure and calls CredWrite to store the credential.
The persistence value determines how long Windows should retain the credential. LocalMachinePersistence requests persistence across logon sessions for the current Windows user, subject to Windows credential storage behavior.
Finally, the method releases allocated memory and clears the managed password byte array.
The native credential blob has a maximum supported size of 2560 bytes for generic credentials.
Step 5: Retrieve Stored Credentials
Saving credentials is only useful if the application can retrieve them later.
Add the following method to WindowsCredentialStore:
public (string Username, string Password)?
Get(string target)
{
IntPtr credentialPtr = IntPtr.Zero;
try
{
bool success = CredentialNativeMethods.CredRead(
target,
GenericCredential,
0,
out credentialPtr);
if (!success)
{
int error = Marshal.GetLastWin32Error();
if (error == 1168)
return null;
throw new Win32Exception(error);
}
var credential =
Marshal.PtrToStructure<NativeCredential>(
credentialPtr);
string username = Marshal.PtrToStringUni(
credential.UserName) ?? string.Empty;
byte[] passwordBytes = new byte[
credential.CredentialBlobSize];
Marshal.Copy(
credential.CredentialBlob,
passwordBytes,
0,
passwordBytes.Length);
try
{
string password = Encoding.UTF8.GetString(
passwordBytes);
return (username, password);
}
finally
{
CryptographicOperations.ZeroMemory(
passwordBytes);
}
}
finally
{
if (credentialPtr != IntPtr.Zero)
{
CredentialNativeMethods.CredFree(
credentialPtr);
}
}
}The CredRead function retrieves the credential associated with the specified target name.
The application then reads the username and credential blob from the returned native structure.
One important detail is that CredRead allocates unmanaged memory. Always call CredFree after processing the returned credential, including when an exception occurs.
The example returns the password as a managed string for simplicity. Since strings cannot be reliably cleared from memory, production applications should minimize how long retrieved secrets remain in memory and avoid retaining them unnecessarily.
Step 6: Delete Stored Credentials
Applications also need a way to remove credentials when users sign out, change API accounts, or disconnect an external service.
Add the following method:
public void Delete(string target)
{
bool success = CredentialNativeMethods.CredDelete(
target,
GenericCredential,
0);
if (!success)
{
int error = Marshal.GetLastWin32Error();
if (error == 1168)
return;
throw new Win32Exception(error);
}
}CredDelete removes the credential associated with the specified target name and credential type.
The method treats an already missing credential as a successful cleanup operation.
Using WindowsCredentialStore in a C# Application
Now that the storage service is ready, we can use it inside the application.
For example:
var credentialStore = new WindowsCredentialStore();
credentialStore.Save(
"MyApplication.Api",
"api-user",
"my-secret-password");
var credential = credentialStore.Get(
"MyApplication.Api");
if (credential != null)
{
Console.WriteLine(
$"Username: {credential.Value.Username}");
}
credentialStore.Delete("MyApplication.Api");The target name acts as the identifier for the stored credential.
An application can use different target names for different external services.
For example:
MyApplication.Api
MyApplication.Database
MyApplication.Storage
MyApplication.Email
Using meaningful target names makes credential management easier and reduces the possibility of accidentally overwriting unrelated credentials.
Advantages and Disadvantages of Windows Credential Manager
Advantages
Native Windows integration: Applications can use the operating system's existing credential storage functionality.
Reduced configuration exposure: Sensitive credentials do not need to be stored directly in application configuration files.
User-specific storage: Credentials are associated with the current Windows user's credential set.
Simple management: Applications can create, retrieve, update, and delete credentials through native APIs.
No additional storage infrastructure: Desktop applications can use the built-in Windows credential system without maintaining a separate database.
Disadvantages
Windows dependency: The native Credential Manager API is Windows-specific.
User-context dependency: Credentials are associated with the current security context and may not be available to another user.
Memory handling: Retrieved credentials still need to exist in application memory when being used.
Size limitations: Generic credential blobs have a maximum supported size.
Limited centralized management: It is not designed to replace enterprise-wide secret management systems.
Best Practices for Production Applications
When integrating Windows Credential Manager into production applications, consider the following practices.
Use meaningful target names. Maintain a consistent naming convention so credentials belonging to different application modules remain separate.
Avoid logging sensitive information. Never write passwords, tokens, or credential blobs into application logs or exception messages.
Minimize secret lifetime. Retrieve credentials only when needed and avoid keeping them in memory longer than necessary.
Release unmanaged memory correctly. Always use CredFree for memory returned by CredRead and release application-allocated unmanaged buffers.
Validate native API errors. Use Marshal.GetLastWin32Error to identify problems such as missing credentials or invalid permissions.
Choose persistence carefully. Use session persistence when credentials should not survive logoff, and longer persistence only when the application requires it.
Avoid sharing credentials between users. Store and retrieve credentials under the intended Windows user account.
Use a centralized vault for server applications. Applications running across multiple machines should consider Azure Key Vault or another managed secret store.
Avoid unnecessary password handling. When supported, prefer certificate-based authentication, passkeys, or other passwordless approaches.
Test different Windows environments. Validate behavior under standard user accounts, service accounts, restricted policies, and environments using Windows Credential Guard.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Recommended Solution |
|---|---|---|
CredRead returns error 1168 | Credential does not exist | Verify the target name and credential type |
CredWrite fails | Invalid credential structure or unsupported values | Review structure layout and credential size |
Credentials are unavailable after switching users | Different Windows security context | Run under the original user account |
Application cannot retrieve credentials from a Windows Service | Service runs under a different account | Configure the correct service identity |
Access fails after logoff | Session-based persistence was used | Review credential persistence settings |
Application crashes during native calls | Incorrect memory handling or structure definition | Verify P/Invoke declarations and memory ownership |
Credentials cannot be restored in a protected environment | Windows Credential Guard or organizational policy | Review the applicable Windows security configuration |
A particularly important issue occurs when applications run as Windows Services.
A service running under LocalSystem or another service account does not automatically have access to credentials stored under an interactive user's account.
Credential Manager uses the security context of the calling process. Therefore, the application must store and retrieve credentials using the intended account.
Summary
Windows Credential Manager provides C# developers with a native Windows solution for storing and retrieving application credentials.
By using P/Invoke with CredWrite, CredRead, CredDelete, and CredFree, developers can integrate the Windows credential vault directly into their applications without implementing a separate credential storage system.
This approach is particularly useful for Windows desktop applications, command-line tools, and applications that operate under a dedicated Windows user account.
However, developers must understand credential persistence, Windows user contexts, unmanaged memory handling, and security restrictions before using this approach in production.
For applications that need centralized secret management across multiple servers or cloud environments, a dedicated secret-management service is generally a better choice.
The important goal is to avoid storing sensitive credentials in plain configuration files and select a credential storage mechanism that matches the application's deployment and security requirements.


Join the conversation! Your thoughts help the community grow.