Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Security.Cryptography.ProtectedData.Unprotect is throwing a Invalid key error in certain circumstances

So I am trying to utilize the Unprotect method in the System.Security.Cryptography.ProtectedData object and keep getting the exception:

cryptographicexception key not valid for use in specified state

I think it has to do with the DataProtectionScope (but I am not 100%).

This method works if I am logged in and run an service executable in DEBUG mode which means to me, it would be running under the "currentuser". However, if I try to run the actual windows service, which runs under the LocalSystem account, it fails throwing the previous mentioned exception.

Method:

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

The DataProtectionScope Enum, only has CurrentUser or LocalMachine as your options. I am not sure what would be the best option for resolving this.

I have tried setting it to DataProtectionScope.LocalMachine which according to the MSDN article, any process running on the machine should be able to unprotect data. But doesn't.

like image 451
pghtech Avatar asked Jul 05 '11 18:07

pghtech


1 Answers

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

That leaves you with two options :

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

Either way, encryption and decryption must be done the same way. For example, use the local machine flag when encrypting and decrypting.

like image 80
ixe013 Avatar answered Sep 27 '22 21:09

ixe013