Private Key Encryption


While hash digests are useful for one-way encryption, when you need to decrypt the encrypted information, you need to use two-way encryption. The most common two way-encryption technique is key-based encryption. A key is simply a unique string that you pass together with a plain-text message to an encryption algorithm, which returns the message encrypted as cipher text. The cipher text bears no resemblance to the original message. To decrypt the cipher text, you again pass the key with the cipher text to a decryption algorithm, which returns the original plain-text message.

The most common type of key-based encryption is private key encryption, also called symmetric, traditional, shared-secret, secret-key, or conventional encryption. (Encryption is one of those areas in computing in which many names mean the same thing.) Private key encryption relies on the sender and recipient both knowing the key. This implies that potential intruders do not know the key and have no way to obtain the key. Private key encryption is good for communicating information over the Internet or for storing sensitive information in a database, registry, or file. Figure 1-3 shows private key encryption in action.

click to expand
Figure 1-3: Private key encryption

Now you’ll add functions for applying private key encryption to the security library you created in the preceding exercise, and you’ll use private key encryption to store and retrieve bank account information in the database. The type of encryption you’ll use is Triple-DES—DES is an acronym for Data Encryption Standard. Triple refers to how the encryption works—first the plain text is encrypted; this encrypted result is encrypted again; and finally, the encrypted-encrypted plain-text message is encrypted once more, resulting in the plain-text message being encrypted three times and earning the moniker Triple-DES. You get three encryptions for the price of one, and the result is a robust 192-bit encryption.

Encrypt the BankAccount field with a private key

The employee management system stores bank account information for the purpose of depositing the salaries of employees directly into their bank accounts. Currently this information is being stored as plain text. In this exercise, you’ll add private key encryption and decryption functions to your security library, and you’ll use these functions to encrypt the BankAccount field.

  1. Open the same EncryptDatabaseField program we used when encrypting the password field earlier in this chapter. The project is located at CH01_Encryption\ EncryptDatabaseField\Start\EncryptDatabaseField.sln. We will be changing the program to encrypt the BankAccount field.

  2. Add the following code to the end of SecurityLibrary.db:

    Namespace PrivateKey
    Module PrivateKey
    Function Encrypt(ByVal strPlainText As String, _
    ByVal strKey24 As String) As String
    Dim crp As New TripleDESCryptoServiceProvider()
    Dim uEncode As New UnicodeEncoding()
    Dim aEncode As New ASCIIEncoding()
    ’Store plaintext as a byte array
    Dim bytPlainText() As Byte = uEncode.GetBytes(strPlainText)
    ’Create a memory stream for holding encrypted text
    Dim stmCipherText As New MemoryStream()
    ’Private key
    Dim slt(0) As Byte
    Dim pdb As New PasswordDeriveBytes(strKey24, slt)
    Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
    crp.Key = bytDerivedKey
    ’Initialization vector is the encryption seed
    crp.IV = pdb.GetBytes(8)
    ’Create a crypto-writer to encrypt a bytearray
    ’into a stream
    Dim csEncrypted As New CryptoStream(stmCipherText, _
    crp.CreateEncryptor(), CryptoStreamMode.Write)
    csEncrypted.Write(bytPlainText, 0, bytPlainText.Length)
    csEncrypted.FlushFinalBlock()
    ’Return result as a Base64 encoded string
    Return Convert.ToBase64String(stmCipherText.ToArray())
    End Function
    Function Decrypt(ByVal strCipherText As String, _
    ByVal strKey24 As String) As String
    Dim crp As New TripleDESCryptoServiceProvider()
    Dim uEncode As New UnicodeEncoding()
    Dim aEncode As New ASCIIEncoding()
    ’Store cipher text as a byte array
    Dim bytCipherText() As Byte = _
    Convert.FromBase64String(strCipherText)
    Dim stmPlainText As New MemoryStream()
    Dim stmCipherText As New MemoryStream(bytCipherText)
    ’Private key
    Dim slt(0) As Byte
    Dim pdb As New PasswordDeriveBytes(strKey24, slt)
    Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
    crp.Key = bytDerivedKey

    ’Initialization vector
    crp.IV = pdb.GetBytes(8)
    ’Create a crypto stream decoder to decode
    ’a cipher text stream into a plain text stream
    Dim csDecrypted As New CryptoStream(stmCipherText, _
    crp.CreateDecryptor(), CryptoStreamMode.Read)
    Dim sw As New StreamWriter(stmPlainText)
    Dim sr As New StreamReader(csDecrypted)
    sw.Write(sr.ReadToEnd)
    ’Clean up afterwards
    sw.Flush()
    csDecrypted.Clear()
    crp.Clear()
    Return uEncode.GetString(stmPlainText.ToArray())
    End Function
    End Module
    End Namespace

    You can use these two functions in your code to encrypt and decrypt messages. The key is named strKey24 because it must be 24 characters long.

  3. Open the MainModule.vb file, and in Sub Main(), change the line

    EncryptField("Password", "PasswordHash")

    to read

    EncryptField("BankAccount", "BankAccountEncrypted")
  4. In Sub EncryptField(), find the line that reads

    strCipherText = HashCreateHash(strPlainText)

    and change it to the following:

    strCipherText = PrivateKey.Encrypt(strPlainText, _  "111222333444555666777888")

  5. Now press F5 to run the program. The BankAccountEncrypted field will now contain the bank account information encrypted with the key 111222333444555666777888, and you should see output similar to what is shown here:

    click to expand

Store and retrieve account information using encryption

Next you’ll change the employee management system to store and retrieve the bank account number using private key encryption.

  1. In Visual Studio .NET, open the project CH01_Encryption\EMS\ Start\EMS.sln. Open MainModule.vb, and add the following line to the Declarations section:

    Public G_PRIVATEKEY As String = "111222333444555666777888"

    This is the global variable you’ll use to store the private key.

  2. Open the class clsEmployee, and find the declaration

    Private m_BankAccount As String

    Change it to

    Private m_BankAccountEncrypted As String
  3. In the property Get of BankAccount, change the line that reads

    Return m_BankAccount

    to

    Return PrivateKey.Decrypt(m_BankAccountEncrypted, G_PRIVATEKEY)

  4. In the property Set of BankAccount, change the line that reads

    m_BankAccount = Value

    to

    m_BankAccountEncrypted = PrivateKey.Encrypt(Value, G_PRIVATEKEY)

  5. In the Create function, change the line that reads

    Me.m_BankAccount = CStr(dr("BankAccount"))

    to

    Me.m_BankAccountEncrypted = CStr(dr("BankAccountEncrypted"))
  6. In the function SaveToDatabase, change the lines that read

    Dim strSQL As String = "UPDATE Employee SET " & _
    "FirstName =‘" & Me.FirstName & "‘," & _
    "LastName =‘" & Me.LastName & "‘," & _
    "Fullname =‘" & Me.FullName & "‘," & _
    "BankAccount =‘" & Me.m_BankAccount & _
    "‘ WHERE Username =‘" & Me.Username & "‘"

    to

    Dim strSQL As String = "UPDATE Employee SET " & _
    "FirstName =‘" & Me.FirstName & "‘," & _
    "LastName =‘" & Me.LastName & "‘," & _
    "Fullname =‘" & Me.FullName & "‘," & _
    "BankAccountEncrypted =‘" & Me.m_BankAccountEncrypted & _
    "‘ WHERE Username =‘" & Me.Username & "‘"

  7. Now press F5 to run the application. Log on using the username RKing and the password RKing. On the dashboard, click the View Or Change Personal Information button. On the My Personal Information form, you can change bank account information. Click OK to save the account to the database in encrypted format, as shown here:

    click to expand

Keeping Private Keys Safe

The Triple-DES encryption algorithm we use accepts a 24-character string for a key. The 24 characters are treated as a passphrase that is used to derive a 192-bit byte array, which is then used as the actual key. This is known as 192-bit encryption. The number of bits in the key determines the total combination of possible keys—for example, a 192-bit key has 6.3 1057 possible values. A common method intruders use to try to crack encryption is a brute force attack, which means trying every different key combination available until they find the key that works. The more bits in the key, the longer it takes for a brute force attack to find the key. An intruder using the latest hardware would take a long time to crack a 192-bit key—supposing the intruder can try 1,000,000,000,000 keys a second, it would take about 200,000,000,000,000,000,000,000,000,000,000,000,000 years to try every combination. Even if the intruder got lucky, and found the key after trying only 0.0000000001% of the available combinations, the task would still take trillions of years.

Another method intruders use for cracking encryption is to find where the key is stored and then simply read the key. How can you store the key to protect against this? The least secure method is to store the key unencrypted in a file or in the registry accessible to everyone, since if an intruder gains access to your machine, all he needs is notepad.exe to read the file or RegEdit.exe to read the registry. Hard-coding the key in the application (as the employee management system currently does) is also not a good idea since if an intruder gets a copy of your application, he could easily use a de-compiler or debugger to find the key. A better method is to encrypt the key and store it in a file that is protected by the file system so that only authorized users of the system can read it. This immediately raises the questions of where to store the key you use to encrypt the private key? Windows helps with this by providing methods for encrypting and decrypting sensitive data by using logon credentials as a key. When using these methods, there are several things to be aware of:

  • Data encrypted by one user cannot be decrypted by another user. If several people share the same computer, each person will need to have her own separate copy of the encrypted data because one person’s logon credentials can’t be used to decrypt data encrypted with another person’s logon credentials.

  • Directory Security. You can make this technique even more secure by storing the encrypted data in a directory that only the current user has access to. In the following exercise, you’ll store the encrypted key in the Application Data directory, which is different for each user.

  • Installing. If you’re using this technique to install a predefined value such as a private key, consider how you will install the value in the first place. One option is to provide a key-installer program that can be run from the server to install the key. You should ensure that only authorized users of the application have permission to view or run the program that installs the key. Also, you should consider removing access to it after the key has been installed.

While these techniques are great for storing private keys, they can be used for any sensitive information such as connection strings and credit card information.

Encrypt the private key

In this exercise, you will encrypt the private key and store it in the application directory. You will also change the employee management system to retrieve the private key from the encrypted file.

  1. Start Visual Basic .NET, and load the solution CH01_Encryption\ InstallKey\Start\InstallKey.sln.

  2. Open MainModule.vb, and insert the following code:

     ’Insert code below...
    Public G_PRIVATEKEY As String = "111222333444555666777888"
    Sub Main()
    ’Encrypt the key and store it in the location
    ’c:\Documents And Settings\<username>\Application Data\emsKey
    Settings.SaveEncrypted("EMSKey", G_PRIVATEKEY)
    MsgBox("Done")
    End Sub

  3. Open SecurityLibrary.vb, and move to the end of the file. You are about to add the necessary code to easily use the Windows CryptProtectData and CryptUnprotectData APIs. This is 120 lines of code, so it will be easiest to simply cut and paste it in. In the same directory as InstallKey.sln, you will find a text file named LoadAndSaveSettings.txt. Open this file, and copy and paste the contents at the end of SecurityLibrary.vb.

  4. Press F5 to run the application. It will install a file named EMSKey.txt in the Application Data directory, which is usually c:\Documents And Settings\<username>\Application Data\EMSKey.txt.

  5. Now that the key is installed, you need to change the employee management system to use the encrypted key. In Visual Basic .NET, open the solution CH01_Encryption\ EMS\Start\EMS.sln.

  6. Open MainModule.vb, find the line that reads

    Public G_PRIVATEKEY As String = "1122334455667788"

    and change it to

    Public G_PRIVATEKEY As String = Settings.LoadEncrypted("EMSKey")

  7. Press F5 to run the application. Now the private key is being loaded from an encrypted file.

One final note on private keys: In your own applications, you should create a private key that is more complicated than the 111222333444555666777888 used in this example—private keys should be a random string of characters, numbers, and punctuation.




Security for Microsoft Visual Basic  .NET
Security for Microsoft Visual Basic .NET
ISBN: 735619190
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net