Ashutosh Kumar
Ashutosh Kumar

Reputation: 91

Encrypting and decrypting values in Azure redis cache

I want to encrypt while storing and decrypt while reading the values in redis cache. What can be best secured way to do it. Due to GDPR compliance i can't directly store the user aliases.

Following is my approach of converting it to Bytes and storing the byte array in redis.

https://learn.microsoft.com/es-es/dotnet/api/system.security.cryptography.rijndaelmanaged.generatekey?view=netcore-3.1

But i am not able to decrypt the byte array from redis.

Upvotes: 1

Views: 1615

Answers (1)

Jason Pan
Jason Pan

Reputation: 21916

UPDATE

enter image description here

enter image description here

PRIVIOUS

You can download my sample code.

enter image description here

public ActionResult RedisCache()
{
    ViewBag.Message = "A simple example with Azure Cache for Redis on ASP.NET.";
    var lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
    {
        string cacheConnection = _configuration.GetSection("CacheConnection").Value;
            return ConnectionMultiplexer.Connect(cacheConnection);
    });


    // Connection refers to a property that returns a ConnectionMultiplexer
    // as shown in the previous example.
    IDatabase cache = lazyConnection.Value.GetDatabase();

    // Perform cache operations using the cache object...

    string original = "Here is some data to encrypt!";
    string guid = Guid.NewGuid().ToString();

    byte[] myRijndaelKey;
    byte[] myRijndaelIV;

    using (RijndaelManaged myRijndael = new RijndaelManaged())
    {
        myRijndael.GenerateKey();
        myRijndael.GenerateIV();
        myRijndaelKey = myRijndael.Key;
        myRijndaelIV = myRijndael.IV;
    }
    byte[] encrypted_original = EncryptandDecrypt.EncryptStringToBytes(original, myRijndaelKey, myRijndaelIV);

    ViewBag.command6 = original;
    ViewBag.command6Result = encrypted_original;
    //set orginal data
    cache.StringSet(guid, encrypted_original);
    //set key and iv
    cache.StringSet(guid+"Key", myRijndaelKey);
    cache.StringSet(guid+"IV", myRijndaelIV);


    //get data from redis
    byte[] get_encrypted_originalByte = (byte[])cache.StringGet(guid);

    byte[] get_Key = (byte[])cache.StringGet(guid+"Key");

    byte[] get_IV = (byte[])cache.StringGet(guid+"IV");

    string decrypted_originalString = EncryptandDecrypt.DecryptStringFromBytes(get_encrypted_originalByte, get_Key, get_IV);

    ViewBag.command7 = "Get From Redis:"+ get_encrypted_originalByte;
    ViewBag.command7Result = "decrypted data:" + decrypted_originalString;

    lazyConnection.Value.Dispose();


    return View();
}

Upvotes: 1

Related Questions