检测 IsEncryptedString?

detect IsEncryptedString?

我们如何找到给定的字符串是加密字符串还是纯字符串?

老实说,这就是所有问题。例如,当我使用 DPAPI 加密进行数据保护时,当给定的字符串已经是加密的字符串或者可能在解密调用之前,请检查给定的字符串是否已加密。

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

数据保护配置

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
        });
    }

服务将如下所示

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;
        }
    }

老实说,我对 DDAPI 并不熟悉。一个通用的答案,因为它是一个通用的问题...

字符串只是一段数据。在不知道要查找什么的情况下,不可能知道它是垃圾(加密)还是不是(解密),也就是说,您总是知道要查找的某种上下文或指标。我建议您加密数据(您的字符串),然后对其进行签名。在'isprotected'中尝试验证签名。如果它验证你会知道你需要解密它并且它来自可信赖的来源。

https://blogs.msdn.microsoft.com/alejacma/2008/06/25/how-to-sign-and-verify-the-signature-with-net-and-a-certificate-c/

如果数据与随机字节无法区分,则很可能是加密的。
如果有模式,则未加密。

请注意,加密数据可能使用 Base64、十六进制或其他编码进行编码,在这种情况下,有必要在检查随机性之前进行解码。