Home > Articles > Security > Software Security

CryptoNugget

Cryptography is a minor hobby of author Richard Heathfield. He has written this article in much the same way that he might have written for his book, C Unleashed, and he hopes you'll find it diverting and send you to the book for more!
Like this article? We recommend

Like this article? We recommend

Introduction

When I was writing the C Unleashed outline, I knew that I wouldn’t be able to write the whole book myself but I didn’t know who the co-authors would be and, consequently, I didn’t know which chapters they would be able to take off my hands. Sams was very keen to have a chapter on cryptography in the book. So, until Mike Wright turned up (bless him!), I was faced with the very real possibility that I might have to write the chapter myself. I’m no expert in cryptography, but it is a minor hobby of mine and when I was approached for a “nugget” - something not specifically in the book, but which might interest readers, it seemed appropriate to include an article I wrote a while back. I've edited it in much the same way that I might have edited it for the actual book. Naturally this isn’t going to be a full-blown 50-page chapter, but I hope you’ll find it diverting, anyway.

Elementary Cryptography

Let’s begin by looking at a simple cipher - a substitution cipher. This cipher substitutes each letter of the alphabet with a different one. For the purposes of this article we will consider plaintexts consisting entirely of upper case letters, to simplify matters. The techniques shown here can be easily modified for plaintexts using a computer’s entire character set or any subset thereof.

Perhaps the most common form of substitution cipher is ROT13, which is typically available on Unix systems (on my Linux system it’s called Caesar). In ROT13 each letter is rotated 13 places around the alphabet. Thus, HELLO becomes WTAAD.

We can represent this as follows:

P is the plaintext (in this case, HELLO). C is the ciphertext (in this case, WTAAD). If we call the process of substituting ROT13, then C = ROT13(P).

In this case, to decrypt the message is simple. We just ROT13 it again. Think of a dial with an indicator pointing upwards. If you move it 180 degrees clockwise, it now points downwards. Turn it 180 degrees clockwise again, and it points upwards again. Thus, P = ROT13(C) and, therefore, P = ROT13(ROT13(C)).

As you might imagine, this is not a particularly difficult cipher to crack. It is sometimes used on Usenet to allow people to read information, if they so choose, by deciphering it. For example: for all those who can’t wait for the final episode of “Dying For A Drink,” I can exclusively reveal (ROT13): GUR OHGYRE QVQ VG. As you can see, those using ROT13 will frequently publish the fact to assist people who want to decrypt the ciphertext. ROT13 is not intended to be a super-secure cipher.

Programming ROT13 is relatively trivial. Here’s C code to do it and which assumes the ASCII character set is being used:

#include <string.h>

char *rot13(char *s)
{
  char *t = s;
  const char *lower = “abcdefghijklmnopqrstuvwxyz”;
  const char *upper = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
  char *p;

  if(s != NULL)
  {
    while(*s)
    {
      p = strchr(lower, *s);
      if(p != NULL)
      {
        *s = lower[((p - lower) + 13) % 26];
      }
      else
      {
        p = strchr(upper, *s);
        if(p != NULL)
        {
          *s = upper[((p - upper) + 13) % 26];
        }
      }
      ++s;
    }
  }
  return t;
}

ROT13 is, not surprisingly, easy to crack. Nevertheless, by using different rearrangements of letters some people think they can achieve security. For example, here is a substitution cipher that is possibly a shade more secure than ROT13:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

QWERTYUIOPASDFGHJKLZXCVBNM

The cipher works like this: for each character in the plaintext, find that character in the top row. Look at the character beneath it: this is the corresponding character in the ciphertext. Decryption, of course, comprises the opposite operation (look it up in the second row, convert to the character above).

Thus, HELLOWORLD becomes ITSSGVGKSR

This seems a little more secure, no doubt. Unfortunately, it’s not. A short message makes it a little harder, but not much. It is possible, and indeed trivial, to cryptanalyse substitution ciphers using letter frequencies. You can easily determine which letters are used frequently in a given language using a simple program to count alphabetic characters in a large sample of text. You can then compare that table against your ciphertext and make deductions about it. According to one analysis, the frequency of English letters is (from most common to least common) ETAONRISHDLFCMUGPYWBVKXJQZ. Your mileage may vary: it obviously depends on the text sample you use. Nevertheless, E is a clear winner, and every study I ever saw puts T second and A/O third/fourth (sometimes the other way around - O/A). Between them, these four letters account for approximately 40% of all letters used!

There is more information yet to be gained from a monoalphabetical cipher - letter patterns. For example, consider the phrase “letter pattern”. Take each word in turn, and assign each unique letter in the word a number. “Letter” gives us “123324” (1 = L, 2 = E, etc). “Pattern” gives us “1233456”.

There aren’t that many words in the English language that give us these patterns. Some duplicates exist, for example, “LET” and “CAT” have the same pattern codes, but longer words can give us useful pattern information which we can use to help us crack a monoalphabetic cipher.

The following is a sample of C code that takes a list of words, one per line, and prints out their patterns. It’s not amazingly efficient - in fact it has a time complexity of O(m2 * n) where n is the number of words and m is the average number of letters in a word. Still, it’s better than nothing. It was actually written with a Unix system’s /usr/dict/words dictionary in mind (with the idea of building a pattern dictionary for decryption) but could be simply adapted to serve as a cryptanalytic tool (and was designed with this flexibility in mind).

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void pattern_map(char *answer, char *buffer, size_t len)
{
  size_t idx, j;
  int done = 0;
  static const char *p =
    “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
  static const size_t maxidx = strlen(p);
  int curr = 1;

  answer[0] = ‘1’;
  buffer[0] = tolower(buffer[0]);

  for(idx = 1; idx < len; idx++)
  {
    buffer[idx] = tolower(buffer[idx]);
    done = 0;
    for(j = 0; !done && j < idx; j++)
    {
      if(buffer[idx] == buffer[j])
      {
        answer[idx] = answer[j];
        done = 1;
      }
    }

    if(!done)
    {
      if(curr < maxidx)
      {
        answer[idx] = p[++curr];
      }
      else
      {
        answer[idx] = ‘?’;
      }
    }
  }

  answer[idx] = ‘\0’;
}

int main(void)
{
  char buffer[8192] = {0};
  char answer[8192] = {0};

  size_t len = 0;

  while(fgets(buffer, sizeof buffer, stdin))
  {
    len = strlen(buffer) - 1;
    if(buffer[len] != ‘\n’)
    {
      fprintf(stderr, “Line too long: %s\n”, buffer);
    }
    else
    {
      pattern_map(answer, buffer, len);
      printf(“%s %s”, answer, buffer);
    }
  }

  printf(“\n”);

  return 0;
}

As a result of these trivial cracks, substitution ciphers are not at all secure - frequency analysis of any ciphertext of 40 characters or more is unlikely to fail to reveal the plaintext.

A former colleague, in a former lifetime, was very keen on substitution ciphers. For some reason he thought that if he ran his plaintext through successive substitution tables, some of which were numbers rather than letters, and some of which were invented symbols, it would somehow be really secure. He presented his ‘uncrackable’ ciphertext to me proudly and it took me about 5 minutes to crack. He asked me how I’d managed to deduce the existence of the intermediate tables. My answer was “What intermediate tables?” I’d had no idea he’d gone to all that trouble! The existence of the intermediate tables was irrelevant to the crack, because there was still a one-to-one mapping between the plaintext and the ciphertext.

Homophonic substitution is a variation on the same theme. In homophonic substitution, each character of plaintext can be replaced by one of a small selection of ciphertext characters. So you could, for example, map A to 54, 90, 102, or 155; B to 2, 37, 39 or 158; C to 17, 38, 70 or 99; etc. This is a lot harder to crack, but it’s still not impossible. The same statistical irregularities of the plaintext will still show up and, thus, decryption is possible.

Maybe we can do better by encrypting groups of letters instead of individual letters. This certainly gives us more scope. If we take groups of three characters at a time, that gives us approximately 17000 (I’ll let you cube 26 for yourselves!) possible groups of plaintext triplets. If we mapped each to a unique ciphertext triplet, that would be a lot harder to crack, yes? For example, you can encipher AAA as FOO, AAB as BAR, AAC as QUX, AAD as FRE, etc.

Well, okay, it’s better. It’s still not very good, though. For sufficiently large samples of ciphertext it is still possible to get a handle on statistical anomalies in the data. For example, what’s the betting that THE is the most common triplet in the English language? (Not counting the capitalised word, the triplet THE still occurs three times in that last sentence alone.) So all you’d have to do is find the most common triplet and you have a hook into the cipher. I’m not saying that THE is necessarily the most common, although it is a good guess. Writing a program to determine a triplet frequency table is left as an exercise for the discerning reader.

Okay, how about using more than one substitution table? Maybe if we had, say, six tables, and we used the first table to encrypt the first, seventh, thirteenth letters of the plaintext, and the second to encrypt the second, eighth, and fourteenth, etc?

Not a bad idea, it seems, but all this really means is that it takes more ciphertext before the tables can be deduced (in this case, only six times as much ciphertext). Computer programs exist which can do this kind of cryptanalysis extraordinarily quickly and accurately.

But "WAIT!," I hear you cry. Any one of these methods could have been used. The cryptanalyst has no way of knowing which encryption method I’ve used! So how can one possibly decide which cryptanalytical technique to use on my ciphertext?

Three answers exist for this. Firstly, if your security relies on the secrecy of your algorithm, that’s not security, it’s obscurity. Your algorithm must be known to at least two people - the sender and the receiver of the information. If you have a group of people who all need to share secure information, you’re going to have to change your algorithm every time somebody leaves the group, because they know the secret and now they are a 'loose cannon', so to speak.

Secondly, even if it’s just the two of you, and even if you have complete confidence that your secret algorithm won’t be revealed (unwittingly, deliberately, or under coercion) by the other person, that still doesn’t help. Cryptanalysts know a huge number of algorithms and have a large selection of cryptanalysis programs at their disposal.

Thirdly, if you are using a “secret” computer program to encrypt and decrypt your secrets, remember that cryptanalysts are bright bunnies. If they can get hold of the binary of your program (to how many people have you distributed this binary, hmmm?), they can disassemble it and study your algorithm. In fact, it’s a rather perverse truth of cryptography that the truly secure algorithms are those which have been published by their authors and subjected to all kinds of attacks by some of the best cryptanalysts in the world. Anything which can survive that onslaught, intact, mustbe good.

So, if you used any of the techniques I’ve described so far and a professional cryptanalyst got hold of your ciphertext, I wouldn’t give your secret ten minutes before it was cracked.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020