1

使用 PostSharp 我想对字段拦截进行加密/解密

我有一堂课

public class guestbookentry
  {       
    [Encryption]  // This Attribute has to Encrypt and Decrypt
    public string Message { get; set; }
    public string GuestName { get; set; }       
  }

我将对象保存在 Azure 表中。只有特定的字段必须得到加密/解密。

字段拦截的 PostSharp 属性

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();
        }
    } 
}
}

问题是 1. 连续加密和解密发生,难以处理。

请建议

4

1 回答 1

1

注意,调用与调用base.OnSetValue(args)相同,调用args.ProceedSetValue()与调用base.OnGetValue(args)相同args.ProceedGetValue()。这意味着您在每个处理程序中调用了继续方法两次。

您需要做的是args.ProceedGetValue()在开头调用OnGetValue以读取加密值,并args.ProceedSetValue()在结尾调用OnSetValue以保存加密值。

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();
}

此外,您不需要应用该[MulticastPointcut]属性。它在开发复合方面时使用,如开发复合方面中所述

于 2014-01-08T10:32:44.770 回答