I was wondering if there is easy solution to this or I’m stuck with following:
When updating DB:
dti.Pass = Crypter.Encrypt(dti.Pass); _db.SubmitChanges();
When selecting from DB:
Data.DbTableItem dti = _db.Single(a=>a.Id == id); dti.Pass = Crypter.Decrypt(dti.Pass);
Meaning – I am not really into writing repetitive code and this seems like logical thing to be supported by LINQ; so I’m wondering if it is.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could add a partial class with a property encapsulating this logic like:
public partial class DbTableItem
{
public String UnencryptedPass
{
get
{
return Crypter.Decrypt(this.Pass);
}
set
{
this.Pass = Crypter.Encrypt(value)
}
}
}
Hope it helps : )
Method 2
You should use SQL Server cryptographic functions, ENCRYPTBYKEY and DECRYPTBYKEY. Even better still, use Transparent Database Encryption. Right now you encrypt and decrypt the password with some key stored who know where. Databases have this nasty habit of moving around and being restored on completely new machines in case of disaster recovery or as part of various high availability scenarios, and you’ll discover that storing the encrypted data in the database and the encryption key in the system key store (or worse, in the app) has left you with a bunch of ‘completely secure’ data, impossible to decrypt because you lost the key.
Method 3
You could define a fake Password property which encapsulates your password logic and an original password field (which is mapped to the database – PasswordInternal in my example) should be e.g. internal.
public partial class YourEntity
{
public string Password
{
get
{
return Crypter.Decrypt(this.PasswordInternal)
}
set
{
this.PasswordInternal = Crypter.Encrypt(value)
}
}
}
AFAIK, there is no built-in functionality you’re looking for.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0