My Disclaimer:

The purpose of this post is only to show methods of encryption used in the .net framework. In no way do I claim to be any expert in cryptography. Again my only goal here is to show the methods used in the .net framework. This post was inspired both by “Better Know a Framework” from DotNetRocks. And a talk by Jeff Moser, given at the Indy Code Camp 2008.

The System.Security.Cyptopgraphy namspace contains may classes and methods for encrypting and decrypting data. In this post I’m going to discuss the DES method of encryption. In later posts I plan on discussing each of the implementations symmetric and asymmetric cryptography in the .net framework.

The DES method uses the symmetric encryption algorithm (also called a cipher). Symmetric encryption is fast and well suited for encrypting large quantities of data.

DES Concerns

The DES algorithm is now considered by today’s standards to be insecure, mainly do to the fact that it uses a 56-bit key. Another disadvantages of DES is that because it uses symmetric encyption it presumes that two parties have already agreed on a key. The key itself cannot be encrypted and depends heavily on a secure channel to send the key to the other party. For example: If you send the key to your friend in an email, but your email was captured. Or you could relay the key over the phone, if your phone were tapped or someone overheard your conversation. The result is a third part has your key.

 The following code is a very basic example on how to encrypt a text file using DES. 


Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module Module1

    Sub Main()
        MyDESEncyption()
    End Sub

    Sub MyDESEncyption()

        Dim input As String = "C:\TestFile.txt"
        Dim output As String = "C:\TestFile.txt.enc"

        'File Stream object
        Dim infile As FileStream = New FileStream(input, FileMode.Open, FileAccess.Read)
        Dim outfile As FileStream = New FileStream(output, FileMode.OpenOrCreate, FileAccess.Write)

        'Create Symmetric Algortithm object as a new DES Algorithm object
        Dim DESAlg As SymmetricAlgorithm = New DESCryptoServiceProvider

        'MustOverride method that generates a random key
        DESAlg.GenerateKey()

        'Read plain text file
        Dim fileData(infile.Length - 1) As Byte
        infile.Read(fileData, 0, CType(infile.Length, Integer))

        'Create the ICryptoTransform object
        Dim encytptor As ICryptoTransform = DESAlg.CreateDecryptor

        'Create the CryptoStream object
        Dim encryptStrm As CryptoStream = New CryptoStream(outfile, encytptor, CryptoStreamMode.Write)

        'Write to the CryptoStream
        encryptStrm.Write(fileData, 0, fileData.Length)

        'Close the file hanles
        infile.Close()
        outfile.Close()

    End Sub
End Module

For more information on DES cyprography: