Click here to Skip to main content
Click here to Skip to main content

Encrypt/Decrypt String using DES in C#

, 9 Jul 2007
Rate this:
Please Sign up or sign in to vote.
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:

/// <span class="code-SummaryComment"><summary></span>
/// Encrypt a string.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="originalString">The original string.</param></span>
/// <span class="code-SummaryComment"><returns>The encrypted string.</returns></span>
/// <span class="code-SummaryComment"><exception cref="ArgumentNullException">This exception will be </span>
/// thrown when the original string is null or empty.<span class="code-SummaryComment"></exception></span>
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.

/// <span class="code-SummaryComment"><summary></span>
/// Decrypt a crypted string.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="cryptedString">The crypted string.</param></span>
/// <span class="code-SummaryComment"><returns>The decrypted string.</returns></span>
/// <span class="code-SummaryComment"><exception cref="ArgumentNullException">This exception will be thrown </span>
/// when the crypted string is null or empty.<span class="code-SummaryComment"></exception></span>
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Xinwen Cheng
Software Developer Autumoon
China China
No Biography provided
Follow on   Twitter

Comments and Discussions

 
Questiondecrypt not work in ftp server Pinmembersurinderrawat27-Apr-14 21:45 
GeneralMy vote of 4 PinprofessionalAmir Mohammad Nasrollahi29-Jul-13 0:38 
Questionmore about bytes variable? PinmemberSurenSaluka6-Jun-13 3:35 
QuestionEMERGENCY PinmemberMember 99588781-Apr-13 21:36 
Questionan easy question PinmemberZhou Oscar17-Feb-13 14:33 
QuestionThanks Pinmemberdavid-cor99930-Aug-11 8:31 
GeneralMy vote of 5 Pinmemberwkblalock8-Feb-11 10:14 
GeneralMy vote of 5 Pinmemberthirinwe20-Sep-10 18:23 
GeneralGood on DES, see here for AES: http://www.davidezordan.net/blog/?p=202 PinmemberFrank Jammes11-Sep-10 9:24 
Generalthanks PinmemberMikyps25-Feb-10 2:16 
Generallimit characters PinmemberMember 35807641-Nov-09 6:31 
QuestionIs there any way to generate encrypted text is less than 25 character? Pinmembersonashish29-Sep-09 7:31 
GeneralCan't specify a key longer or shorter than 8 characters Pinmemberwayneo20004-Sep-09 15:52 
GeneralThanks for this Pinmembershekharp11-Jun-09 3:52 
GeneralYou'd better to use "Encoding.Default" Pinmemberdemogodyou10-Dec-08 16:11 
Generalquestion Pinmembercmorenojorquera31-Oct-07 8:01 
NewsTwo other related encryption articles in CodeProject ... PinmemberTony Selke27-Sep-07 6:54 
GeneralRe: Two other related encryption articles in CodeProject ... PinmemberJacmac5-May-08 12:00 
GeneralLike it. How about... PinmemberSimon Hughes17-Jul-07 0:45 
GeneralRe: Like it. How about... PinmemberXinwen Cheng26-Jul-07 17:00 
GeneralDES isn't secure Pinmembermerlin98110-Jul-07 3:17 
GeneralRe: DES isn't secure PinmemberXinwen Cheng10-Jul-07 15:35 
General56 bits key PinmemberFilip Geens10-Jul-07 1:22 
GeneralRe: Filip Geens PinmemberXinwen Cheng10-Jul-07 15:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 9 Jul 2007
Article Copyright 2007 by Xinwen Cheng
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid