> For the complete documentation index, see [llms.txt](https://junweiwangs-organization.gitbook.io/information-security/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junweiwangs-organization.gitbook.io/information-security/playfair-cipher.md).

# Playfair Cipher

* Digraph substitution cipher
* Encrypts a pair of alphabets (digraphs) instead of a single alphabet

## Algorithm Steps

1. Generate they key square (5x5)
   1. 5x5 grid of alphabets (25)
   2. Each character must be unique
   3. B.c. there are 26 characters, one of them will be omitted (usually "j")
      1. If "j" appears, it is replaced with "i"
   4. > The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order
2. Algorithm to encrypt the plain text:
   1. Plaintext is split into two letters (digraphs)
   2. If odd number of letters, a "Z" is added to last letter
   3. > **Worked example:**\
      > "instruments"
      >
      > "in", "st", "ru", "me", "nt", "sz"
   4. A pair cannot be made with the same same letter
      1. Break the pair & add a bogus letter
      2. > "hello"
         >
         > "he", "ll", "ox"
         >
         > "he", "lx", "lo"

### Rules for encryption

* **If both the letters aer in the same column**\
  Take the letter below each one (going back to the top if at them bottom)
* **If both the letters are in the same row**\
  Take the letter to the right of each one (going back to the leftmost if at the rightmost position)
* **If neither of the above rules is true**\
  Form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle

> The process of decryption is just doing the **reverse**, simple as that!

<figure><img src="/files/sCUiVnOw14CQQnBfoOXq" alt=""><figcaption><p>Worked example</p></figcaption></figure>

## 模拟退火算法 (Simulated annealing) & 爬山算法(Hill-climbing)

<figure><img src="/files/CtV8p42ViDd7MCENKfUH" alt=""><figcaption></figcaption></figure>
