I'd like to encrypt a SecureString using DPAPI so that I can save it to disk.
The .net DPAPI class is the ProtectedData class, however, ProtectedData.Protect has a single overload which takes a byte array. There is no overload which accepts a SecureString.
In Encrypting Passwords in a .NET app.config File, John Galloway makes use of the above overload by first converting the SecureString to an unsecured string. I'd like to avoid this as it defeats the purpose of using the SecureString in the first place.
The ConvertFrom-SecureString PowerShell cmdlet seems to do what I need since "if no key is specified, the Windows Data Protection API (DPAPI) is used to encrypt the standard string representation" but I'm not sure how I'd use this cmdlet directly from .net or even if it's a good idea to do so.
The blog post SecureString: Soup to Nuts, Part I by Jeff Griffin shows how this can be done. The approach is to convert the SecureString to an unmanaged BSTR and then use P/Invoke to call the unmanaged DPAPI functions.