Search code examples
c#.net-standard-2.0system.security

detect IsEncryptedString?


How can we find the given string is encrypted or plain string?

to be honest thats all the question. For instance when I'm using dataprotection using DPAPI encryption, when the given string is already a encrypted string or may be before decrypt call, check if the given string is encrypted.

 "ConnectionStrings": {
    "DefaultConnection": "Server=SQL2014;Database=TestDb;Trusted_Connection=false;User Id=test;Password=test@123;MultipleActiveResultSets=true"
  }

Configuration for Data protection

public void ConfigureServices(IServiceCollection services)
    {
        var dataProtectionBuilder = services.AddDataProtection().SetApplicationName("TestDataProtection");
        dataProtectionBuilder.PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"F:\Test Data\TestDPAPI"));
        //Configuration goes here
        dataProtectionBuilder.AddKeyManagementOptions(options =>
        {
            options.AutoGenerateKeys = true;
            options.NewKeyLifetime = TimeSpan.FromMinutes(1);
        });

        dataProtectionBuilder.ProtectKeysWithDpapi(true);//Scope to LocalMachine (default Scope.CurrentUser)
        dataProtectionBuilder.SetDefaultKeyLifetime(TimeSpan.FromMinutes(1));
        dataProtectionBuilder.UseCryptographicAlgorithms(new Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.AuthenticatedEncryptionSettings
        {
            EncryptionAlgorithm = Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.EncryptionAlgorithm.AES_256_GCM,
            ValidationAlgorithm = Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm.HMACSHA512
        });
    }

Service will looks something like below

public class TestClass
    {
        IDataProtector dataProtector;
        public TestClass(IDataProtectionProvider dataProtectorProvider)
        {
            this.dataProtector = dataProtectorProvider.CreateProtector("purpose");
        }

        private string Protect(string value)
        {
           return dataProtector.Protect(value);
        }
        private string UnProtect(string value)
        {           
            return IsProtected(value)? dataProtector.Unprotect(value):value;
        }
        private bool IsProtected(string value)
        {
            //TODO How can we find 
            return false;
        }
    }

Solution

  • If the data is indistinguishable from random bytes it is mist likely encrypted.
    If there are patterns it is not encrypted.

    Note that encrypted data may be encoded with with Base64, hex or another encoding, in that case it is necessary to decode before checking for randomness.