Various Ways To Secure Sensitive Data In C#

Data security is a critical issue for organizations and individuals alike. Sensitive information such as personal data, financial details, and confidential business information must be protected from unauthorized access, theft, or misuse.

In this article, we'll discuss various ways to secure sensitive data in C#, We'll look at techniques such as

  1. Encryption
  2. Hashing
  3. Data masking

and explain how they can be used to secure sensitive data in a C# application. I will provide easy-to-understand examples for a few of the methods.

1. Encryption

Encryption is a process of converting plain text into ciphertext using an encryption key, which is a non-readable form. The main purpose of encryption is to protect sensitive data from unauthorized access or modification.

In C#, encryption can be achieved using the .NET framework's cryptography library, C# provides several classes in the System.Security.Cryptography namespace provides a wide range of encryption algorithms, including symmetric encryption (e.g. AES), asymmetric encryption (e.g. RSA), and hash-based encryption (e.g. SHA).

Here is an example of using the AES algorithm for encryption,

public string Encrypt(string plainText, string key)
	byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
	using (Aes aes = Aes.Create())
		aes.Key = Encoding.UTF8.GetBytes(key);

		using (MemoryStream memoryStream = new MemoryStream())
			memoryStream.Write(aes.IV, 0, aes.IV.Length);
			using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
				cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

				return Convert.ToBase64String(memoryStream.ToArray());

It is important to note that encryption provides data security only when used in conjunction with decryption. Without the ability to decrypt the encrypted data, the encrypted data is effectively useless and cannot be used for its intended purpose. Decryption enables authorized users to access and use the encrypted data while denying access to unauthorized users.

So Decryption is the reverse process of encryption, which converts the encrypted data back into its original form.

Here is an example of using the AES algorithm for decryption,

public string Decrypt(string cipherText, string key) {
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
    using(Aes aes = Aes.Create()) {
        aes.Key = Encoding.UTF8.GetBytes(key);
        using(MemoryStream memoryStream = new MemoryStream(cipherTextBytes)) {
            byte[] iv = new byte[aes.BlockSize / 8];
            memoryStream.Read(iv, 0, iv.Length);
            aes.IV = iv;
            using(CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read)) {
                using(StreamReader streamReader = new StreamReader(cryptoStream)) {
                    return streamReader.ReadToEnd();

Here is an example of how you can use the above code in your application.

static void Main() {
    // The original data to be encrypted
    string originalData = "This is some sensitive data.";
    // The secret key used for encryption and decryption
    string secretKey = "abcdefghijklmnopqrstuvwxyz123456";
    // Encrypt the data
    string encryptedData = new Program().Encrypt(originalData, secretKey);
    Console.WriteLine("Encrypted Data: " + encryptedData);
    // Decrypt the data
    string decryptedData = new Program().Decrypt(encryptedData, secretKey);
    Console.WriteLine("Decrypted Data: " + decryptedData);

In AES encryption, the key size must be 128, 192, or 256 bits

The code will result in the following,

Various Ways To Secure Sensitive Data In A C#

In summary, encryption and decryption are essential components of data security, and their use ensures the confidentiality, integrity, and authenticity of sensitive information.

2. Hashing

Hashing is a one-way process that converts sensitive data into a fixed-length string of characters. In C#, you can use the System.Security.Cryptography namespace to hash data using algorithms such as SHA256 and MD5.

A hash is a unique digital fingerprint or summary of a data set, often referred to as the “message”. Hashing algorithms take the input data and produce a fixed-length output, called a hash value, which serves as a digital signature of the data. The hash value is typically much smaller than the original data and provides a way to identify the data in a more efficient manner.

One of the key benefits of hashing is that it is a one-way process. This means that it is computationally infeasible to derive the original message from the hash value. This makes hashes ideal for verifying the integrity of data, as well as for secure password storage.

For example, when a user creates an account, their password can be hashed and stored in a database. When the user logs in, the entered password is hashed and compared to the stored hash. If the two hashes match, the user is granted access.

Here's an example of how you could hash a password in C# using a private key.

public void ComputeHash() {
    // The private key provided by the developer
    string privateKey = "9a2c3eab3d40b8f30b6e7ce7b1e2237e";
    byte[] privateKeyBytes = Encoding.UTF8.GetBytes(privateKey);
    // The password to hash
    string password = "secret123";
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
    // Compute the hash of the password using the private key
    using(var hmac = new HMACSHA256(privateKeyBytes)) {
        byte[] passwordHash = hmac.ComputeHash(passwordBytes);
        Console.WriteLine("Password hash: " + BitConverter.ToString(passwordHash).Replace("-", "").ToLower());

The code will result in the following,

Various Ways To Secure Sensitive Data In A C#

That this is just one possible approach for password hashing and there are many other algorithms and techniques that can be used for this purpose.

Now if you want to validate a password that has been hashed using the code example above, you would perform the following steps:

  1. Hash the entered password (This can be user input) using the same private key and HMACSHA256 algorithm.
  2. Compare the resulting hash with the stored hash (This can be a value stored in Database) value.
  3. If the two hashes match, the entered password is correct.

3. Data masking

Data masking, also known as data obfuscation or data pseudonymization, is a technique for obscuring sensitive data in order to protect it from unauthorized access. The goal of data masking is to replace sensitive information with realistic but fictitious data that retains the general format and characteristics of the original data. This makes it possible to use the masked data for testing, development, or other purposes without compromising the privacy of the original data. You can implement data masking in C# by using techniques such as substitution, shuffling, and truncation.

For example, We have user info inside DB and if we want to show that info to the user, but we don't want to show actual value instead we can mask them with some special character such as a password can be masked as  ****** or mobile number can be masked as 56XXXXXXXX. 

Here is an example of how you can mask a Mobile number,

public void MaskData(string data) {
    string mobile = "2589632547";
    int mobileLength = mobile.Length;
    string maskedMobile = mobile.Substring(0, 3) + new string('*', mobileLength - 2) + mobile.Substring(mobileLength - 1, 1);
    Console.WriteLine("Masked Mobile: " + maskedMobile);

Here is an example of how you can use the above code in your application.

// Mask the sensitive data using substitution
string maskedData = new Program().MaskData();

The code will result in the following. 

Various Ways To Secure Sensitive Data In A C#

Encryption and hashing require the use of keys, so it is important to manage those keys securely. You can store encryption keys in a secure key vault, such as Azure Key Vault or AWS Key Management Service.

In conclusion, securing sensitive data is a critical aspect of modern software development. There are various ways to secure sensitive data in C#, including encryption, hashing, and data masking. and the specific approach that you choose will depend on the requirements of your application and the level of security that you need to provide for your data.

I hope you will find this article helpful. If you have any suggestions, then please feel free to ask in the comment section.

Thank you.

Similar Articles