Skip to main content

What is Cryptography and how to secure sensitive data in .NET app with encryption

What is Cryptography? 

Cryptography is the process of securing data through encryption, hashing, digital signatures. It helps protect communication messages transmitted over non-secure networks, ensuring that only authorized parties can read the information.

Encryption and Decryption

Encryption is the process of converting plaintext data into ciphertext, which appears random and meaningless to anyone who does not have the key. Decryption is the reverse process — converting ciphertext back into readable plaintext.

The strength of encryption depends on several factors, including the algorithm used and the length of the encryption key. Generally, the longer the key, the harder it is to decrypt the ciphertext without authorization.

When choosing an encryption algorithm, it’s best to select one that has been thoroughly tested and widely used over time, as new or unproven algorithms may have hidden weaknesses.

Cryptographic Keys

At the heart of every cryptographic operation lies a cryptographic key, which is essential for both encryption and decryption. Without the correct key, the encrypted message remains unreadable. There are 4 types of keys:

- Symmetric key: Same key used for both encryption and decryption (e.g., AES, DES). It is an efficent way to encrypt large amount of data but possess a security risk when sharing the same key between sender and receiver.

- Asymmetric key: Uses a public key to encrypt and a private key to decrypt (e.g., RSA).

- Session key: A temporary, symmetric key used for a single session, and often in secure communication between two parties, such as browser and server

- Hash key: Used in HMACs to verify data integrity, not for encryption/decryption.

Data Protection in .NET

One practical way to encrypt sensitive data in software development is by using the Data Protection API in .NET. The Data Protection system provides a set of cryptographic APIs designed to protect application data easily and securely.

It uses symmetric key encryption under the hood, where the key is randomly generated and automatically managed by the system, so that developers don't have to manage secret keys manually.

To use data protection, there're 3 steps:


1. Create a data protector from data protection provider

A purpose string is needed. It defines the intended use of a data protector, and differentiate among consumers. For example, a protector with purpose string as 'red' won't be able to decrypt data with purpose string as 'blue'.

public class SecureData

    {

        IDataProtector _protector;

        public SecureData(IDataProtectionProvider provider)

        {

            _protector = provider.CreateProtector("purpose string here");

        }

2. Call Protect method to encrypt your data

        public void EncryptData()

        {

            string encryptedResult = _protector.Protect(input);

        }

3. Call Unprotect to decrypt data

        public void DecryptData()

        {

            string decryptedData = _protector.Unprotect(encryptedResult );

        }


IDataProtectionProvider is an interface that is needed to create a data protector (IDataProtector) by calling CreateProtector(). Then IDataProtector is used to have access to Protect and Unprotect method.


Source:


https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/using-data-protection?view=aspnetcore-9.0

https://www.c-sharpcorner.com/article/encrypting-sensitive-data-in-asp-net-core-applications/


Comments

Popular posts from this blog

Declarative Programming in Angular with Async Pipe and shareReplay

A declarative approach is a way that focuses on writing code that specifies what the application should do, rather than detailing how it should be done. For example, with the async pipe in Angular, we don’t need to write code to manually subscribe to an Observable, handle its data, and update the view. Instead, we simply specify in the template that we want the data from the Observable using the async pipe. Angular handles all the underlying processes to retrieve and display the data It's often used in reactive programming with RxJS and Angular's built-in features, such as the async pipe. export class ProductComponent { product$ = this.productService.getProduct(); constructor(private productService: ProductService) {} } The product observable will hold the product data and the async pipe in the template will automatically subscribe and unsubscribe observable <div *ngIf="product$ | async as product"> <h1>{{ product.name }}</h1> <p>{{...

The Developer’s Guide to Clean Code: Tips and Techniques

What is clean code? Clean code is a term used to describe code that is easy to read, understand, and maintain. It is written in a way that makes it simple, concise, and expressive. Clean code follows a set of conventions, standards, and practices that make it easy to read and follow. Here are some signs indicating that the code is not clean: 1. Poor names The name is not clear to understand, meaningless, or misleading . It doesn't reveal the intention of what it want to achieve. Consider the following examples: SqlDataReader drl; int od; void Button1_Click(); Class Pages1 In the examples above, it’s challenging to get the purpose of drl, od, or what Button1_Click() does. To enhance clarity, we can rename these identifiers as follows: SqlDataReader dataReader/reader; int overdueDays; void CheckAvailability_Click(); Class ViewCustomerPage {} Ambiguous names int? incidentNameId for instance. incidentNameId lacks clarity because if it represents the ID of an incident, then the inclu...

Date and Time in .NET: DateTime, DateTimeOffset, TimeZoneInfo, DateOnly, TimeOnly, and TimeSpan

What is UTC UTC (Coordinated Universal Time) is the world’s primary time standard used to regulate clocks and time zones. It serves as the reference point for civil time worldwide, ensuring that all local times are defined by their offset from UTC. DateTime The DateTime class provides a way to work with dates and times without including an offset. This approach can reduce a certain level of accuracy when dealing with time zones. For example, calling DateTime.Now returns the current date and time based on your computer’s local time zone. DateTime.Now gives you the local time, while DateTime.UtcNow returns the universal coordinated time (UTC). You typically use DateTime when you only need to track the date and time itself, without worrying about time zones. This is suitable for scenarios such as birthdays, deadlines, or local schedules, especially when your application is used primarily within a single time zone. The DateTime class also includes a Kind property, which provides limited in...