System.Security.Cryptography Namespace in .NET

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The System.Security.Cryptography namespace contains support for the most common symmetric (DES, 3DES, RC2, Rijndael), asymmetric (RSA, DSA), and hash (MD5, SHA-1, SHA-256, SHA- 384, SHA-512) cryptography algorithms. It also includes a helpful class to encrypt and decrypt streams. You can use this class, called CryptoStream, in combination with other stream classes or you can use several CryptoStream class objects together. With a little effort, you can feed the output of one CryptoStream object into another CryptoStream object. 

Table 22.6 lists the classes and interfaces that are part of the System.Security.Cryptography namespace of the .NET Framework base class library. These classes and interfaces define the abstract object model for encryption algorithms within the .NET Framework. New algorithms may be added to the .NET Framework by subclassing and/or implementing a portion of these classes and interfaces.

Table-22.6.gif

Table 22.6: Classes and Interfaces in the System.Security.Cryptography Namespace 

Listing 22.35 illustrates the use of DES and CryptoStream classes to encipher and decipher a file. 

Listing 22.35: Cryptostream1.cs, CryptoStream with DES 

// NOTE: Before you execute the program, first
// create a file named c:\myfile.txt with text "myname is bozo..." in it.
// After you execute the code, two files will be created on the c: drive.
// The c:\ciphered.txt file will include weird ciphered characters like
// "¼ş_Eó_ğNª_4û Õ?8Ò¤¤_"5"
// The c:\enciphered.txt file will be identical to c:\myfile.txt.

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;

class CryptoDESSample
{
    public static void Main(string[] args)
    {
        FileStream fsInput = new FileStream(@"c:\myfile.txt", FileMode.Open, FileAccess.Read);
        FileStream fsCiphered = new FileStream(@"c:\ciphered.txt", FileMode.Create, FileAccess.Write);
        DESCryptoServiceProvider ourDESProvider = new DESCryptoServiceProvider();

        // our 8 byte DES secret key is 12345678
        ourDESProvider.Key = ASCIIEncoding.ASCII.GetBytes("12345678");
        ourDESProvider.IV = ASCIIEncoding.ASCII.GetBytes("12345678");
        ICryptoTransform des1 = ourDESProvider.CreateEncryptor();
        ICryptoTransform des2 = ourDESProvider.CreateDecryptor();
        CryptoStream cryptostream1 = new CryptoStream(fsCiphered, des1, CryptoStreamMode.Write);
        byte[] bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream1.Write(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream1.Close();
        fsInput.Close();
        fsCiphered.Close();
        FileStream fsread = new FileStream(@"c:\ciphered.txt", FileMode.Open, FileAccess.Read);
        CryptoStream cryptostream2 = new CryptoStream(fsread, des2, CryptoStreamMode.Read);
        StreamWriter fsEnciphered = new StreamWriter(@"c:\enciphered.txt");
        fsEnciphered.Write(new StreamReader(cryptostream2).ReadToEnd());
        fsEnciphered.Flush();
        fsEnciphered.Close();
    }
}

The code in Listing 22.36 uses the SHA1 algorithm to compute the hash value of a given string. 

Listing 22.36: Hash1.cs, Hashing a String Using SHA-1 Algorithm 

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;

public class Class1
{
    public static void Main(string[] args)
    {
        String str1 = "MCBinc";
        Char[] char1a = str1.ToCharArray();
        Byte[] byte1a = new Byte[char1a.Length];

        for (int i = 0; i < byte1a.Length; i++)
            byte1a[i] = (Byte)char1a[i];

        // create hash value from str1 using SHA1 instance
        // returned by CryptoConfig

        byte[] hash1 = ((HashAlgorithm)
        CryptoConfig.CreateFromName("SHA1")).ComputeHash(byte1a);

        // or you can use directly created instance of the SHA1 class
        // byte[] hash1 = (new SHA1CryptoServiceProvider()).ComputeHash(byte1a );
        Console.WriteLine(str1 + @" hashed Value is <" +
        BitConverter.ToString(hash1) + @">");
        Console.ReadLine();
    }
}

The code in the listing writes the output in Figure 22.9 to the console. 

Figure-22.9.gif

Figure 22.9: Output Generated from Listing 22.36 

Conclusion

Hope this article would have helped you in understanding System.Security.Cryptography Namespace in .NET. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all