Search code examples
c#.netcryptographydata-protection

Issues with protectedData API


I have following code and application works successfully sometimes but for certain users its not able to decrypt the password. It happens when mostly on server and multi user environment, works great on dev machine.

public static byte [] Protect( byte [] data )
    {
        try
        {
            // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            //  only by the same current user.
            return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not encrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static byte [] Unprotect( byte [] data )
    {
        try
        {
            //Decrypt the data using DataProtectionScope.CurrentUser.
            return ProtectedData.Unprotect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not decrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

Solution

  • DataProtectionScope.LocalMachine: This scope is valid to decrypt any authenticated user in the system.

    DataProtectionScope.CurrentUser : This scope is valid for only the user whose identity was used for encrypt only that identity can make it decrypt.

       public static byte [] Protect( byte [] data )
            {
                try
                {
                    return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.LocalMachine );
                } 
                catch (CryptographicException e)
                {
                    Console.WriteLine("Data was not encrypted. An error occurred.");
                    Console.WriteLine(e.ToString());
                    return null;
                }
            }
    
            public static byte [] Unprotect( byte [] data )
            {
                try
                {
                    return ProtectedData.Unprotect( data, s_aditionalEntropy, DataProtectionScope.LocalMachine );
                } 
                catch (CryptographicException e)
                {
                    Console.WriteLine("Data was not decrypted. An error occurred.");
                    Console.WriteLine(e.ToString());
                    return null;
                }
            }