我们如何才能找到给定的字符串是加密的还是纯字符串?
老实说,这就是所有问题。例如,当我使用 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;
}
}