Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Encrypt/Decrypt String using DES in C#

0.00/5 (No votes)
9 Jul 2007 6  
Use DES to encrypt/decrypt a string in C#

Introduction

This article aims to show you how to use DES to encrypt or decrypt a string.

Prerequisites

  1. Familiarity with C# programming
  2. Familiarity with Console Application

Using the Code

First of all, your application needs an entrance to let a user in, missing the Main() method is a compile-time error.

static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Original String: ");
        string originalString = Console.ReadLine();
        string cryptedString = Encrypt(originalString);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("\nEncrypt Result: {0}", cryptedString);
        Console.WriteLine("Decrypt Result: {0}", Decrypt(cryptedString));
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("From: {0}.\nDetail: {1}", ex.Source, ex.Message);
    }
    finally
    {
        Console.ReadLine();
    }
}

You can also make it as a Windows Forms application if you like, but this is not our key point. Let's go through the code. There are two customer-defined methods using DES, Encrypt and Decrypt, both receive a string and return another string. Let's take a look at the details. BTW, the Console.ReadLine method in the finally block aims to pause the screen.

Let's see the Encrypt method first:

/// <summary>
/// Encrypt a string.
/// </summary>
/// <param name="originalString">The original string.</param>
/// <returns>The encrypted string.</returns>
/// <exception cref="ArgumentNullException">This exception will be 
/// thrown when the original string is null or empty.</exception>
public static string Encrypt(string originalString)
{
    if (String.IsNullOrEmpty(originalString))
    {
        throw new ArgumentNullException
               ("The string which needs to be encrypted can not be null.");
    } 
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, 
        cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
    StreamWriter writer = new StreamWriter(cryptoStream);
    writer.Write(originalString);
    writer.Flush();
    cryptoStream.FlushFinalBlock();
    writer.Flush();
    return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}

First, you should verify whether the input string is valid. Then, you need to define an instance of the DESCryptoServiceProvider class and use its methods, and you need a stream to keep the result. In my sample, I used MemoryStream. If you want to store your result into a file directly, you should use FileStream, or something similar. The CryptoStream links data streams to cryptographic transformations, and there is a variable named bytes in its parameter. The first one is used as specified key, and the second one is used as initialization vector, both of them can use the same one. I'll show you how to define it. Then, we also need a StreamWriter to write the result to the stream and keep it. After that, we can return the result to the user.

static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("ZeroCool");

The ASCIIEncoding class is in the System.Text namespace.

Okay, let's see the last method Decrypt.

/// <summary>
/// Decrypt a crypted string.
/// </summary>
/// <param name="cryptedString">The crypted string.</param>
/// <returns>The decrypted string.</returns>
/// <exception cref="ArgumentNullException">This exception will be thrown 
/// when the crypted string is null or empty.</exception>
public static string Decrypt(string cryptedString)
{
    if (String.IsNullOrEmpty(cryptedString))
    {
        throw new ArgumentNullException
           ("The string which needs to be decrypted can not be null.");
    }
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    MemoryStream memoryStream = new MemoryStream
            (Convert.FromBase64String(cryptedString));
    CryptoStream cryptoStream = new CryptoStream(memoryStream, 
        cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
    StreamReader reader = new StreamReader(cryptoStream);
    return reader.ReadToEnd();
}

Like Encrypt, we need to verify the input string first, and use DescryptoServiceProvider, MemoryStream, CryptoStream and StreamReader to deal with our job. Obviously, the difference is cryptoProvider.CreateDecryptor in there, and when we want to encrypt a string, we use the cryptoProvider.CreateEncryptor method. Secondly, we use StreamReader when we decrypt an encrypted string.

Ok, that's all, let your code run!

Points of Interest

Using DES, you can encrypt or decrypt users' passwords or something else, and you can delve into the algorithm if you like.

Good luck!

History

  • 9th July, 2007: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here