0

I'm experimenting with ProtectData.Protect() and ProtectData.Unprotect() functions in C#. I've written a program that writes encrypted data to an SQLite database, and then reads the database and decrypt the data. Every time I run my code I receive the following error:

   Unhandled Exception: System.Security.Cryptography.CryptographicException: The parameter is incorrect.

   at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
   at MyProgram.ReadData(SQLiteConnection conn)
   at MyProgram.Main()

The full code is very long, but here is the decrypt() function. I'm passing a byte array; I have verified the type to be a byte array using myByteData.GetType(), which returns System.Byte[].

public static byte [] decrypt( byte [] data ) {
        
        byte [] s_additionalEntropy = null;
        
        try {
            
            //Decrypt
            return ProtectedData.Unprotect( data, s_additionalEntropy, DataProtectionScope.CurrentUser );
            
        }catch{
            
            try {
            
                return ProtectedData.Unprotect( data, s_additionalEntropy, DataProtectionScope.LocalMachine );
                
            }catch (Exception e){
                
                Console.Write("Error: ");
                Console.WriteLine(e.Message);
                return null;
                
            }
        }
    }
Vimal CK
  • 3,543
  • 1
  • 26
  • 47
  • the example here is straightforward: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.dataprotectionscope?view=dotnet-plat-ext-3.1 – Mitch Wheat Sep 02 '20 at 08:20
  • As a general comment, I wouldn't use these functions to encrypt/decrypt data. being tied to a current user key or a machine key is liable to bite you. – Mitch Wheat Sep 02 '20 at 08:23

0 Answers0