# 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>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junweiwangs-organization.gitbook.io/information-security/playfair-cipher.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
