Skip to content

Instantly share code, notes, and snippets.

@jkuemerle
Created August 30, 2012 03:35
Show Gist options
  • Save jkuemerle/3522053 to your computer and use it in GitHub Desktop.
Save jkuemerle/3522053 to your computer and use it in GitHub Desktop.
Attribute to decorate automatically encrypted properties
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using PostSharp.Aspects;
using PostSharp.Aspects.Dependencies;
using PostSharp.Aspects.Advices;
namespace DataAccess.Aspects {
[Serializable]
[AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, typeof(EncryptedTypeAttribute))]
[AttributeUsage(AttributeTargets.Property)]
public class EncryptedAttribute : LocationInterceptionAspect, IInstanceScopedAspect {
private string propname;
public override void CompileTimeInitialize(PostSharp.Reflection.LocationInfo targetLocation, AspectInfo aspectInfo) {
propname = targetLocation.Name;
}
[ImportMember("EncryptedValues", IsRequired = true)]
public Property<Dictionary<string, string>> EncryptedValuesStore;
public object CreateInstance(AdviceArgs adviceArgs) { return this.MemberwiseClone(); }
public void RuntimeInitializeInstance() { }
public override void OnSetValue(LocationInterceptionArgs args) {
var val = System.Text.UnicodeEncoding.Unicode.GetBytes(args.Value.ToString());
var ent = CreateEntropy();
var enc = Convert.ToBase64String(ent) + Convert.ToBase64String(ProtectedData.Protect(val, ent, DataProtectionScope.CurrentUser));
if(null != EncryptedValuesStore)
if (!EncryptedValuesStore.Get().ContainsKey(propname))
EncryptedValuesStore.Get().Add(propname, enc);
else
EncryptedValuesStore.Get()[propname] = enc;
}
public override void OnGetValue(LocationInterceptionArgs args) {
args.Value = null;
if (null != EncryptedValuesStore)
if (EncryptedValuesStore.Get().ContainsKey(propname))
args.Value = EncryptedValuesStore.Get()[propname];
}
private byte[] CreateEntropy() {
var rng = new RNGCryptoServiceProvider();
byte[] ent = new byte[100];
rng.GetBytes(ent);
return ent;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment