Click here to Skip to main content
12,063,909 members (60,893 online)
Click here to Skip to main content
Add your own
alternative version

Stats

164.1K views
7.3K downloads
41 bookmarked
Posted

Cryptography in C#

, 14 Apr 2004
Rate this:
Please Sign up or sign in to vote.
An article on cryptography in C#

Introduction

No so long ago, I faced a problem to keep passwords in my application. Passwords in my application were stored on hard drive in XML file, but in text mode, so anyone who has such rights to open this file, could view my passwords. So I decided to solve this problem by using cryptography and store only cipher of the passwords on hard drive. I did not need huge and complex algorithms like RSA or another open-key solutions, all I needed was just a simple class with two methods CryptoClass.Encrypt and CryptoClass.Decrypt. So look through MSDN library and search through Internet, but all information I found was a much more theoretical then practice. Also I found some examples at CodeProject, but one of them is about Web-Services security, and was too hard for my needs and another was an example in VB.NET in which I’m not so familiar with. After all that, I decided to write this simple cryptography class in C#. The way my class is different then other classes? Well I think it is pretty simple and good for use in small projects, and also maybe it will be useful for beginners. I commented code through each line, so I think these explanations would be enough.

Using the code

All you need to using this code in your projects is to compile code to dll, add a reference to you project from this dll and just create a new instance of crypto class in you project code, like:

Cryptography.Cryption Cryption = new Cryptography.Cryption(
  "Your key","Your vector");

Code Listing

public sealed class Cryption
  {
//members of the Cryption 
//algorithm type in my case it’s RijndaelManaged
    private RijndaelManaged Algorithm;
//memory stream
    private MemoryStream memStream;
//ICryptoTransform interface
    private ICryptoTransform EncryptorDecryptor;
//CryptoStream
    private CryptoStream crStream;
//Stream writer and Stream reader
    private StreamWriter strWriter;
    private StreamReader strReader;
//internal members
    private string m_key;
    private string m_iv;
//the Key and the Inicialization Vector
    private byte[] key;
    private byte[] iv;
//password view
    private string pwd_str;
    private byte[] pwd_byte;
//Constructor
    public Cryption(string key_val, string iv_val)
    {
      key = new byte[32];
      iv = new byte[32];

      int i;
      m_key = key_val;
      m_iv = iv_val;
//key calculation, depends on first constructor parameter
      for(i=0;i < m_key.Length;i++)
      {
        key[i] = Convert.ToByte(m_key[i]);
      }
//IV calculation, depends on second constructor parameter
      for(i=0;i < m_iv.Length;i++)
      {
        iv[i] = Convert.ToByte(m_iv[i]);
      }

    }
//Encrypt method implementation
    public string Encrypt(string s)
    {
//new instance of algorithm creation
      Algorithm = new RijndaelManaged();

//setting algorithm bit size
      Algorithm.BlockSize = 256;
      Algorithm.KeySize = 256;

//creating new instance of Memory stream
      memStream = new MemoryStream();

//creating new instance of the Encryptor
      EncryptorDecryptor = Algorithm.CreateEncryptor(key,iv);

//creating new instance of CryptoStream
      crStream = new CryptoStream(memStream, EncryptorDecryptor, 
      CryptoStreamMode.Write);

//creating new instance of Stream Writer
      strWriter = new StreamWriter(crStream);

//cipher input string
      strWriter.Write(s);

//clearing buffer for currnet writer and writing any 
//buffered data to //the underlying device
      strWriter.Flush();
      crStream.FlushFinalBlock();

//storing cipher string as byte array 
      pwd_byte = new byte[memStream.Length];
      memStream.Position = 0;
      memStream.Read(pwd_byte,0,(int)pwd_byte.Length);

//storing cipher string as Unicode string
      pwd_str = new UnicodeEncoding().GetString(pwd_byte);

      return pwd_str;
    }

//Decrypt method implementation 
    public string Decrypt(string s)
    {
//new instance of algorithm creation
      Algorithm = new RijndaelManaged();

//setting algorithm bit size
      Algorithm.BlockSize = 256;
      Algorithm.KeySize = 256;

//creating new Memory stream as stream for input string      
MemoryStream memStream = new MemoryStream(
   new UnicodeEncoding().GetBytes(s));

//Decryptor creating 
      ICryptoTransform EncryptorDecryptor = 
          Algorithm.CreateDecryptor(key,iv);

//setting memory stream position
      memStream.Position = 0;

//creating new instance of Crupto stream
      CryptoStream crStream = new CryptoStream(
          memStream,EncryptorDecryptor,CryptoStreamMode.Read);

//reading stream
      strReader = new StreamReader(crStream);

//returnig decrypted string
      return strReader.ReadToEnd();
    }
  }

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

Share

About the Author

Alex Getman
Web Developer
Ukraine Ukraine

You may also be interested in...

Comments and Discussions

 
QuestionNot Working On Decrypt Pin
crazy_louisth8-Jan-14 19:03
membercrazy_louisth8-Jan-14 19:03 
GeneralHelp me to resolve this problem Pin
Cryptogrpahy16-Mar-09 13:32
memberCryptogrpahy16-Mar-09 13:32 
GeneralA more elegant code Pin
Elmue29-Jan-08 8:18
memberElmue29-Jan-08 8:18 
GeneralNice class, but you forgot to mention something... Pin
Darkwinter4-Dec-07 1:12
memberDarkwinter4-Dec-07 1:12 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 8:10
memberTony Selke27-Sep-07 8:10 
GeneralThe decryption using the above logic fails!!!! Pin
Rageesh7-Apr-06 12:57
memberRageesh7-Apr-06 12:57 
GeneralMaybe you have changed the code in some way? The code works fine at my PC Pin
Alex Getman3-May-06 3:53
memberAlex Getman3-May-06 3:53 
GeneralRe: The decryption using the above logic fails!!!! [modified] Pin
spamshit26-Jun-06 6:42
memberspamshit26-Jun-06 6:42 
GeneralRe: The decryption using the above logic fails!!!! Pin
Alex Getman5-Jul-06 21:39
memberAlex Getman5-Jul-06 21:39 
GeneralRe: The decryption using the above logic fails!!!! Pin
damicolo20-Sep-06 0:00
memberdamicolo20-Sep-06 0:00 
GeneralRe: The decryption using the above logic fails!!!! Pin
Nick Lucas16-Jan-07 5:53
memberNick Lucas16-Jan-07 5:53 
GeneralRe: The decryption using the above logic fails!!!! Pin
winnypolo2-Oct-07 5:32
memberwinnypolo2-Oct-07 5:32 
GeneralThanks Pin
D@vid.drx3-Feb-06 6:33
memberD@vid.drx3-Feb-06 6:33 
GeneralThanks man... Pin
grimsonblade8-Sep-05 8:23
membergrimsonblade8-Sep-05 8:23 
GeneralProblem with web application..... Pin
taithien10-Aug-05 0:47
membertaithien10-Aug-05 0:47 
Generalnice simple app, but ... Pin
Lordas4-Jul-04 23:57
memberLordas4-Jul-04 23:57 
GeneralRe: nice simple app, but ... Pin
Carlos Groba23-Feb-06 23:05
memberCarlos Groba23-Feb-06 23:05 
Generalmsdn on cryptography... Pin
rugha19-Apr-04 23:16
memberrugha19-Apr-04 23:16 
Generalwhere to store the key Pin
Corinna John15-Apr-04 4:03
memberCorinna John15-Apr-04 4:03 
GeneralPasswords and cryptography Pin
Pecuchet15-Apr-04 3:55
memberPecuchet15-Apr-04 3:55 
GeneralOne-liner encryption for the lazy... Pin
MicrosoftBob15-Apr-04 11:14
memberMicrosoftBob15-Apr-04 11:14 
GeneralRe: One-liner encryption for the lazy... Pin
Anonymous16-Apr-04 3:03
sussAnonymous16-Apr-04 3:03 
GeneralRe: One-liner encryption for the lazy... Pin
MicrosoftBob16-Apr-04 3:25
memberMicrosoftBob16-Apr-04 3:25 
GeneralRe: One-liner encryption for the lazy... Pin
Anonymous16-Apr-04 3:03
sussAnonymous16-Apr-04 3:03 
GeneralRe: Passwords and cryptography Pin
andrew_g16-Apr-04 7:07
memberandrew_g16-Apr-04 7:07 
GeneralRe: Passwords and cryptography Pin
Pecuchet16-Apr-04 7:32
memberPecuchet16-Apr-04 7:32 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160204.4 | Last Updated 15 Apr 2004
Article Copyright 2004 by Alex Getman
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid