Chapter 8. Protecting Data: Encryption

Introduction

Without encryption, it is easy for anyone with access to a computer between you and the receiver to view transmitted data while it is in transit. In fact, this book includes a chapter that describes how to monitor network traffic at the packet level. This network traffic could include confidential or privileged information that you transmit from your computer.

Security is paramount in financial transactions and many other types of information exchange with an associated dollar value. It is vitall that privileged information remain in the hands of its rightful owners and not stray into the hands of hackers, or worse, the public domain.

This chapter is divided into three sections. The first section describes how encrypted data is cracked and how to recognize weak encryption, which effectively makes your data less secure than plain text. The second section describes asymmetric encryption, which is most applicable for securing data in transit. The chapter concludes with a discussion on symmetric encryption, which is ideal for use in conjunction with other types of encryption for added performance and security.

Cryptanalysis

In order to appreciate fully what cryptography is, it is necessary to understand the difference between good and bad encryption. When encryption techniques are used incorrectly, they are worse than having no encryption at all because system users will mistakenly trust the encryption, when it is not secure at all. This section should plainly demonstrate how to recognize weak encryption and how simply it can be broken.

Any encryption algorithm that substitutes one character for another can be broken without knowing the key or even the mechanism by which the text was encrypted. The process is known as frequency analysis.

The most common character used in English text is the space character (ASCII code 32). After that comes the letter “e,” then “t,” right down to “z,” the least common.

The complete list is:

(space)etaoinshrdlcumwfgypbvkjxqz

In ciphers, where each letter is substituted by another letter, the frequency of its occurrence is similar to that of plain English.

For instance, a piece of text was taken randomly out of a text file and encrypted. The resultant cipher text was:

v`z/bnv/a`{/c`na/}ja{/cjn|j/cjak/`}/`{gj}xf|j/{}na|ij}/{gj/
`{gj}/bjkfzb/{`/na`{gj}/z|j}/jwlj {/n|/ n}{/`i/{gj/ j}bnaja{/
{}na|ij}/n|/ }`yfkjk/nm`yj/`i/{gj/|`i{xn}j/ }`kzl{

The most common character is “/,” so we can assume that it is the space character. After that, “j” can be assumed to be “e,” and so on down to “z.” The result seems more like a human language, but only a few English words can be seen (e.g., “not,” “the,” “to”).

fou cif not moin aent meise mend oa otheagwse tainsrea the
othea cedwuc to inothea usea ebpelt is liat or the leacinent
tainsrea is laoywded ivoye or the sortgiae laodupt

Looking through the text, a few words would make sense if one letter were changed. Because character substitution ciphers must have one-to-one mapping between characters, if one letter is changed, then the letter it is changed to must also be substituted.

We can therefore make three assumptions:

  1. othea → other: a = r, r = ?

  2. o? → on, of: Assume “not” is correct, r = f, f = ?

  3. ?ou → you: f = y, “y” doesn’t appear in cipher text

This process can be iterated several times. Each step makes the cipher text more legible.

you ciy not moin rent meise mend or othergwse trinsfer the
other cedwuc to inother user ebpelt is lirt of the lercinent
trinsfer is lroywded ivoye of the softgire lrodupt
  1. trinsfer → transfer: i = a

  2. softgare → software: g = w, w = ?

  3. otherw?se → otherwise: w = I

you cay not moan rent mease mend or otherwise transfer the
other cediuc to another user ebpelt as lart of the lercanent
transfer as lroyided avoye of the software lrodupt
  1. cediuc → medium: c = m

  2. ?ermanent → permanent: l = p, p =?

  3. mease → lease: m = l

you may not loan rent lease lend or otherwise transfer the
other medium to another user eb?ept as part of the permanent
transfer as proyided avoye of the software produ?t
  1. produ?t → product: p = c

  2. ebcept → except: b = x

  3. proyided → provided: y = v

  4. avove → above: v = b

Voilà! The message has been decrypted.

you may not loan rent lease lend or otherwise transfer the
other medium to another user except as part of the permanent
transfer as provided above of the software product

Frequency analysis software can be programmed to run without any human intervention and could easily recognize and decrypt files or network data that was encrypted with any of the ciphers mentioned to date. If the message had not been in English, or was audio data rather than text, this approach would not have worked.

Terminology

Cryptography carries with it a vast amount of jargon, some of which is unavoidable when discussing the subject.

  • Plain text is digital information that is unencrypted.

  • Cipher text is digital information that has been encrypted.

  • A key is a piece of digital data that is used by a computer program to convert plain text, to cipher text or vice versa.

  • A cryptographic algorithm, or cipher, is a prescribed algorithm for converting plain text into cipher text and back again, using a key.

  • Strength is the measure of the difficulty a hacker would have converting cipher text to plain text without having access to the key.

Asymmetric encryption

If you imagine a padlock, it consists of a bolt, a key, and a locking mechanism. Each padlock is unique. They all have different keys and different locking mechanisms. The way these padlocks are made in the factory, it is impossible to guess the shape of the key by simply looking at the locking mechanism. It is possible to close the bolt on the padlock without having a key. This makes it much more secure than the previous encryption methods described, which would be more akin to a combination lock, where the combination needs to be set when inserting the bolt into the lock.

Now imagine three people: a tourist, a travel agent, and a thief. The tourist wants to send $1,000 to the travel agent, but if the thief gets to the key before the travel agent, he will steal the money. If the tourist were to put the money in a box and then lock it, the travel agent would not have a way to reopen the box if she did not have the key. If the key were to be sent, the thief would surely steal the key and the money before anyone knew what had happened.

The solution is that the tourist asks the travel agent to send him an open padlock and keep the key. The tourist then puts the money in the box, locks it, and sends it back. The travel agent still has the key, so she can open the box and bank the money. The thief may have seen the padlock, and may even have been able to examine the locking mechanism, but he could not open it.

In this case, the padlock key is called the private key, and the locking mechanism is the public key. In computing, the padlocks become one-way mathematical equations, and the keys become numbers.

An example of a one-way mathematical equation is as follows:

A prime number is a number that is divisible only by itself and 1 (e.g., 13). Given a number z, which is a product of two prime numbers x and y, determine the values of x and y, where neither x nor y is equal to 1.

For example, what two numbers multiply to give 22,321?

To solve this problem by hand, you could multiply every prime number between 1 and 149 (square root of 22,321). Other techniques to factor large primes exist, but this would take a computer merely seconds to do; however, if the number to be factored was in the order of billions, it no longer remains feasible for desktop PCs to solve.

The Rivest-Shamir-Adleman (RSA) is quite slow in comparison to most of the shared key (symmetrical) encryption technologies available. In a system using a combination of public key and shared key, overall encryption speed can be increased.

If a message is encrypted with the Triple Data Encryption Standard (3DES), then the key is encrypted with RSA. The same level of security is offered, but with a much faster execution.

Using RSA as asymmetric encryption

RSA (Rivest Shamir Adleman, named after its inventors) is implemented in the RSACryptoServiceProvider class. It generates public and private keys on instantiation; encryption and decryption are performed from the Encrypt and Decrypt methods. Keys are stored in XML format.

Start a new project in Visual Studio .NET. Add two textboxes: tbWorking and tbStatus. The latter should be set with MultiLine to True. Add two more buttons: btnEncrypt and btnDecrypt. To further assist code development, we will encapsulate the core cryptographic functions in a class. Therefore, add a new class to your project named clsCryptography.

First, the Cryptography class has to implement both encryption and decryption. The cryptographic framework works from byte arrays primarily, so the functions will accept and return byte arrays. As mentioned earlier, RSA is asymmetric, so it uses two keys, which happen to be stored in XML (string) format.

Open clsCryptography and enter the following code:

C#

namespace rsa
{
  public class clsCryptography
  {
    private RSACryptoServiceProvider RSA;
    public string PublicKey;
    public string PrivateKey;
    public byte[] Encrypt(byte[] Data, string PublicKeyIn)
    {
      RSA.FromXmlString(PublicKeyIn);
      return RSA.Encrypt(Data, false);
    }
    public byte[] Decrypt(byte[] Data, string PrivateKeyIn)
    {
      RSA.FromXmlString(PrivateKeyIn);
      return RSA.Decrypt(Data, false);
    }
  }
}

VB.NET

Namespace rsa
 Public Class clsCryptography
  Private RSA As RSACryptoServiceProvider
  Public PublicKey As String
  Public PrivateKey As String

  Public function Encrypt(Data as byte(),PublicKeyIn as _
  string) as Byte()
    RSA.FromXmlString(PublicKeyIn)
    Return RSA.Encrypt(Data,False)
  End function

  Public Function Decrypt(Data as byte(),PrivateKeyIn as_
  string) as Byte()
    RSA.FromXmlString(PrivateKeyIn)
    Return RSA.Decrypt(Data,False)
  End Function

 End Class
End Namespace

RSA cryptography is of little value if we have no keys to work from. These keys should be generated when the class is created, so we insert this code as the constructor of clsCryptography:

C#

public clsCryptography()
{
  CspParameters cspParams = new CspParameters();
  cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
  RSA = new RSACryptoServiceProvider(cspParams);
  PublicKey = RSA.ToXmlString(false);
  PrivateKey = RSA.ToXmlString(true);
}

VB.NET

Public Sub New()
  Dim cspParams As CspParameters = New CspParameters()
  cspParams.Flags = CspProviderFlags.UseMachineKeyStore
  RSA = New RSACryptoServiceProvider(cspParams)
  PublicKey = RSA.ToXmlString(False)
  PrivateKey = RSA.ToXmlString(True)
End Sub

The Boolean parameter sent to ToXmlString indicates whether the private key should be included in the XML output.

The following namespaces must be added to the clsCryptography class:

C#

using System;
using System.Security.Cryptography;

VB.NET

imports System
imports System.Security.Cryptography

Open the application, go to the point in the code directly after the constructor of the form, and enter some private variables:

C#

public class Form1 : System.Windows.Forms.Form
{
  private rsa.clsCryptography clsRSA = new
  rsa.clsCryptography();
  private byte[] Decrypted;
  private byte[] Encrypted;
  ...

VB.NET

Public Class Form1
  Inherits System.Windows.Forms.Form
  Private clsRSA As clsCryptography =  New clsCryptography()
  Private Decrypted() As Byte
  Private Encrypted() As Byte

To display the generated keys on-screen, we append the XML to the status textbox at startup:

C#

private void Form1_Load(object sender, System.EventArgs e)
{
  tbStatus.Text += "Private key is:
" + clsRSA.PrivateKey
+ "
";
  tbStatus.Text += "Public key is:
" + clsRSA.PublicKey +
"
";
}

VB.NET

Private  Sub Form1_Load(ByVal sender As Object, ByVal e _
As System.EventArgs)
   tbStatus.Text += "Private key is:"
   tbStatus.Text += clsRSA.PrivateKey + vbcrlf
   tbStatus.Text += "Public key is:" + vbcrlf
   tbStatus.Text += clsRSA.PublicKey + vbcrlf
End Sub

To encrypt the text, we convert it to a byte array and pass it to the clsCryptography class; the process is similar with decryption. Click on the two buttons in turn and add the following code:

C#

private void btnEncrypt_Click(object sender, System.EventArgs
e)
{
  byte[] PlainText =
  System.Text.Encoding.ASCII.GetBytes(tbWorking.Text);
  Encrypted = clsRSA.Encrypt(PlainText, clsRSA.PublicKey);
  tbWorking.Text =
  System.Text.Encoding.ASCII.GetString(Encrypted);
}

private void btnDecrypt_Click(object sender, System.EventArgs e)
{
  Decrypted = clsRSA.Decrypt(Encrypted,
  clsRSA.PrivateKey);
  tbWorking.Text =
  System.Text.Encoding.ASCII.GetString(Decrypted);
}

VB.NET

Private  Sub btnEncrypt_Click(ByVal sender As Object, _
 ByVal e As System.EventArgs)
  Dim PlainText() As Byte = _
  System.Text.Encoding.Encoding.ASCII.GetBytes _
       (tbWorking.Text)
  Encrypted = clsRSA.Encrypt(PlainText, _
        clsRSA.PublicKey)
  tbWorking.Text = _
   System.Text.Encoding.ASCII.GetString(Encrypted)
End Sub

Private  Sub btnDecrypt_Click(ByVal sender As Object, _
  ByVal e As System.EventArgs)
  Decrypted = clsRSA.Decrypt(Encrypted, clsRSA.PrivateKey)
  tbWorking.Text = _
  System.Text.Encoding.ASCII.GetString(Decrypted)
End Sub

No additional namespaces are required.

To test the application, run it from Visual Studio .NET. Type something into the box provided and press Encrypt (Figure 8.1). The text should change into an unrecognizable series of characters. Pressing Decrypt will revert this back to plain text again.

Asymmetric encryption application.

Figure 8.1. Asymmetric encryption application.

Symmetric encryption

Symmetric encryption is when the same key is used for encryption and decryption. It is commonly used in conjunction with asymmetric encryption for performance purposes. When used on its own, it is important that the key never travel on an insecure channel and that is be delivered by hand to the receiver on physical media, such as a disk or smart card. It is not suitable for network use by itself; however, asymmetric encryption can provide a means to deliver these keys on a secure channel and, therefore, makes symmetric encryption viable for networked applications.

Symmetric encryption is, however, suitable for securing software and databases because the administrator can hold this key on a disk in a secure location. Without the key, symmetric algorithms are actually more difficult to break than RSA for the same key size.

Using 3DES as symmetric encryption

A famous author, Simon Singh, once offered $15,000 to crack a short passage of text encrypted with 3DES. One year later, a Swedish team managed to crack the message and claimed the prize. Unbeknown to Simon Singh at the time, the message had actually been singleDES and thus substantially less secure. 3DES remains one of the world’s unbroken cryptographic algorithms.

Create an application in Visual Studio .NET as usual, and draw a textbox, tbFile. Include three buttons named btnEncrypt, btnDecrypt, and btnBrowse. You will also require an Open File Dialog control named openFileDialog.

Directly following the class definition, add a public DESCryptoService-Provider object as follows:

C#

public class Form1 : System.Windows.Forms.Form
{
  private DESCryptoServiceProvider des;

VB.NET

Public Class Form1
  Inherits System.Windows.Forms.Form
  Private des As DESCryptoServiceProvider

This public object will contain the symmetric keys required to encrypt and decrypt files. In this application, the keys are not saved to disk; they are only stored within this object.

Click on the Browse button and enter the following code:

C#

private void btnBrowse_Click(object sender,
System.EventArgs e)
{
  openFileDialog.ShowDialog();
  tbFile.Text  = openFileDialog.FileName;
}

VB.NET

  Private  Sub btnBrowse_Click(ByVal sender As Object, _
  ByVal e As System.EventArgs)
  openFileDialog.ShowDialog()
  tbFile.Text  = openFileDialog.FileName
End Sub

This code is pretty self-explanatory. It opens the standard File Open dialog window and displays the filename of the selected file in the tbFile textbox.

Click on the Encrypt button and enter the following code:

C#

  private void btnEncrypt_Click(object sender,
  System.EventArgs e)
  {
    string encFile = tbFile.Text + ".enc";
    FileStream fs = new FileStream(encFile, FileMode.Create,
      FileAccess.Write);
    StreamReader sr = new StreamReader(tbFile.Text);
      string strinput = (sr).ReadToEnd();
      sr.Close();

            byte[] bytearrayinput  =
            Encoding.Default.GetBytes(strinput);
            des = new DESCryptoServiceProvider();
            ICryptoTransform desencrypt =
            des.CreateEncryptor();
            CryptoStream cryptostream =
            new CryptoStream(fs, desencrypt,
            CryptoStreamMode.Write);
            cryptostream.Write(bytearrayinput, 0,
            bytearrayinput.Length);
            cryptostream.Close();
            fs.Close();
            MessageBox.Show("encrypted");
  }

VB.NET

Private Sub btnEncrypt_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles btnEncrypt.Click
        Dim encFile As String = tbFile.Text + ".enc"
        Dim fs As FileStream = New FileStream(encFile, _
             FileMode.Create,FileAccess.Write)
        Dim sr As StreamReader = New _
             StreamReader(tbFile.Text)
        Dim strinput As String = (sr).ReadToEnd()
        sr.Close()
        Dim bytearrayinput() As Byte = _
             Encoding.Default.GetBytes(strinput)
        des = New DESCryptoServiceProvider
        Dim desencrypt As ICryptoTransform = _
             des.CreateEncryptor()
        Dim CryptoStream As CryptoStream = _
             New CryptoStream(fs, desencrypt, _
             CryptoStreamMode.Write)
        cryptostream.Write(bytearrayinput, 0, _
             bytearrayinput.Length)
        cryptostream.Close()
        fs.Close()
        MessageBox.Show("encrypted")
End Sub

The encryption procedure consists of several steps. The first step is where an output file is prepared. The output file has the same name as the input file, except that the extension .enc is appended to the end of the filename. The input file is then read in from memory by passing the filename as a parameter to the constructor of a StreamReader object and calling the ReadToEnd method to pull in the file contents to a string. This string is then converted to a byte array.

The next step in the encryption process is the application of DES. Here the public DES variable is instantiated. At this point, a unique symmetric key is generated within the DESCryptoServiceProvider class. The encryption mechanism works as a stream. As with most value-added streams, an existing stream is passed to the constructor of the new stream. In this case, the output file stream is the underlying stream used by the cryptographic stream. This stream then processes and writes out the byte array read in from the input file using the Write method. The stream is then closed, and a message is shown on the screen.

Now double-click on the Decrypt button, and enter the following code:

C#

private void btnDecrypt_Click(object sender, System.EventArgs e)
  {
    FileStream fsread = new FileStream(tbFile.Text,
    FileMode.Open, FileAccess.Read);
    ICryptoTransform desdecrypt = des.CreateDecryptor();
    CryptoStream cryptostreamDecr = new CryptoStream(fsread,
    desdecrypt, CryptoStreamMode.Read);
    string decryptedFile = new StreamReader(
       cryptostreamDecr).ReadToEnd();
    FileInfo fi = new FileInfo(tbFile.Text);
    string origionalFile = tbFile.Text.Substring(0,
       tbFile.Text.Length - fi.Extension.Length);
    StreamWriter fileWriter = new
       StreamWriter(origionalFile);
    fileWriter.Write(decryptedFile);
    fileWriter.Close();
    MessageBox.Show("decrypted");
  }

VB.NET

Private Sub btnDecrypt_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnDecrypt.Click
Dim fsread As FileStream = _
   New FileStream(tbFile.Text, _
   FileMode.Open, FileAccess.Read)
   Dim desdecrypt As ICryptoTransform = _
      des.CreateDecryptor()
   Dim cryptostreamDecr As CryptoStream = _
      New CryptoStream(fsread, _
      desdecrypt, CryptoStreamMode.Read)
   Dim decryptedFile As String = New _
      StreamReader(cryptostreamDecr).ReadToEnd()
   Dim fi As FileInfo = New FileInfo(tbFile.Text)
   Dim origionalFile As String = _
      tbFile.Text.Substring(0,tbFile.Text.Length _
          - fi.Extension.Length)
   Dim fileWriter As StreamWriter = New _
      StreamWriter(origionalFile)
   fileWriter.Write(decryptedFile)
   fileWriter.Close()
   MessageBox.Show("decrypted")
End Sub

The decryption process is a little easier because our symmetric key is already generated. Three streams are used to decrypt the file on disk. The first stream is a FileStream that reads the cipher text from the file on disk. The crypto stream is created from our public des variable, which would have been previously instantiated in the encryption process. The FileStream is passed as a parameter to the constructor of the crypto stream, which decrypts the data from the stream. To extract the data quickly from the crypto stream, a StreamReader is used, which uses the ReadToEnd method to pull the decrypted data into a string.

Finally, using a bit of string manipulation, the .enc extension is removed from the filename, and a StreamWriter dumps the string containing the decrypted data to disk. This stream is then closed, and a message is displayed on-screen.

As usual, the following namespaces are required:

C#

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

VB.NET

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

To test this application, run it from Visual Studio .NET. Press Browse and locate a file on your hard disk. Press the Encrypt button, and press OK when the message box appears. You will notice that a new file has been created with the extension .enc. If you open this file in Notepad, it will appear to be garbage. If you wish, you can delete or move the original file. Press the Browse button again, and select the .enc file (Figure 8.2). When the message box appears, you will notice that the original file has been re-created.

Symmetric encryption application.

Figure 8.2. Symmetric encryption application.

Piracy protection

Software is expensive to create, but costs virtually nothing to duplicate. People generally have few qualms about sharing a CD filled with copyrighted material with anyone who they believe will find it useful. To the software producer, this can be considered a lost sale.

The most common form of software piracy is a CD-R with the license code scribbled across the front. The only real way to guarantee that the same license code cannot be used on multiple machines is to track these codes from a central server.

A common way to generate license codes is to choose a large random number (a), and increment it with a multiple of a smaller random number (b). This number would generally be encrypted so that it is not easily memorable. A key that the user enters (c) can be deemed to be valid if

(c - a) mod b = 0

Your software can broadcast this key on the local network or a central server to ensure uniqueness of the key. It is difficult for an attacker to determine a second valid key from c if a and b are sufficiently large.

An other way to protect software is if your software generates a large random number (n) at the time of purchase. This number can be encrypted by your private key to produce a second number (m) and returned to your software. If m, decrypted with the public key, is n, then the key is valid. Because n is random, m is not valid for any other copy of the software.

Hackers can also use programs to cycle automatically through millions of key combinations by simulating a user typing into your “enter license key” window. For this reason, you should have your software close after 3 failed attempts to enter the license key and delete itself after 100 failed attempts.

Beyond license fraud, there are people who make a hobby out of disassembling executable files and disabling piracy protection. There is no surefire way to defeat this type of attack, but it can be made difficult by duplicating the piracy protection code several times throughout the application.

Conclusion

This chapter has introduced the concept of data encryption in .NET with both asymmetric and symmetric forms. Also covered was the basic theory behind cryptographic systems and cryptanalysis.

It cannot be stressed enough that you are more likely to get a faster, simpler, stronger, and sometimes even more interoperable method when using the standard encryption mechanisms used in .NET as compared to homegrown encryption algorithms.

The next chapter deals with authentication, the science of knowing with whom you are dealing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.170.187