I am storing some data in an external key-value store. This data is used as a cache. Because of the nature of the data we need to encrypt/hash the keys as well as values. We are using DataProtection APIs for the encryption and decryption with the default algorithm (AES-256-CBC). As per my knowledge, the encryption of the same plaintext doesn't give you the same cyphertext in this algorithm, so I can't encrypt the keys because next time I won't have the same encrypted key for lookup.
If we hash the keys (using SHA-256) instead of encrypting it, we can actually solve this problem but in some rare scenarios hashing can cause collisions and in our application, due to the nature of data we can't afford to have even a single collision. Code example:
public class MyClass
{
IDataProtector dataProtector;
ISomeStore externalStore;
public MyClass(IDataProtectionProvider dataProtectionProvider, ISomeStore externalStore)
{
this.dataProtector = dataProtectionProvider.CreateProtector("somePurposeString");
this.externalStore = externalStore;
}
public string GetOrAddValue(string someKey)
{
string encryptedKey = this.dataProtector.Protect(someKey);
if (this.externalStore.KeyExists(encryptedKey)
{
string encryptedValue = this.externalStore.Get(encryptedKey); // lookUp in the cache
return this.dataProtector.Unprotect(encryptedValue);
}
else
{
string someValue = GetValue(someKey);
this.externalStore.Set(encryptedKey, this.dataProtect.Protect(someValue)); // setting the value in the cache
return someValue;
}
}
}
Is there a way to efficiently solve this problem? The avergae lookup time from external key value store is around 100 ms.