How can I securly store an AES key in Windows with .Net (C#)? How can I securly store an AES key in Windows with .Net (C#)? windows windows

How can I securly store an AES key in Windows with .Net (C#)?


Windows DPAPI (Win32 documentation), and its .NET wrapper (ProtectedData Class) does not store any data. Rather, Windows DPAPI returns a cryptographic cypher value which you can store anywhere you like, including on multiple servers.

At my place of work we use DPAPI to generate a cypher for an AES key which we then store in the Registry.

The sole purpose of Windows DPAPI is to encrypt data such that only a given user account or machine can decrypt it, without needing to store a password.

The .NET ProtectedData class has been in the .NET Framework since 2.0.

I would stick with Windows DPAPI over a third party product as it is mature, stable, free, easy to use and fully supported in .NET.


Depending on who you're defending against, you can use the ProtectedData class.


@SLaks is right, if its in your memory it can be accessed. You can make it more difficult, but it's always going to be possible.

That's why folks who are serious offload the crypto.

One options is a smart card. This lets you move data to the card and get results back, but doesn't allow access to the key material. It's not in your PCs memory space so it can't be leaked.

Ross Anderson has a good paper, Programming Satan's Computer about just this kind of thing. From the abstract:

The problem is the presence of a hostile opponent,who can alter messages at will. In effect, ourtask is to program a computer which gives answerswhich are subtly and maliciouslywrong at the most inconvenient possible moment.

Even if you're not concerned about physical memory and just the hard disk and source you still need to be wary of virtual memory. If you're not careful (or using a carefully written service) you can get plaintext keys in your swap file. Here's another link that discusses the issue. Not that you want to do that but it makes the issue apparent: Encrypting Virtual Memory. I believe there are system calls for this purpose to mark memory as unswappable but I can't find a link.