James Bruckner
James Bruckner

Reputation: 909

Encrypt field value in LINQ-to-sql

I'm trying to take a better encryption approach for the functionality of

Person.FirstName = Encrypt(rawFirstName);
Person.sensitiveInfo = Encrypt(sensitiveInfo);

I'd rather not have to manually encrypt this kind of data every time it's used, so I've looked into modifying the .dbml and the Person object found in the .designer file.

I've come up with this:

.dbml file:

<Column Name="FirstName" Type="System.String" DbType="VarChar(256) NOT NULL" CanBeNull="false" /> 

.designer.cs file:

public partial class Person : INotifyPropertyChanging, INotifyPropertyChanged
{

    private string _FirstName;

    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FirstName", DbType="VarChar(256) NOT NULL", CanBeNull=false)]
    public string FirstName
    {
        get
        {
            return Decrypt(this._firstName);
        }
        set
        {
            if (Decrypt(this._firstName) != value)
            {
                this.OnFirstNameChanging(value);
                this.SendPropertyChanging();
                this._firstName = Encrypt(value);
                this.SendPropertyChanged("FirstName");
                this.OnFirstNameChanged();
            }
        }
    }
}

The problem I'm facing now is that it works inside the program(I've logged the before/after values in set to make sure), but will actually save the unencrypted values to the database. It looks like the storage _FirstName variable isn't being saved to the database as I thought, but the get method is being used instead.

I've taken a look at this answer as well as this one, but I can't for the life of me exactly figure out what they're trying to get across with the protected vs internal variables. Is there something simple I'm missing?

Upvotes: 0

Views: 868

Answers (1)

John Taylor
John Taylor

Reputation: 446

The best way to do this is to use a partial class for the generated class. The field stored in the database should be FirstNameSecure, LastNameSecure, etc.

Then in the partial class create the properties FirstName, LastName, etc that will encrypt/decrypt their secure version.

Upvotes: 1

Related Questions