System.Security.Cryptography.ProtectedData.Unprotect throws an invalid key error in certain circumstances

So, I'm trying to use the Unprotect method in a System.Security.Cryptography.ProtectedData object and get an exception:

cryptographicexception key not valid for use in specified state 

I think this is due to DataProtectionScope (but I'm not 100%).

This method works if I logged in and ran the service executable in DEBUG mode, which means that it will run under "currentuser". However, if I try to start the actual Windows service that is running under the LocalSystem account, it cannot fail the previous exception.

Method:

 ProtectedData.Unprotect(Byte[] byteArray, <some_password_salt>, DataProtectionScope.CurrentUser) 

The DataProtectionScope view lists only those CurrentUser or LocalMachine parameters. I am not sure what would be the best option to resolve this issue.

I tried to install it in DataProtectionScope.LocalMachine, which, according to an MSDN article, any process running on a machine should be able to remove protection. But does not.

+6
source share
1 answer

The data protection API uses a key generated for each user. This is a symmetric encryption scheme, which means that data encrypted for the user cannot be decrypted by another user. It cannot be decrypted by the same user on another machine.

This leaves you with two options:

  • Encrypt and decrypt data using code running under the same account on the same machine
  • Use the CRYPTPROTECT_LOCAL_MACHINE flag to use the machine key, not the user.

In any case, encryption and decryption should be the same. For example, when encrypting and decrypting, use the local machine flag.

+13
source

Source: https://habr.com/ru/post/892067/


All Articles