I use DPAPI
with DataProtectionScope.LocalMachine
in a Windows Service.
I tested my service by running it directly on my user account. It works.
Also works when run as administrator.
Then I install it as a Windows Service on LocalSystem
account.
Then it throws something like this:
Exception Info: Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the path specified.
at System.Security.Cryptography.ProtectedData.ProtectOrUnprotect(Byte[] inputData, Byte[] optionalEntropy, DataProtectionScope scope, Boolean protect)
at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
I changed service user to my user account and it works. So - the data protection fails only if the service is run as LocalSystem
.
Fragment that throws:
public byte[] Unprotect(byte[] data, DataProtectionScope scope = DataProtectionScope.CurrentUser)
=> ProtectedData.Unprotect(data, null, scope.AsSystemType());
The scope
is set to DataProtectionScope.LocalMachine
.
I also tried to run the service as "NT Authority\NetworkService" user. Same behavior. Can't access local machine protection keys.
Why is that and how can I fix that?