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

Simple encrypting and decrypting data in C#

By , 25 Dec 2003
 

Introduction

I am seeing a lot of questions people are asking on how to do encryption/decryption. To help those people, I have written a simple class incorporating several encryption/decryption functions:

  • byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) - encrypts a byte array with a key and an IV and returns a byte array;
  • string Encrypt(string clearText, string Password) - encrypts a string with a password and returns a string;
  • byte[] Encrypt(byte[] clearData, string Password) - encrypts a byte array with a password and returns a byte array;
  • void Encrypt(string fileIn, string fileOut, string Password) - encrypts a file with a password and writes the encrypted bytes into another file.

For each of those, there is also a corresponding Decrypt function. The Main method is a simple testing method that exercises some of those functions. The 2nd and the 3rd Encrypt functions call into the 1st function, so you will need to carry the 1st one around if you are using the 2nd or the 3rd. The last Encrypt function (the one that works with files) is standalone. I made it operate in a stream-like manner, without reading the whole file into memory, which makes it possible to encrypt/decrypt gigabytes of data without going out of memory space.

I am using Rijndael algorithm in this sample. The reason for this is that it is 100% implemented in managed code in our libraries, so it does not rely on CryptoAPI or any encryption packs and will work everywhere. If you need performance, I would suggest replacing it with TripleDES (it is a one line change), and if you do, also do not forget to change the IV size to 8 bytes and the Key size to 16 bytes.

I have tried to document the code well, and I would like to encourage you to read through it and understand how it works, it should be pretty easy. You can also grab the whole thing, stick it into a .cs file and it should compile. If you run it, you will see it make some test encryption/decryption roundtrip; you can also provide a file name as a parameter, and it will encrypt the file into a <name>.encrypted file and then decrypt it back into a <name>.decrypted.

Enjoy!

P.S. A crypto-related FAQ can be found here and there is a good chapter on how to use crypto in "Writing Secure Code" by Michael Howard (2nd edition came out recently). For in depth information on crypto in general, "Applied Cryptography" by Bruce Schneier is an excellent resource.

// 

//    This sample code is provided "AS IS" with no warranties,
//    and confers no rights. 
// 
//    ATTENTION: This sample is designed to be more of a
//    tutorial rather than something you can copy and paste in
//    the production code! 
// 

  

using System; 
using System.IO; 
using System.Security.Cryptography; 

// 
// Sample encrypt/decrypt functions 
// Parameter checks and error handling
// are ommited for better readability 
// 

public class EncDec 
{
    // Encrypt a byte array into a byte array using a key and an IV 
    public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) 
    { 
        // Create a MemoryStream to accept the encrypted bytes 
        MemoryStream ms = new MemoryStream(); 

        // Create a symmetric algorithm. 
        // We are going to use Rijndael because it is strong and
        // available on all platforms. 
        // You can use other algorithms, to do so substitute the
        // next line with something like 
        //      TripleDES alg = TripleDES.Create(); 
        Rijndael alg = Rijndael.Create(); 

        // Now set the key and the IV. 
        // We need the IV (Initialization Vector) because
        // the algorithm is operating in its default 
        // mode called CBC (Cipher Block Chaining).
        // The IV is XORed with the first block (8 byte) 
        // of the data before it is encrypted, and then each
        // encrypted block is XORed with the 
        // following block of plaintext.
        // This is done to make encryption more secure. 

        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure. 
        alg.Key = Key; 
        alg.IV = IV; 

        // Create a CryptoStream through which we are going to be
        // pumping our data. 
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream and the output will be written
        // in the MemoryStream we have provided. 
        CryptoStream cs = new CryptoStream(ms, 
           alg.CreateEncryptor(), CryptoStreamMode.Write); 

        // Write the data and make it do the encryption 
        cs.Write(clearData, 0, clearData.Length); 

        // Close the crypto stream (or do FlushFinalBlock). 
        // This will tell it that we have done our encryption and
        // there is no more data coming in, 
        // and it is now a good time to apply the padding and
        // finalize the encryption process. 
        cs.Close(); 

        // Now get the encrypted data from the MemoryStream.
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way. 
        byte[] encryptedData = ms.ToArray();

        return encryptedData; 
    } 

    // Encrypt a string into a string using a password 
    //    Uses Encrypt(byte[], byte[], byte[]) 

    public static string Encrypt(string clearText, string Password) 
    { 
        // First we need to turn the input string into a byte array. 
        byte[] clearBytes = 
          System.Text.Encoding.Unicode.GetBytes(clearText); 

        // Then, we need to turn the password into Key and IV 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        // Now get the key/IV and do the encryption using the
        // function that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size. 
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes. 
        byte[] encryptedData = Encrypt(clearBytes, 
                 pdb.GetBytes(32), pdb.GetBytes(16)); 

        // Now we need to turn the resulting byte array into a string. 
        // A common mistake would be to use an Encoding class for that.
        //It does not work because not all byte values can be
        // represented by characters. 
        // We are going to be using Base64 encoding that is designed
        //exactly for what we are trying to do. 
        return Convert.ToBase64String(encryptedData); 

    }
    
    // Encrypt bytes into bytes using a password 
    //    Uses Encrypt(byte[], byte[], byte[]) 

    public static byte[] Encrypt(byte[] clearData, string Password) 
    { 
        // We need to turn the password into Key and IV. 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        // Now get the key/IV and do the encryption using the function
        // that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is 8
        // bytes and so should be the IV size. 
        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes. 
        return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)); 

    }

    // Encrypt a file into another file using a password 
    public static void Encrypt(string fileIn, 
                string fileOut, string Password) 
    { 

        // First we are going to open the file streams 
        FileStream fsIn = new FileStream(fileIn, 
            FileMode.Open, FileAccess.Read); 
        FileStream fsOut = new FileStream(fileOut, 
            FileMode.OpenOrCreate, FileAccess.Write); 

        // Then we are going to derive a Key and an IV from the
        // Password and create an algorithm 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        Rijndael alg = Rijndael.Create(); 
        alg.Key = pdb.GetBytes(32); 
        alg.IV = pdb.GetBytes(16); 

        // Now create a crypto stream through which we are going
        // to be pumping data. 
        // Our fileOut is going to be receiving the encrypted bytes. 
        CryptoStream cs = new CryptoStream(fsOut, 
            alg.CreateEncryptor(), CryptoStreamMode.Write); 

        // Now will will initialize a buffer and will be processing
        // the input file in chunks. 
        // This is done to avoid reading the whole file (which can
        // be huge) into memory. 
        int bufferLen = 4096; 
        byte[] buffer = new byte[bufferLen]; 
        int bytesRead; 

        do { 
            // read a chunk of data from the input file 
            bytesRead = fsIn.Read(buffer, 0, bufferLen); 

            // encrypt it 
            cs.Write(buffer, 0, bytesRead); 
        } while(bytesRead != 0); 

        // close everything 

        // this will also close the unrelying fsOut stream
        cs.Close(); 
        fsIn.Close();     
    } 

    // Decrypt a byte array into a byte array using a key and an IV 
    public static byte[] Decrypt(byte[] cipherData, 
                                byte[] Key, byte[] IV) 
    { 
        // Create a MemoryStream that is going to accept the
        // decrypted bytes 
        MemoryStream ms = new MemoryStream(); 

        // Create a symmetric algorithm. 
        // We are going to use Rijndael because it is strong and
        // available on all platforms. 
        // You can use other algorithms, to do so substitute the next
        // line with something like 
        //     TripleDES alg = TripleDES.Create(); 
        Rijndael alg = Rijndael.Create(); 

        // Now set the key and the IV. 
        // We need the IV (Initialization Vector) because the algorithm
        // is operating in its default 
        // mode called CBC (Cipher Block Chaining). The IV is XORed with
        // the first block (8 byte) 
        // of the data after it is decrypted, and then each decrypted
        // block is XORed with the previous 
        // cipher block. This is done to make encryption more secure. 
        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure. 
        alg.Key = Key; 
        alg.IV = IV; 

        // Create a CryptoStream through which we are going to be
        // pumping our data. 
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream 
        // and the output will be written in the MemoryStream
        // we have provided. 
        CryptoStream cs = new CryptoStream(ms, 
            alg.CreateDecryptor(), CryptoStreamMode.Write); 

        // Write the data and make it do the decryption 
        cs.Write(cipherData, 0, cipherData.Length); 

        // Close the crypto stream (or do FlushFinalBlock). 
        // This will tell it that we have done our decryption
        // and there is no more data coming in, 
        // and it is now a good time to remove the padding
        // and finalize the decryption process. 
        cs.Close(); 

        // Now get the decrypted data from the MemoryStream. 
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way. 
        byte[] decryptedData = ms.ToArray(); 

        return decryptedData; 
    }

    // Decrypt a string into a string using a password 
    //    Uses Decrypt(byte[], byte[], byte[]) 

    public static string Decrypt(string cipherText, string Password) 
    { 
        // First we need to turn the input string into a byte array. 
        // We presume that Base64 encoding was used 
        byte[] cipherBytes = Convert.FromBase64String(cipherText); 

        // Then, we need to turn the password into Key and IV 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 
            0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        // Now get the key/IV and do the decryption using
        // the function that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first
        // getting 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by
        // default 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size. 
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes. 
        byte[] decryptedData = Decrypt(cipherBytes, 
            pdb.GetBytes(32), pdb.GetBytes(16)); 

        // Now we need to turn the resulting byte array into a string. 
        // A common mistake would be to use an Encoding class for that.
        // It does not work 
        // because not all byte values can be represented by characters. 
        // We are going to be using Base64 encoding that is 
        // designed exactly for what we are trying to do. 
        return System.Text.Encoding.Unicode.GetString(decryptedData); 
    }

    // Decrypt bytes into bytes using a password 
    //    Uses Decrypt(byte[], byte[], byte[]) 

    public static byte[] Decrypt(byte[] cipherData, string Password) 
    { 
        // We need to turn the password into Key and IV. 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        // Now get the key/IV and do the Decryption using the 
        //function that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size. 

        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes. 
        return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16)); 
    }

    // Decrypt a file into another file using a password 
    public static void Decrypt(string fileIn, 
                string fileOut, string Password) 
    { 
    
        // First we are going to open the file streams 
        FileStream fsIn = new FileStream(fileIn,
                    FileMode.Open, FileAccess.Read); 
        FileStream fsOut = new FileStream(fileOut,
                    FileMode.OpenOrCreate, FileAccess.Write); 
  
        // Then we are going to derive a Key and an IV from
        // the Password and create an algorithm 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 
        Rijndael alg = Rijndael.Create(); 

        alg.Key = pdb.GetBytes(32); 
        alg.IV = pdb.GetBytes(16); 

        // Now create a crypto stream through which we are going
        // to be pumping data. 
        // Our fileOut is going to be receiving the Decrypted bytes. 
        CryptoStream cs = new CryptoStream(fsOut, 
            alg.CreateDecryptor(), CryptoStreamMode.Write); 
  
        // Now will will initialize a buffer and will be 
        // processing the input file in chunks. 
        // This is done to avoid reading the whole file (which can be
        // huge) into memory. 
        int bufferLen = 4096; 
        byte[] buffer = new byte[bufferLen]; 
        int bytesRead; 

        do { 
            // read a chunk of data from the input file 
            bytesRead = fsIn.Read(buffer, 0, bufferLen); 

            // Decrypt it 
            cs.Write(buffer, 0, bytesRead); 

        } while(bytesRead != 0); 

        // close everything 
        cs.Close(); // this will also close the unrelying fsOut stream 
        fsIn.Close();     
    }
 }

Need a Main method to make this code complete? Write your own (it's quite simple) or visit this site, find this article there and grab it.

The encryption sample above had a very defined purpose - being extremely easy to read and understand. While it explains how to use symmetric encryption classes and gives some ideas on how to start implementing encryption in your applications, there are things you will have to do before it becomes a shippable piece of code. One of them I have already mentioned in the posting below - parameter checking and error handling. Check the parameters for being valid, wrap calls that can potentially fail into try/catch blocks, use finally blocks to release resources (close files) if something goes wrong, etc.

Some cryptography specific considerations should also be there. For example, the salt values in PasswordDeriveBytes should better be random rather than hard coded (sometimes it is ok to have them hard coded, for example, when encryption happens rarely and the code is not accessible by attackers). If the salt is random and changed frequently, you don't even have to keep it secret. Also, when possible, use byte[] keys as opposed to passwords. Because of the human factor, password-based encryption is not the most secure way to protect information. In order to get 128bit of key information out of a password, it has to be long. If you are using just small letters that give you about 5 bits of information per character and your password will have to be over 25 characters long to get to 128bit. If you are using capital letters and some symbols you can get to about 7 bits per character and your password minimum length will have to be around 18 characters (how long is your password? ;-)).

I also invite you to read my .NET-security centric blog.

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

About the Author

DotNetThis
Web Developer
United States United States
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberNicolai Kjaersgaard26-Nov-12 11:33 
Still quite good and useful
GeneralSimple encrypting and decrypting data in C#memberdeanoliv6-Aug-12 4:08 
This is just a thumbs up. This helped me a lot.
Questionother possible algorithmsmemberMember 920121118-Jul-12 21:50 
great article. thank you very much for sharing.
 
I managed to modify your code to use tripleDES algorithm i changed the algorithm and the byte sizes for both "Key" and "IV".
 
can you give me other possible algorithms and it's correct byte sizes for "Key" and "IV"?
ie: like the SHA1 I don't know what will be the byte size to set for "Key" and "IV".
 
your help would be greatly appreciated.
GeneralMy vote of 5memberMmohmmad16-Jul-12 2:37 
Well presented article
QuestionSimple encrypting and decrypting data in C# (please provide the code in php also) [modified]memberpriya mary18-May-12 23:49 
HI ,
i am using the .net code u provided for the decryption but i need to encrpt the result in php.
Will u please post the code in php for encrypting and decrypting data in C#?
I am in dire need of it.
the follwoing is the code i have in php
 
 
$pass="4111111111111111";
$salt="atevs36";
 
$result=Encrypt($pass,$salt);
function Encrypt($pass,$salt)
{
$derived = $this->PBKDF1($pass, $salt, 100, 48);

$key = bin2hex(substr($derived, 0, 32));
$iv = bin2hex(substr($derived, 0, 16));
try{
$passcrypt= mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $pass, MCRYPT_MODE_CBC, $iv);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$encode = base64_encode($passcrypt);
return $encode;
}
public function PBKDF1($pass, $salt, $count, $dklen)
{
$t = $pass.$salt;

$t = sha1($t, true);

for($i=2; $i <= $count; $i++)
{
$t = sha1($t, true);
}
$t = substr($t,0,$dklen);
return $t;
}
?>

modified 19-May-12 5:55am.

GeneralTHANKSmemberMatthew E East8-May-12 12:22 
This was really helpful!
GeneralMy vote of 5membermanoj kumar choubey29-Mar-12 20:11 
Nice
GeneralMy vote of 2memberAmol_B13-Feb-12 20:12 
no source file
QuestionGreat article but I need to understand why the output buffer is double the size.memberdinus31-Dec-11 11:44 
Hi DotNetThis,
 
I was wondering why the outbut buffer is double the size of the input buffer even in case my input, key and vector buffers are all equal to 16 bytes and I'm using 128 bit encryption.
 
Thank you.
GeneralMy vote of 5memberyazanjaradat16-Dec-11 6:56 
Excellent
GeneralMy vote of 3memberchandru20115-Dec-11 17:11 
nice for newbies
GeneralMy vote of 5memberMember 840931230-Nov-11 22:31 
good
QuestionA problem with your function.memberkilofafeure25-Sep-11 1:19 
Hi, with your code I've understood better the AES, but when I'm trying to do it work (when I try to decrypt) I ever obtain a value of Nothing. I've debugged and I obtain it on this line: cs.Close()
Any idea why can this happen? I did create an aspx to check the encrypt and decrypt and there it works fine (I've my DB examples encripted). The problems has come when I've made the call to the function since a web method. Any idea why and how to solve it? Thanks!
QuestionEncrypted string is very long!?memberNicRei23-Aug-11 11:58 
Hello,
 
the encrypted string is in comparison to the plain string very long. Is there a possibility, that the encrypted string has the same length or the similar length?
AnswerRe: Encrypted string is very long!?memberdinus1-Jan-12 9:45 
Hi NicRei,
 
Considering that you posted your question more than 4 months ago, you have probably found the answer to your question. I decided to reply to your polst so others could also see the answer.
The reason the output buffer is longer than the input buffer is because of block alignment. The algorythm works with blocks of data (16 bytes for 128 bit encryption, 32 bytes for 256 bits and so on, although the block size can be different from the key size). I was surprised to see though that even after encoding a block of 16 bytes of data with 128 bit key (and 128 bit block size) my output block size was 32 bit. I found that this was because of "padding". After turning it off (see RijndaelAlg.Padding = PaddingMode.None;) I was able to get my 16 bit output data block. Please note that if you turn of the padding then you have to take care of padding in your code. As an example, you could add zeroes to your input data in order to align it to the block size boundary and then treat the decrypted data accordingly.
 
Regards,
GeneralMy vote of 5memberkharisma1657-May-11 20:10 
Thank you very much, now I understand how AES file encryption works Smile | :)
GeneralMy vote of 5memberleonidf6717-Feb-11 21:20 
Very elegant code. Thank you very much.
GeneralMy vote of 5memberAlfredo Blanco27-Jan-11 6:29 
One more times is just what I was looking for: simple, efficient & understandable.
GeneralThank youmembermadhuraka9-Jan-11 21:21 
Thank you, this article is great and it causes to vanish my biggest headache.
GeneralQuestion about encryptmemberthready1-Jun-10 7:25 
Hi DotNetThis,
 
Looks good! Just that I'm confused about encrypted values. I see your Encrypt function takes strings and returns an encrypted string. Do we have to be using unicode ? (I need to learn to use it and have been very reluctant to do so). The reason I ask about unicode is because typically encrypted bytes often fall in the non-printable character range...
GeneralRe: Question about encryptmemberthready1-Jun-10 8:04 
Silly me - I just noticed the ToBase64String at the end. Cool! I'm using it.
 
Thanks,
Mike
GeneralThanks for a really helpful tutorial.memberMichael B Pliam23-Apr-10 6:13 
I have found this to be one of the clearest expositions on how to use the C# Rijndael features of .NET and have used it for my website.
 
I have one question: From your code, I have learned that C# string is a unicode string. Yet the byte arrays used for Key and IV appear to be 16-bit bytes. So I am confused as to whether the Rijndael EncDec inputs and outputs represent ansi strings or unicode strings. The reason that I ask is that I have a web client that needs to decrypt the bytes encrypted by your code. Unfortunately, this client is written in C++. I need a C++ version of Rijndael that uses Unicode (I think), but cannot find one that works.
 
Your thoughts greatly appreciated. And thanks again for all the beautiful documentation.
Generalwhy encrypted file sent via packet failed to get decryptedmemberVijay_G_Gupta13-Apr-10 19:20 
I have encryted one PDF file and sent it to another machine using the WinSocket program which sents the file in packets to the other machine
 
Now the problem is that the file which is received on the another machine fails to get decrypted
 
Can any one please help me since i am badly stuck in this
GeneralDecent coding but bad writingmemberDutchMafia10-Mar-10 4:06 
Let me first say that I appreciate the effort you've made to create the article and that it is useful and instructive.
 
As a rebuttal to the arguments in comments below, I want to point out that in my opinion in this line of code:
 
PasswordDeriveBytes pdb = new PasswordDeriveBytes(...
 
Calling a PasswordDeriveBytes object "pdb" is poor variable naming and you do this throughout your code. Using this object later in code requires someone to remember (or use intellisense) to know what the object is. I think a better name would be "pwdDerBytes" if not the full "passwordDeriveBytes". Or "pwdDerBytesObj". More typing? Yes, but more clear later when methods are called or properties set. The reason this is important is because someone might not be familiar with all these objects (like readers of your Code Project article). Let me show you an example of what this looks like to a newbie:
 
Object o = new Object(x, y, z);
o(x, y) = o(z / 2);
 
The line "o(x, y) = o(z / 2);" does something but tells the reader nothing about what's going on. The object Object is something but is unfamiliar so I know nothing about it from reading the object declaration. This is how unfamiliar code looks to someone when you use non-descriptive variable names.
 
Nitpicking? perhaps, but that's my opinion.
 
Additionally, your comment descriptions could use some review to shorten explanations. It's not that they are bad and I REALLY appreciate that you took the time to put them in but I do agree with other commentators that it makes your example look ugly and I think more difficult to read.
 
For example, in these lines:
 
// Now will will initialize a buffer and will be
// processing the input file in chunks.
 
Can be rewritten as "Initialize a buffer to process the input file in chunks". 15 words to 10 in one line.
 
If English is not your primary language then I think you've done a fine job and I commend your work but if it is, then I think you need to take more time trying to communicate clearly.
 
More nitpicking? perhaps, but that's my opinion.
 
I hope you take this constructively. My motivation for writing was also to offer help in writing for our developer community because I think what you're written is valuable and I would like to see more from you. I'd hate to think someone would skim over your article based on how it looks or how it's written, as I said before, the fact that you took the time to write in all the comments is invaluable. Thanks.
GeneralRe: Decent coding but bad writingmemberbfo200518-Mar-10 4:47 
I think you missed the point of the article.
 
Your critique is like a book reviewer doing the entire review on the font used in the book. An exercise in wasting energy. The article gets the relevant points across perfectly, that, after all, is its sole purpose. It is made abundantly clear in the source that it is not for copying and pasting into your production code.
 
If the user forgets what "pdb" is when it is used on the very next line of code after it's declaration and instantiation, then perhaps encryption/decryption is the least of their problems.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130619.1 | Last Updated 26 Dec 2003
Article Copyright 2003 by DotNetThis
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid