Question

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

No correct solution

OTHER TIPS

Note, that calling base.OnSetValue(args) is the same as calling args.ProceedSetValue(), and calling base.OnGetValue(args) is the same as calling args.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 the OnGetValue to read the encrypted value, and call args.ProceedSetValue() at the end of the OnSetValue to save the encrypted value.

public override void OnGetValue(LocationInterceptionArgs args)
{
    args.ProceedGetValue();
    if (args.Value != null)
    {
        args.Value = // decrypt
    }
}

public override void OnSetValue(LocationInterceptionArgs args)
{
    if (args.Value != null)
    {
        args.Value = // encrypt
    }
    args.ProceedSetValue();
}

Also, you don't need to apply the [MulticastPointcut] attribute. It's used when developing composite aspects as described in Developing Composite Aspects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top