Chapter 7. Manipulating Data

Every application uses data, and we need to manipulate that data from one form to another. This chapter offers several topics on data transformation in areas such as secret management, JSON serialization, and XML serialization.

Secrets are data, such as passwords or API keys, that we don’t want to expose to third parties. This chapter has three sections on managing secrets for hashing, encryption, and hidden storage.

Much of the data we work with today is in JSON format. Basic serialization/deserialization is simple in modern frameworks, and it’s even simpler when you own both the data consumer and provider. When consuming third-party data, you don’t have control over that data’s consistency or standards. That’s why the JSON sections of this chapter drill down on customizations to help you handle JSON in whatever format you need.

Finally, although JSON has a dominant place among internet data formats today, there’s still plenty of XML data to work with, which is the subject of the XML sections. You’ll see another flavor of LINQ, called LINQ to XML, which gives you full control over the serialization/deserialization process.

7.1 Generating Password Hashes

Problem

You need to securely store user passwords.

Solution

This method generates a random salt to protect secrets:

static byte[] GenerateSalt()
{
    const int SaltLength = 64;

    byte[] salt = new byte[SaltLength];
    var rngRand = new RNGCryptoServiceProvider();

    rngRand.GetBytes(salt);

    return salt;

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.