Skip to content

Atbash Cipher

Intro

The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards. The first letter is replaced with the last letter, the second with the second-last, and so on.

An Atbash cipher for the Latin alphabet would be as follows:

1
2
Plain:  abcdefghijklmnopqrstuvwxyz
Cipher: zyxwvutsrqponmlkjihgfedcba

It is a very weak cipher because it only has one possible key, and it is a simple monoalphabetic substitution cipher. However, this may not have been an issue in the cipher's time.

Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, and punctuation is excluded. This is to make it harder to guess things based on word boundaries.

Examples

  • Encoding test gives gvhg
  • Decoding gvhg gives test
  • Decoding gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt gives thequickbrownfoxjumpsoverthelazydog

Task

Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "atbash_cipher.h"
#include <cctype>
#include <string>

/*
Plain:  abcdefghijklmnopqrstuvwxyz
Cipher: zyxwvutsrqponmlkjihgfedcba
*/

namespace atbash_cipher {
std::string encode(std::string test) {
std::string dict{"zyxwvutsrqponmlkjihgfedcba"};
std::string result{};
int sp{};
for (auto c : test) {
    c = std::tolower(c);
    if (!std::isalnum(c))
    continue;
    if (sp == 5) {
    sp = 0;
    result.push_back(' ');
    }
    if (std::isalpha(c)) {
    result.push_back('z'+'a'-c);      
    } else if (std::isdigit(c)) {
    result.push_back(c);
    }
    sp++;
}
return result;
}

std::string decode(std::string test) {
std::string result{};

for (auto c : test) {
    if (!std::isalnum(c))
    continue;
    if (std::isspace(c))
    continue;

    if (std::isdigit(c)) {
    result.push_back(c);
    } else if (std::isalpha(c))
    result.push_back(('z' - c) + 'a');
}
return result;
}
} // namespace atbash_cipher
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#if !defined(ATBASH_CIPHER_H)
#define ATBASH_CIPHER_H
#include "string"

namespace atbash_cipher {
    std::string encode(std::string);
    std::string decode(std::string);
}  // namespace atbash_cipher

#endif // ATBASH_CIPHER_H

Last update: February 11, 2021

Comments