Click here to Skip to main content
15,123,509 members
Articles / Programming Languages / C#
Posted 9 Jul 2007


68 bookmarked

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
Use DES to encrypt/decrypt a string in C#


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


  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)
        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);

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);
    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
    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!


  • 9th July, 2007: Initial post


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

Comments and Discussions

QuestionEfficient Pin
Gluups9-Dec-19 15:17
MemberGluups9-Dec-19 15:17 
PraiseNice post Pin
shanbu_chi200817-Aug-16 18:23
Membershanbu_chi200817-Aug-16 18:23 
GeneralMy vote of 4 Pin
Md. Marufuzzaman7-Feb-15 6:32
professionalMd. Marufuzzaman7-Feb-15 6:32 
Questiondecrypt not work in ftp server Pin
surinderrawat27-Apr-14 22:45
Membersurinderrawat27-Apr-14 22:45 
GeneralMy vote of 4 Pin
Amir Mohammad Nasrollahi29-Jul-13 1:38
professionalAmir Mohammad Nasrollahi29-Jul-13 1:38 
Questionmore about bytes variable? Pin
SurenSaluka6-Jun-13 4:35
MemberSurenSaluka6-Jun-13 4:35 
Member 99588781-Apr-13 22:36
MemberMember 99588781-Apr-13 22:36 
Questionan easy question Pin
Hongyu Zhou198917-Feb-13 15:33
MemberHongyu Zhou198917-Feb-13 15:33 
QuestionThanks Pin
david-cor99930-Aug-11 9:31
Memberdavid-cor99930-Aug-11 9:31 
GeneralMy vote of 5 Pin
wkblalock8-Feb-11 11:14
Memberwkblalock8-Feb-11 11:14 
GeneralMy vote of 5 Pin
thirinwe20-Sep-10 19:23
Memberthirinwe20-Sep-10 19:23 
GeneralGood on DES, see here for AES: Pin
Frank Jammes11-Sep-10 10:24
MemberFrank Jammes11-Sep-10 10:24 
Generalthanks Pin
Mikyps25-Feb-10 3:16
MemberMikyps25-Feb-10 3:16 
Generallimit characters Pin
Member 35807641-Nov-09 7:31
MemberMember 35807641-Nov-09 7:31 
QuestionIs there any way to generate encrypted text is less than 25 character? Pin
sonashish29-Sep-09 8:31
Membersonashish29-Sep-09 8:31 
GeneralCan't specify a key longer or shorter than 8 characters Pin
wayneo20004-Sep-09 16:52
Memberwayneo20004-Sep-09 16:52 
GeneralThanks for this Pin
shekharp11-Jun-09 4:52
Membershekharp11-Jun-09 4:52 
GeneralYou'd better to use "Encoding.Default" Pin
RayShaw10-Dec-08 17:11
MemberRayShaw10-Dec-08 17:11 
Generalquestion Pin
cmorenojorquera31-Oct-07 9:01
Membercmorenojorquera31-Oct-07 9:01 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 7:54
MemberTony Selke27-Sep-07 7:54 
GeneralRe: Two other related encryption articles in CodeProject ... Pin
Jacmac5-May-08 13:00
MemberJacmac5-May-08 13:00 
GeneralLike it. How about... Pin
Simon Hughes17-Jul-07 1:45
MemberSimon Hughes17-Jul-07 1:45 
GeneralRe: Like it. How about... Pin
Xinwen Cheng26-Jul-07 18:00
MemberXinwen Cheng26-Jul-07 18:00 
GeneralDES isn't secure Pin
merlin98110-Jul-07 4:17
professionalmerlin98110-Jul-07 4:17 
GeneralRe: DES isn't secure Pin
Xinwen Cheng10-Jul-07 16:35
MemberXinwen Cheng10-Jul-07 16: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.