C# Encrypt and Decrypt a field with setter and getter

Sometimes we need to encrypt a field while saving to database instead of original value but while reading it and using it in our application we need to decrypt again.

This can be implemented at class level by making use of setter and getter and another property to back the property we are trying to encrypt.

Consider the following class Customer with Name and SSN

public class Customer { public string Name { get; set; } public string SSN {get;set;} }
Code language: JavaScript (javascript)

In this class if we want to encrypt the SSN property, this can be done as follows.

public class Customer { public string Name { get; set; } private string _SSN; [JsonIgnore] public string SSN { //make sure this property is not saved to database get { return Decrypt(EncryptedSSN); } set { _SSN = value; EncryptedSSN = Encrypt(value); } } private string _encryptedSSN; public string EncryptedSSN { get; private set; } public string Decrypt(string encryptedSSN) { return "originialvalue"; } public static string Encrypt(string originalSSN) { return "encryptedValue"; } }
Code language: JavaScript (javascript)

Here the encryptedSSN is saved to database and we can get and set the original SSN field like normal field and the encryption and decryption takes place at the class level and we don’t have to worry about making changes else where.
Also the private set on the “EncryptedSSN” ensures we don’t set it from anywhere in the code.Just make sure you don’t save the field “SSN” to the database.

Using lock in C#

Sometimes when we are using threading in a project and there are simultaneous threads running a piece of code but you want the threads to run the code sequentially,then we can make use of lock and create an object and place the critical section code in this lock.

private static readonly Object _lock = new Object(); lock (_lock) { // critical section }
Code language: JavaScript (javascript)