Click here to Skip to main content
15,884,472 members
Articles / Programming Languages / C#
Article

Encrypt/Decrypt String using DES in C#

Rate me:
Please Sign up or sign in to vote.
4.38/5 (34 votes)
9 Jul 2007CPOL2 min read 349.3K   13.6K   69   27
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.

C#
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:

C#
/// <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.

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

The ASCIIEncoding class is in the System.Text namespace.

Okay, let's see the last method Decrypt.

C#
/// <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Autumoon
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionEfficient Pin
Gluups9-Dec-19 14:17
Gluups9-Dec-19 14:17 
PraiseNice post Pin
shanbu_chi200817-Aug-16 17:23
shanbu_chi200817-Aug-16 17:23 
GeneralMy vote of 4 Pin
Md. Marufuzzaman7-Feb-15 5:32
professionalMd. Marufuzzaman7-Feb-15 5:32 
Questiondecrypt not work in ftp server Pin
surinderrawat27-Apr-14 21:45
surinderrawat27-Apr-14 21:45 
GeneralMy vote of 4 Pin
Amir Mohammad Nasrollahi29-Jul-13 0:38
professionalAmir Mohammad Nasrollahi29-Jul-13 0:38 
Questionmore about bytes variable? Pin
SurenSaluka6-Jun-13 3:35
SurenSaluka6-Jun-13 3:35 
QuestionEMERGENCY Pin
Member 99588781-Apr-13 21:36
Member 99588781-Apr-13 21:36 
Questionan easy question Pin
Hongyu Zhou198917-Feb-13 14:33
Hongyu Zhou198917-Feb-13 14:33 
QuestionThanks Pin
david-cor99930-Aug-11 8:31
david-cor99930-Aug-11 8:31 
GeneralMy vote of 5 Pin
wkblalock8-Feb-11 10:14
wkblalock8-Feb-11 10:14 
GeneralMy vote of 5 Pin
thirinwe20-Sep-10 18:23
thirinwe20-Sep-10 18:23 
GeneralGood on DES, see here for AES: http://www.davidezordan.net/blog/?p=202 Pin
Frank Jammes11-Sep-10 9:24
Frank Jammes11-Sep-10 9:24 
Generalthanks Pin
Mikyps25-Feb-10 2:16
Mikyps25-Feb-10 2:16 
Generallimit characters Pin
Member 35807641-Nov-09 6:31
Member 35807641-Nov-09 6:31 
QuestionIs there any way to generate encrypted text is less than 25 character? Pin
sonashish29-Sep-09 7:31
sonashish29-Sep-09 7:31 
GeneralCan't specify a key longer or shorter than 8 characters Pin
wayneo20004-Sep-09 15:52
wayneo20004-Sep-09 15:52 
GeneralThanks for this Pin
shekharp11-Jun-09 3:52
shekharp11-Jun-09 3:52 
GeneralYou'd better to use "Encoding.Default" Pin
RayShaw10-Dec-08 16:11
RayShaw10-Dec-08 16:11 
Generalquestion Pin
cmorenojorquera31-Oct-07 8:01
cmorenojorquera31-Oct-07 8:01 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 6:54
Tony Selke27-Sep-07 6:54 
You may also be interested in looking at the following, related Code Project articles:

Generic SymmetricAlgorithm Helper[^]
This is a generic helper class that exposes simplified Encrypt and Decrypt functionality for strings, byte arrays and streams for any SymmetricAlgorithm derivative (DES, RC2, Rijndael, TripleDES, etc.).

Making TripleDES Simple in VB.NET and C#[^]
This is a simple wrapper class that provides an easy interface for encrypting and decrypting byte arrays and strings using the 3DES algorithm.
GeneralRe: Two other related encryption articles in CodeProject ... Pin
Jacmac5-May-08 12:00
Jacmac5-May-08 12:00 
GeneralLike it. How about... Pin
Simon Hughes17-Jul-07 0:45
Simon Hughes17-Jul-07 0:45 
GeneralRe: Like it. How about... Pin
Xinwen Cheng26-Jul-07 17:00
Xinwen Cheng26-Jul-07 17:00 
GeneralDES isn't secure Pin
merlin98110-Jul-07 3:17
professionalmerlin98110-Jul-07 3:17 
GeneralRe: DES isn't secure Pin
Xinwen Cheng10-Jul-07 15:35
Xinwen Cheng10-Jul-07 15:35 

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

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