This chapter is about protecting your data from being viewed by malicious users using encryption, and from being manipulated or corrupted using hashing and signing.
This chapter covers the following topics:
There are many techniques to protect your data; some of them are as follows:
Authentication and authorization will be covered in Chapter 14, Building Web Applications Using ASP.NET Core MVC.
Protection algorithms often use a key. Keys can be symmetric (also known as shared or secret because the same key is used to encrypt and decrypt) or asymmetric (a public-private key pair where the public key is used to encrypt and only the private key can be used to decrypt).
Good Practice
Symmetric key encryption algorithms are fast and can encrypt large amounts of data using a stream. Asymmetric key encryption algorithms are slow and can only encrypt small byte arrays. In the real world, use the best of both worlds by using symmetric to encrypt your data, and asymmetric to share the symmetric key. For example, this is how Secure Sockets Layer (SSL) encryption on the Internet works.
Keys are represented by byte arrays of varying sizes.
When encrypting large amounts of data, there are likely to be repeating sequences. For example, in an English document, the sequence of characters "the" would appear frequently. A good cracker would use this knowledge to make it easier to crack the encryption:
When the wind blew hard the umbrella broke. 5:s4&hQ2aj#D f9d1d£8fh"&hQ2s0)an DF8SFd#][1
We can avoid repeating sequences by dividing data into blocks. After encrypting a block, a byte array value is generated from that block and this value is fed into the next block to adjust the algorithm so that "the" isn't encrypted in the same way. To encrypt the first block, we need a byte array to feed in. This is called the initialization vector (IV).
A salt is a random byte array that is used as an additional input to a one-way hash function. If you do not use a salt when generating hashes, then when many of your users register with 123456 as their password (about 8% of users still do this!), they all have the same hashed value, and their account will be vulnerable to a dictionary attack.
When a user registers, a salt should be randomly generated and concatenated with their chosen password before being hashed. The output (but not the original password) is stored with the salt in the database.
When the user next logs in and enters their password, you look up their salt, concatenate it with the entered password, regenerate a hash, and then compare its value with the hash stored in the database. If they are the same, you know they entered the correct password.
Keys and IVs are byte arrays. You can reliably generate a key or IV using a password-based key derivation function (PBKDF2). A good one is the Rfc2898DeriveBytes
class, which takes a password, a salt, and an iteration count, and then generates keys and IVs by making calls to its GetBytes
method.
18.191.205.99