Click here to Skip to main content
15,881,380 members
Articles / Security / Cryptography
Alternative
Article

Secret Key Encryption Demo

Rate me:
Please Sign up or sign in to vote.
4.94/5 (17 votes)
6 Jun 2013CPOL1 min read 54K   3.3K   40   23
This is an alternative for "Secret Key Encryption Demo"

Encryption

Introduction

Encryption is the process of transforming electronic data from a "plain text" state to an unreadable state by use of a cipher, also known as an algorithm.

Although formerly pretty complex, encryption can now be implemented very easily in any .NET application using the various encryption classes in the System.Security.Cryptography namespace.

I've put together an encryption demo program that demonstrates how to encrypt and decrypt documents using the following encryption methods:

  • AES (Advanced Encryption Standard)
  • DES (Data Encryption Standard)
  • RC2 ("Ron's Code" or "Rivest Cipher")
  • Rijndael
  • Triple DES (Triple Data Encryption Standard)

This application uses persistent keys in combination with the respective algorithms to encrypt and decrypt data.

When appropriate, you will see a C# snippet first, and then a VB version of the same.

Using the Code

  • Pass the selected file to the Encrypt and Decrypt methods below:
  • VB.NET
    Dim path As String = "C:\temp\Encryption\Encrypt-decrypt.doc"
    Dim encrytedPath As String = String.Empty
    
    encrytedPath = Encrypt(path)
    MessageBox.Show("The following file has been encrypted:" & _
                              vbCrLf & vbCrLf & encrytedPath)
    
    path = Decrypt(encrytedPath)
    MessageBox.Show("The following file has been decrypted:" & _
                              vbCrLf & vbCrLf & path)
  • Declare the instance of the AES class that will be used to encrypt and decrypt:
  • C#
    //Create the a new instance of AES
    private System.Security.Cryptography.Aes mAes = System.Security.Cryptography.Aes.Create();
    VB.NET
    'Create the a new instance of AES
    Private mAes As System.Security.Cryptography.Aes = _
                             System.Security.Cryptography.Aes.Create() 
  • The code for the Encrypt method:
  • C#
    public override void Encrypt(string inputFilePath, string outputFilePath)
    {
    
        //Get a persisted key and vector
        byte[] key = this.GetKey();
        byte[] iv = this.GetIV();
    
        // When a new instance of the AES class is created, a new random Key and Vector (IV)
        // are created automatically.  You can use these to encrypt and decrypt your files,
        // however, they are only good until a new instance of this class is created.  Once
        // a new random Key and Vector (IV) are created, you won't be able to decrypt files,
        // because the Key and Vector (IV) will have changed.  The solution is use them 1  
        // time to create a random Key and Vector (IV) (which can be viewed in the Immediate 
        // window by typing "?mAes.Key" or "?mAes.IV", and pressing 
        // Enter), and then somehow  in your application (like in a class, or in a .DLL, or in
        // an encrypted file or something), which I've done as an example in the GeyKey() and 
        // GetIV() methods.
        //The auto-generated random key can be used by uncommenting these lines, and the 
        // corresponding lines in the Decrypt method below
        //key = mAes.Key
        //iv = mAes.IV
    
        //Create the Encryptor using the Key and Vector (IV)
        ICryptoTransform encryptor = mAes.CreateEncryptor(GetKey(), GetIV());
    
        //Call the PerformEncryption method in the _BaseEncryption base class
        base.PerformEncryption(encryptor, inputFilePath, outputFilePath);
    
    }
    VB.NET
    ''' <summary>
    ''' This function Encryptes a document and returns the encrypted document path.
    ''' </summary>
    ''' <param name="path">The path of the file to encrypt.</param>
    ''' <returns>The path of the encrypted file.</returns>
    ''' <remarks></remarks>
    Private Function Encrypt(ByVal path As String) As String
    
        Dim outputPath As String = String.Concat(path, ".enc")
    
        'Encryption example using AES
    
        'Get a persisted key and vector
        Dim key As Byte() = GetKey()
        Dim iv As Byte() = GetIV()
    
        'When a new instance of the AES class is created, a new random Key and Vector (IV)
        ' are created automatically. You can use these to encrypt and decrypt your files,
        ' however, they are only good until a new instance of this class is created. Once
        ' a new random Key and Vector (IV) are created,
        ' you won't be able to decrypt files, because
        ' the Key and Vector (IV) will have changed. The solution is use them 1 time to 
        ' create a random Key and Vector (IV) (which can be viewed in the Immediate window 
        ' by typing "?mAes.Key" or "?mAes.IV",
        ' and pressing Enter), and then somehow persist it 
        ' in your application (like in a class, or in a .DLL,
        ' or in an encrypted file or something), 
        ' which I've done as an example in the GeyKey() and GetIV() methods.
    
        'The auto-generated random key can be used
        'by uncommenting these lines, and the corresponding
        'lines in the Decrypt method below
        'key = mAes.Key
        'iv = mAes.IV
    
        'Create the Encryptor using the Key and Vector (IV)
        Dim encryptor As ICryptoTransform = mAes.CreateEncryptor(GetKey(), GetIV())
    
        'Open both the input file for reading, and
        ' the output file for writing.
        Dim reader As New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim writer As New FileStream(outputPath, FileMode.Create, FileAccess.Write)
    
        'Create an Encrypted Stream using the "encryptor" we created above
        Dim encryptedStream As _
                    New System.Security.Cryptography.CryptoStream(writer, _
                    encryptor, CryptoStreamMode.Write)
    
        Dim bites(1023) As Byte 'Stores 1 KB
        Dim bitesRead As Int32 = 0 'Number of Bytes read
        Dim totalBites As Int64 = 0 'Total Number of Bytes read
    
    
        'Loop through the entire file reading 1 kb at a time
        Do Until totalBites >
  • The code for the Decrypt method:
  • C#
    public override void Decrypt(string inputFilePath, string outputFilePath)
    {
    
        byte[] key = this.GetKey();
        byte[] iv = this.GetIV();
    
        //You can use this to generate a new Key and Vector (IV) for use in your applications.
        //  *** Do not use the key that comes with this demo, 
        //      because everyone who uses this demo will have it. ***
        //key = mAes.GenerateKey()
        //iv = mAes.GenerateIV()
    
        //Create the Decryptor using the Key and Vector (IV)
        ICryptoTransform decryptor = mAes.CreateDecryptor(key, iv);
    
        //Call the PerformDecryption method in the _BaseEncryption base class
        base.PerformDecryption(decryptor, inputFilePath, outputFilePath);
    
    }
    VB.NET
    ''' <summary>
    ''' This function Encryptes a document and returns the encrypted document path.
    ''' </summary>
    ''' <param name="path">The path of the file to encrypt.</param>
    ''' <returns>The path of the encrypted file.</returns>
    ''' <remarks></remarks>
    Private Function Decrypt(ByVal path As String) As String
    
        Dim decryptedPath As String = path.Replace(".enc", "")
    
        Dim key As Byte() = GetKey()
        Dim iv As Byte() = GetIV()
    
        'You can use this to generate a new Key and Vector (IV)
        'for use in your applications.
        ' *** Do not use the key that comes with this demo, 
        ' because everyone who uses this demo will have it. ***
        'key = mAes.GenerateKey()
        'iv = mAes.GenerateIV()
    
        'Create the Decryptor using the Key and Vector (IV)
        Dim decryptor As ICryptoTransform = mAes.CreateDecryptor(key, iv)
    
        'Open both the input file for reading, and
        ' the output file for writing.
        Dim reader As New FileStream(path, FileMode.Open, FileAccess.Read)
        Dim writer As New FileStream(decryptedPath, _
                          FileMode.Create, FileAccess.Write)
    
        'Create an Encrypted Stream using 
        'the "encryptor" we created above
        Dim decryptedStream As _
                        New System.Security.Cryptography.CryptoStream(writer, _
                        decryptor, CryptoStreamMode.Write)
    
        Dim bites(1023) As Byte 'Stores 1 KB
        Dim bitesRead As Int32 = 0 'Number of Bytes read
        Dim totalBites As Int64 = 0 'Total Number of Bytes read
    
    
        'Loop through the entire file reading 1 kb at a time
        Do Until totalBites >
  • Persisted Key and Vector (IV):
  • C#
    //*** Just a note - DO NOT USE THIS KEY FOR YOUR OWN ENCRYPTION
    // Create a new key by using the GenerateKey() method
    private byte[] GetKey()
    {
     
        //32 length byte array
        byte[] key = new byte[32/span>];
        key[<span class="code-digit">0] = 195;
        key[1] = 201;
        key[2] = 141;
        key[3] = 238;
        key[4] = 118;
        key[5] = 179;
        key[6] = 108;
        key[7] = 7;
        key[8] = 37;
        key[9] = 109;
        key[10] = 7;
        key[11] = 48;
        key[12] = 66;
        key[13] = 141;
        key[14] = 2;
        key[15] = 65;
        key[16] = 213;
        key[17] = 136;
        key[18] = 141;
        key[19] = 210;
        key[20] = 78;
        key[21] = 234;
        key[22] = 83;
        key[23] = 34;
        key[24] = 41;
        key[25] = 238;
        key[26] = 152;
        key[27] = 88;
        key[28] = 228;
        key[29] = 72;
        key[30] = 160;
        key[31] = 174;
     
        return key;
     
    }
     
    //*** Just a note - DO NOT USE THIS Vector (IV) FOR YOUR OWN ENCRYPTION
    // Create a new Vector (IV) by using the GenerateIV() method, _
    // or changing the bytes below to whatever you want.
    private byte[] GetIV()
    {
     
        //16 length byte array    
        byte[] IV = new byte[16];
        IV[0] = 30;
        IV[1] = 185;
        IV[2] = 3;
        IV[3] = 73;
        IV[4] = 26;
        IV[5] = 247;
        IV[6] = 159;
        IV[7] = 124;
        IV[8] = 211;
        IV[9] = 112;
        IV[10] = 251;
        IV[11] = 231;
        IV[12] = 69;
        IV[13] = 25;
        IV[14] = 132;
        IV[15] = 1;
     
        return IV;
     
    }
    VB.NET
    '*** Just a note - DO NOT USE THIS KEY FOR YOUR OWN ENCRYPTION
    ' Create a new key by using the GenerateKey() method
    Private Function GetKey() As Byte()
     
        '32 length byte array
        Dim key(31) As Byte
        key(0) = 195
        key(1) = 201
        key(2) = 141
        key(3) = 238
        key(4) = 118
        key(5) = 179
        key(6) = 108
        key(7) = 7
        key(8) = 37
        key(9) = 109
        key(10) = 7
        key(11) = 48
        key(12) = 66
        key(13) = 141
        key(14) = 2
        key(15) = 65
        key(16) = 213
        key(17) = 136
        key(18) = 141
        key(19) = 210
        key(20) = 78
        key(21) = 234
        key(22) = 83
        key(23) = 34
        key(24) = 41
        key(25) = 238
        key(26) = 152
        key(27) = 88
        key(28) = 228
        key(29) = 72
        key(30) = 160
        key(31) = 174
     
        Return key
     
    End Function
     
    '*** Just a note - DO NOT USE THIS Vector (IV) FOR YOUR OWN ENCRYPTION
    ' Create a new Vector (IV) by using the GenerateIV() method
    Private Function GetIV() As Byte()
     
        '16 length byte array
        Dim IV(15) As Byte
        IV(0) = 30
        IV(1) = 185
        IV(2) = 3
        IV(3) = 73
        IV(4) = 26
        IV(5) = 247
        IV(6) = 159
        IV(7) = 124
        IV(8) = 211
        IV(9) = 112
        IV(10) = 251
        IV(11) = 231
        IV(12) = 69
        IV(13) = 25
        IV(14) = 132
        IV(15) = 1
     
        Return IV
     
    End Function

Points of Interest

The process for encrypting and decrypting each of the different algorithms is the same. One of the things you will find different is the number of bytes that are used in the different key and vector arrays.

Hopefully, this demo is helpful to you!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Argentina Argentina
My name is Fernado Emmanuel Braz. I’m a software developer living in I.Casanova, Buenos Aires, and I’m 26 years old. Besides being a programmer (and studying informatics engineering), I’m a law student at UNLaM college.

Comments and Discussions

 
GeneralMy vote of 3 Pin
1337Architect23-Aug-14 21:10
professional1337Architect23-Aug-14 21:10 
GeneralRe: My vote of 3 Pin
Fernando E. Braz11-Sep-14 13:05
Fernando E. Braz11-Sep-14 13:05 
SuggestionNot fully understandable. Pin
Debopam Pal10-Nov-13 17:19
professionalDebopam Pal10-Nov-13 17:19 
GeneralRe: Not fully understandable. Pin
Fernando E. Braz10-Nov-13 17:52
Fernando E. Braz10-Nov-13 17:52 
GeneralRe: Not fully understandable. Pin
Debopam Pal10-Nov-13 18:00
professionalDebopam Pal10-Nov-13 18:00 
GeneralMy vote of 5 Pin
Soumitra Mithu1-Oct-13 22:45
professionalSoumitra Mithu1-Oct-13 22:45 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Jul-13 20:50
professionalȘtefan-Mihai MOGA13-Jul-13 20:50 
GeneralRe: My vote of 5 Pin
Fernando E. Braz14-Jul-13 3:55
Fernando E. Braz14-Jul-13 3:55 
SuggestionStatic IV weakens your encryption strength Pin
Steve446-Jun-13 16:53
Steve446-Jun-13 16:53 
GeneralRe: Static IV weakens your encryption strength Pin
Fernando E. Braz8-Jun-13 11:18
Fernando E. Braz8-Jun-13 11:18 
GeneralRe: Static IV weakens your encryption strength Pin
Fernando E. Braz8-Jun-13 11:40
Fernando E. Braz8-Jun-13 11:40 
GeneralRe: Static IV weakens your encryption strength Pin
Steve448-Jun-13 16:52
Steve448-Jun-13 16:52 
GeneralMy vote of 5 Pin
Volynsky Alex6-Jun-13 9:30
professionalVolynsky Alex6-Jun-13 9:30 
Nice article!
GeneralRe: My vote of 5 Pin
Fernando E. Braz8-Jun-13 12:07
Fernando E. Braz8-Jun-13 12:07 
GeneralRe: My vote of 5 Pin
Volynsky Alex8-Jun-13 12:15
professionalVolynsky Alex8-Jun-13 12:15 
QuestionDownload Encryption_C_.zip - 79.3 KB Pin
Haythamsss6-Jun-13 2:36
professionalHaythamsss6-Jun-13 2:36 
AnswerRe: Download Encryption_C_.zip - 79.3 KB Pin
Fernando E. Braz8-Jun-13 11:09
Fernando E. Braz8-Jun-13 11:09 
QuestionRemoving from memory. Pin
Septimus Hedgehog5-Jun-13 5:48
Septimus Hedgehog5-Jun-13 5:48 
AnswerRe: Removing from memory. Pin
Fernando E. Braz5-Jun-13 6:15
Fernando E. Braz5-Jun-13 6:15 
QuestionRijndael = AES? Pin
AlphaDeltaTheta4-Jun-13 17:00
AlphaDeltaTheta4-Jun-13 17:00 
AnswerRe: Rijndael = AES? Pin
Fernando E. Braz4-Jun-13 17:43
Fernando E. Braz4-Jun-13 17:43 
GeneralRe: Rijndael = AES? Pin
cjb1106-Jun-13 20:43
cjb1106-Jun-13 20:43 
GeneralRe: Rijndael = AES? Pin
Fernando E. Braz8-Jun-13 11:09
Fernando E. Braz8-Jun-13 11:09 

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.