Using PostSharp I would like to do Encryption/Decryption on Field Interception
I have a Class
public class guestbookentry
{
[Encryption] // This Attribute has to Encrypt and Decrypt
public string Message { get; set; }
public string GuestName { get; set; }
}
I am saving the object in Azure Tables. Only particular Field has to be get En/Decrypt.
PostSharp Attribute on Field Interception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PostSharp;
using PostSharp.Aspects;
using EncryptionDecryption;
using PostSharp.Serialization;
using PostSharp.Aspects.Advices;
using PostSharp.Extensibility;
namespace GuestBook_Data
{
[Serializable]
public class EncryptionAttribute : LocationInterceptionAspect
{
[MulticastPointcut(Targets = MulticastTargets.Field, Attributes = MulticastAttributes.Instance)]
public override void OnSetValue(LocationInterceptionArgs args)
{
base.OnSetValue(args);
if (args.Value != null)
{
MD5CryptoServiceExample objMD5Encrypt = new MD5CryptoServiceExample();
args.Value = objMD5Encrypt.Encrypt(args.Value.ToString()).Replace(" ", "+");
args.ProceedSetValue();
}
}
public override void OnGetValue(LocationInterceptionArgs args)
{
base.OnGetValue(args);
if (args.Value != null)
{
MD5CryptoServiceExample objMD5Encrypt = new MD5CryptoServiceExample();
args.Value = objMD5Encrypt.Decrypt(args.Value.ToString()); //objMD5Encrypt.Decrypt(args.Value.ToString());
args.ProceedGetValue();
}
}
}
}
Problem is 1. Successive Encryption and Decryption happens which is difficult to handle.
Kindly suggest
Note, that calling
base.OnSetValue(args)
is the same as callingargs.ProceedSetValue()
, and callingbase.OnGetValue(args)
is the same as callingargs.ProceedGetValue()
. This means that you're calling the proceed methods twice in each of your handlers.What you need to do is to call
args.ProceedGetValue()
at the start of theOnGetValue
to read the encrypted value, and callargs.ProceedSetValue()
at the end of theOnSetValue
to save the encrypted value.Also, you don't need to apply the
[MulticastPointcut]
attribute. It's used when developing composite aspects as described in Developing Composite Aspects.