Click here to Skip to main content
Email Password   helpLost your password?

Introduction

While going through lot of articles on MSDN and on other sites, I wasn't able to get enough information in one go. So, I thought to write up an article which will cover up all the cryptography and that too with an example.

Description

The .NET Framework provides the following classes that implement:

Till now we have studied a lot about the Cryptography and the support given in .NET Framework 1.1. Let's take up a example for Encryption/Decryption of text.

Following is the Code of Encryption with �Rijndael� Algorithm. This is a class library developed in C#. You can use this code as a plug-in and use it for Encryption, Decryption and Hashing.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace JackTheGreat.Encryption.Cryptography
{
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace JackTheGreat.Encryption.Cryptography
{
  /// <summary>

  /// Summary description for EncryptData.

  /// </summary>

  public class CryptoLib
  {

    public System.Security.Cryptography.SymmetricAlgorithm mCryptProv;
    public System.Diagnostics.EventLog objEventLog;

    #region "Encrypt Function"
    public string Encrypt(string EncryptProvider, string EncryptStr, 
        int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 

      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it

      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception : " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try

        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones

        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
             mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
             " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
             " With Increment of " + 
             mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
             mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
             " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
             " With Increment of " + 
             mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 

      }
      
      try
      {
        //Change the supplied key to a byte array

        byte[] thisKey = stringtoByte(Key,KySize);
        
        //Hash the Supplied Secret key

        byte[] resultKey = HashOfByteArray(thisKey);
        
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];


        //Change the supplied IV to a byte array

        byte[] thisIV = stringtoByte(IV,BlckSize);
        //Hash the Supplied IV


        byte[] resultIV = HashOfByteArray(thisIV);
        //byte[] resultIV = thisIV;


      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Create the Encryptor, Passing that the Key and IV

        
        ICryptoTransform mEncryptor = 
             mCryptProv.CreateEncryptor(BlockKey, BlockIV);
      
        //Create Memory Stream

        System.IO.MemoryStream mMemStr = new MemoryStream();

        //Create the Crypto Stream,

        // Passing that the Memory Stream and Encryptor

        CryptoStream mCryptStr= new CryptoStream(mMemStr, 
                 mEncryptor, CryptoStreamMode.Write);
      
        //Convert the Supplied plaintext into a byte array

        byte[] bInput = stringtoByte(EncryptStr,512);
        //System.Text.Encoding.UTF8.GetBytes(EncryptStr);

        //stringtoByte(EncryptStr,512);


        // write out encrypted content into MemoryStream 

        mCryptStr.Write(bInput, 0, bInput.Length); 
        mCryptStr.FlushFinalBlock(); 
        
        // get the output and trim the '\0' bytes 

        byte[] bOutput = mMemStr.GetBuffer(); 

        int MemLength = System.Convert.ToInt32(mMemStr.Length);
      
        //Clean up the memory

        mCryptStr.Close();
        mMemStr.Close();
        mEncryptor.Dispose();

        // convert into Base64 so that the result can be used in xml 

        
        return Convert.ToBase64String(bOutput,0,MemLength); 
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        objEventLog = new System.Diagnostics.EventLog();
        objEventLog.Source = "SMP-CryptoGraphy";
        objEventLog.WriteEntry("Exception Occured in Encryption Process." +
                  " Error is = " +
                  ee.Message ,System.Diagnostics.EventLogEntryType.Error);
        objEventLog.Dispose();
        return("");
      }
     }
    #endregion
  
    #region "Decrypt Function"
    public string Decrypt(string EncryptProvider, string EncryptStr, 
            int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 

      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it

      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception-1: " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try

        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones

        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
              mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
              mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 

      }
      
      try
      {
        //Change the supplied key to a byte array

        byte[] thisKey = stringtoByte(Key,KySize);
        //Hash the Supplied Secret key


        byte[] resultKey = HashOfByteArray(thisKey);
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];

        //Change the supplied IV to a byte array

        byte[] thisIV = stringtoByte(IV,BlckSize);

        //Hash the Supplied IV

        byte[] resultIV = HashOfByteArray(thisIV);
      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Try to Decrypt values in the memory

        //First Create the Decryptor, By Passing Key and IV

        ICryptoTransform mDecrypt = 
            mCryptProv.CreateDecryptor(thisKey, thisIV);
          
        byte[] bInput = System.Convert.FromBase64String(EncryptStr); 
        
        // create a MemoryStream with the input 

        System.IO.MemoryStream ms = 
              new System.IO.MemoryStream(bInput, 0, bInput.Length); 

        //Create Crypto Stream

        CryptoStream mCSReader = 
              new CryptoStream(ms, mDecrypt, CryptoStreamMode.Read);

        // read out the result from the Crypto Stream 

        System.IO.StreamReader sr = new System.IO.StreamReader(mCSReader); 
      
        //Close the crypto stream

        mCSReader.Close();
        ms.Close();
        mDecrypt.Dispose();
        return sr.ReadToEnd(); 
      }
      catch(System.Exception ee)
      {
        return("Exception in processing " + ee.Message);
      }
    }
    #endregion

    #region "Hashing of a BYTE Array by using SHA512Managed -" +
            " return value is a Byte Array"
    private byte[] HashOfByteArray(byte[] ByteArray)
    {
      SHA512Managed sha512Key = new SHA512Managed();
      Sha512Key.ComputeHash(ByteArray);
      return(sha512Key.Hash);
    }
    #endregion
  
    #region "Hashing of a String by using SHA512Managed - " +
             "return value is a Base64 string"
    public string HashOfString(string PlainText)
    {
      //Change the supplied string to a byte array

      try
      {
        int thisSize = PlainText.Length*8;
        int temp;
        if(PlainText.Length<1)
        {
          return("Please enter a Valid String to Hash. String passed is " + 
                    PlainText.ToString());
          
        }
        byte[] thisStr = new byte[thisSize];
        int lastBound = PlainText.Length;
        if(lastBound > thisSize)lastBound = thisSize;
        for(temp = 0;temp<=lastBound - 1;temp++)
        {
          thisStr[temp] = Convert.ToByte(PlainText[temp]);
        }
      
        SHA512Managed sha512Key = new SHA512Managed();
        Sha512Key.ComputeHash(thisStr);
        return(Convert.ToBase64String(sha512Key.Hash));
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        return("Exception Occured in Hashing Process. Error is = " +
                ee.Message);
    
      }
    }
    #endregion
    
    #region "String to a byte array conversion -" +
          " return value is a BYTE array"
    private byte[] stringtoByte(string textdata,int keySize)
    {
      int thisSize = (keySize / 8);
      int temp;
      byte[] returnByteArray = new byte[thisSize];
      int lastBound = textdata.Length;
      if(lastBound > thisSize)lastBound = thisSize;
      for(temp = 0;temp<=lastBound - 1;temp++)
      {
        returnByteArray[temp] = Convert.ToByte(textdata[temp]);
      }
      return(returnByteArray);
    }
    #endregion
  }

}
/// <summary>

  /// Summary description for EncryptData.

  /// </summary>

  public class CryptoLib
  {

    public System.Security.Cryptography.SymmetricAlgorithm mCryptProv;
    public System.Diagnostics.EventLog objEventLog;

    #region "Encrypt Function"
    public string Encrypt(string EncryptProvider, string EncryptStr, 
         int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 

      if(EncryptProvider.Length<=0)
      {
              return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it

      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception : " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try

        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones

        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
              mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
              mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
              " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
              " With Increment of " + 
              mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 

      }
      
      try
      {
        //Change the supplied key to a byte array

        byte[] thisKey = stringtoByte(Key,KySize);
        
        //Hash the Supplied Secret key

        byte[] resultKey = HashOfByteArray(thisKey);
        
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ ) 
          BlockKey[loop] = resultKey[loop];


        //Change the supplied IV to a byte array

        byte[] thisIV = stringtoByte(IV,BlckSize);
        //Hash the Supplied IV


        byte[] resultIV = HashOfByteArray(thisIV);
        //byte[] resultIV = thisIV;


      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Create the Encryptor, Passing that the Key and IV

        
        ICryptoTransform mEncryptor = 
             mCryptProv.CreateEncryptor(BlockKey, BlockIV);
      
        //Create Memory Stream

        System.IO.MemoryStream mMemStr = new MemoryStream();

        //Create the Crypto Stream, 

        //Passing that the Memory Stream and Encryptor

        CryptoStream mCryptStr= 
           new CryptoStream(mMemStr, mEncryptor, CryptoStreamMode.Write);
      
        //Convert the Supplied plaintext into a byte array

        byte[] bInput = stringtoByte(EncryptStr,512);
        //System.Text.Encoding.UTF8.GetBytes(EncryptStr);

        //stringtoByte(EncryptStr,512);


        // write out encrypted content into MemoryStream 

        mCryptStr.Write(bInput, 0, bInput.Length); 
        mCryptStr.FlushFinalBlock(); 
        
        // get the output and trim the '\0' bytes 

        byte[] bOutput = mMemStr.GetBuffer(); 

        int MemLength = System.Convert.ToInt32(mMemStr.Length);
      
        //Clean up the memory

        mCryptStr.Close();
        mMemStr.Close();
        mEncryptor.Dispose();

        // convert into Base64 so that the result can be used in xml 

        
        return Convert.ToBase64String(bOutput,0,MemLength); 
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        objEventLog = new System.Diagnostics.EventLog();
        objEventLog.Source = "SMP-CryptoGraphy";
        objEventLog.WriteEntry("Exception Occured in Encryption " +
                "Process. Error is = " + ee.Message, 
                System.Diagnostics.EventLogEntryType.Error);
        objEventLog.Dispose();
        return("");
      }
     }
    #endregion
  
    #region "Decrypt Function"
    public string Decrypt(string EncryptProvider, string EncryptStr, 
           int BlckSize, int KySize, string Key, string IV)
    {
      //Check if something Algo is Selected 

      if(EncryptProvider.Length<=0)
      {
        return("Pass an Algo to use to Encrypt.");
      }
    
      //Since, The selected algo may not be Symmetric, So Try it

      try
      {
        mCryptProv = SymmetricAlgorithm.Create(EncryptProvider);
        mCryptProv.Mode = CipherMode.CBC;
      }
      catch(Exception ee)
      {
        return("Exception-1: " + ee.Message);
      }
      try
      {
        //Each Algo has different Size of Key and Block, So let's try

        mCryptProv.BlockSize = BlckSize;
        mCryptProv.KeySize = KySize;
      }
      catch
      {
        //Invalid Block or Key Size. Show the Default Ones

        string mStr;
        mStr = mCryptProv.BlockSize.ToString();
        mStr += "Invalid Block or Key Size.Valid Sizes are : "; 
        mStr += "Block Size = " + 
               mCryptProv.LegalBlockSizes[0].MinSize.ToString() + 
               " - " + mCryptProv.LegalBlockSizes[0].MaxSize.ToString() + 
               " With Increment of " + 
               mCryptProv.LegalBlockSizes[0].SkipSize.ToString();
        mStr += "Key  Size = " + 
               mCryptProv.LegalKeySizes[0].MinSize.ToString() + 
               " - " + mCryptProv.LegalKeySizes[0].MaxSize.ToString() + 
               " With Increment of " + 
               mCryptProv.LegalKeySizes[0].SkipSize.ToString();
        return(mStr);
        //Show the Valid Block Size 

      }
      
      try
      {
        //Change the supplied key to a byte array

        byte[] thisKey = stringtoByte(Key,KySize);
        //Hash the Supplied Secret key


        byte[] resultKey = HashOfByteArray(thisKey);
        int loopTill=0;
        if(BlckSize==128)loopTill=16;
        if(BlckSize==192)loopTill=24;
        if(BlckSize==256)loopTill=32;

        byte[] BlockKey = new byte[loopTill];
        for(int loop=0; loop<loopTill; loop++ )
          BlockKey[loop] = resultKey[loop];

        //Change the supplied IV to a byte array

        byte[] thisIV = stringtoByte(IV,BlckSize);

        //Hash the Supplied IV

        byte[] resultIV = HashOfByteArray(thisIV);
      
        byte[] BlockIV = new byte[loopTill];
        for( int loop=0; loop<loopTill; loop++ )
          BlockIV[loop] = resultIV[loop];

        //Try to Decrypt values in the memory

        //First Create the Decryptor, By Passing Key and IV

        ICryptoTransform mDecrypt = 
             mCryptProv.CreateDecryptor(thisKey, thisIV);
          
        byte[] bInput = System.Convert.FromBase64String(EncryptStr); 
        
        // create a MemoryStream with the input 

        System.IO.MemoryStream ms = 
             new System.IO.MemoryStream(bInput, 0, bInput.Length); 

        //Create Crypto Stream

        CryptoStream mCSReader = 
             new CryptoStream(ms, mDecrypt, CryptoStreamMode.Read);

        // read out the result from the Crypto Stream 

        System.IO.StreamReader sr = new System.IO.StreamReader(mCSReader); 
      
        //Close the crypto stream

        mCSReader.Close();
        ms.Close();
        mDecrypt.Dispose();
        return sr.ReadToEnd(); 
      }
      catch(System.Exception ee)
      {
        return("Exception in processing " + ee.Message);
      }
    }
    #endregion

    #region "Hashing of a BYTE Array by using SHA512Managed -" +
                   " return value is a Byte Array"
    private byte[] HashOfByteArray(byte[] ByteArray)
    {
      SHA512Managed sha512Key = new SHA512Managed();
      Sha512Key.ComputeHash(ByteArray);
      return(sha512Key.Hash);
    }
    #endregion
  
    #region "Hashing of a String by using SHA512Managed - " +
                   "return value is a Base64 string"
    public string HashOfString(string PlainText)
    {
      //Change the supplied string to a byte array

      try
      {
        int thisSize = PlainText.Length*8;
        int temp;
        if(PlainText.Length<1)
        {
          return("Please enter a Valid String to Hash. String passed is " + 
                  PlainText.ToString());
          
        }
        byte[] thisStr = new byte[thisSize];
        int lastBound = PlainText.Length;
        if(lastBound > thisSize)lastBound = thisSize;
        for(temp = 0;temp<=lastBound - 1;temp++)
        {
          thisStr[temp] = Convert.ToByte(PlainText[temp]);
        }
      
        SHA512Managed sha512Key = new SHA512Managed();
        Sha512Key.ComputeHash(thisStr);
        return(Convert.ToBase64String(sha512Key.Hash));
      }
      catch(System.Security.Cryptography.CryptographicException ee)
      {
        return("Exception Occured in Hashing Process. Error is = " + 
                 ee.Message);
    
      }
    }
    #endregion
    
    #region "String to a byte array conversion - " +
          "return value is a BYTE array"
    private byte[] stringtoByte(string textdata,int keySize)
    {
      int thisSize = (keySize / 8);
      int temp;
      byte[] returnByteArray = new byte[thisSize];
      int lastBound = textdata.Length;
      if(lastBound > thisSize)lastBound = thisSize;
      for(temp = 0;temp<=lastBound - 1;temp++)
      {
        returnByteArray[temp] = Convert.ToByte(textdata[temp]);
      }
      return(returnByteArray);
    }
    #endregion
  }

}
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
NewsTwo other related encryption articles in CodeProject ...
Tony Selke
8:05 27 Sep '07  
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.

GeneralProblem with DES secret key
sortgnz
6:22 16 May '07  
Hello friend.

Now I am developing an application and i've got problems trying to use .net framework Cryptography:

- I am not allowed to Cipher/Decipher any data with key {0,0,0,0,0,0,0,0}

The frameworks said to me that is a "weak key", but some devices use this key on default (some kind of cards).

Is any way to avoid this .net check ?
Or Have I to develop my own Des class?

Thanks for your help.


Nacho

QuestionHelp with TripleDES Cryptography
Sreerag Gopinath
2:02 10 Oct '06  
Hi Atul,
   I read your article "All about Cryptography in .NET" on codeproject.com.
   I myself faced (am still facing) the same problem of insufficent information on .net cryptography.
   I am developing a project that uses all the encryption and decryption algorithms provided by .net.
   My aim is to perform cryptography by allowing the user to enter a password (I derive the key from this password). The user may save the ciphertext and terminate the program. Later, he may want to retrieve the plaintext form the saved ciphertext. He has to enter the same password for this.
I wrote the following code for this, but it gives me an exception.
   I'd be very grateful if you could help me.

**************************************************************************************

/* Provides TripleDES encryption and decryption using classes in the .net Framework 1.1 */
     public class TripleDES_Cryptography
     {
         
          public static byte[] createRandomSalt(int Length)
          {
               // Create a buffer
               byte[] randBytes;

               if (Length >= 1)
               {
                    randBytes = new byte[Length];
               }
               else
               {
                    randBytes = new byte[1];
               }
              
               // Create a new RNGCryptoServiceProvider.
               RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();

               // Fill the buffer with random bytes.
               rand.GetBytes(randBytes);

               // return the bytes.
               return randBytes;
          }

          public static void clearBytes(byte[] Buffer)
          {
               // Check arguments.
               if (Buffer == null)
               {
                    throw new ArgumentException("Buffer");
               }

               // Set each byte in the buffer to 0.
               for (int x = 0; x <= Buffer.Length - 1; x++)
               {
                    Buffer[x] = 0;
               }

          }
         
         
          public static string Encrypt(string plaintext, string key, string IV)
          {
               TripleDES des3 = new TripleDESCryptoServiceProvider();
               des3.Mode = CipherMode.CBC;

               byte[] salt            =   createRandomSalt(7);
               byte[] by_plaintext =     Encoding.ASCII.GetBytes(plaintext);                          byte[] by_IV          =     Encoding.ASCII.GetBytes(IV);              

              
               string     strPassWd = key;
               PasswordDeriveBytes pdb = new PasswordDeriveBytes(strPassWd,salt);
              
               des3.IV   = by_IV;
               des3.Key = pdb.CryptDeriveKey("TripleDES","SHA1",192,des3.IV);              
              
               ICryptoTransform Encryptor = des3.CreateEncryptor(des3.Key,des3.IV);

               MemoryStream ms = new MemoryStream();
               ms.Write(by_plaintext,0,by_plaintext.Length);
               CryptoStream cs = new CryptoStream(ms,Encryptor,CryptoStreamMode.Write);

               byte[] by_ciphertext = ms.ToArray();
                    string ciphertext      = Convert.ToBase64String( by_ciphertext );                   

               cs.Close();
               clearBytes(salt);
               des3.Clear();
              
               return ciphertext;

          }

          public static string Decrypt(string ciphertext, string key, string IV)
          {
               DES des3 = new DESCryptoServiceProvider();
               des3.Mode = CipherMode.CBC;

               byte[] salt                 =   createRandomSalt(7);
               byte[] by_ciphertext = Convert.FromBase64String(ciphertext);
               byte[] by_IV        =     Encoding.ASCII.GetBytes(IV);           
              
               string strPw     = key;
               PasswordDeriveBytes pdb = new PasswordDeriveBytes(strPw,salt);
              
               des3.IV   = by_IV;
               des3.Key = pdb.CryptDeriveKey("TripleDES","SHA1",192,des3.IV);
                             
               ICryptoTransform Decryptor = des3.CreateDecryptor(des3.Key,des3.IV);

               MemoryStream ms = new MemoryStream();
               ms.Write(by_ciphertext,0,by_ciphertext.Length);
               CryptoStream cs = new CryptoStream(ms,Decryptor,CryptoStreamMode.Write);

               byte[] by_plaintext = ms.ToArray();
               string plaintext      =     Encoding.ASCII.GetString(by_plaintext);

               cs.Close();

               clearBytes(salt);
               des3.Clear();
               return plaintext;
          }
     }

GeneralEmpty result from decrypt
eugenevd
6:22 17 Aug '05  
Hi,

I've been trying out this code today, and it seems like the encrypter works fine, it returns an encrypted string. Yet, when I send this string to be decrypted, I get an empty string "". Any tips/help?

---narf!


Last Updated 21 Dec 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010