A Simple Atbash Cipher Implementation


You are given a lowercase alphabet string text. Return a new string where every character in text is mapped to its reverse in the alphabet, so that a becomes z, b becomes y, c becomes x, and so on.

Example 1
Input
text = “abcdef”
Output
“zyxwvu”

Understanding the Cipher

The Atbash cipher is a simple substitution cipher where the alphabet is reversed. This means ‘a’ maps to ‘z’, ‘b’ to ‘y’, and so on.

A Simple Atbash Cipher in C++

Atbash Cipher Algorithm: Iterating each character (lowercase) in the string, and update it to its reverse in the alphabet.

O(N) time complexity and O(1) space.

1
2
3
4
5
6
string atbashCipher(string text) {
    for (auto &n: text) {
        n = 'a' + ('z' - n);
    }
    return text;
}
string atbashCipher(string text) {
    for (auto &n: text) {
        n = 'a' + ('z' - n);
    }
    return text;
}

A Simple Atbash Cipher in C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <ctype.h>
 
char *atbashCipher(char *text) {
    for (int i = 0; text[i] != '\0'; i++) {
        if (isalpha(text[i])) {
            char base = islower(text[i]) ? 'a' : 'A';
            text[i] = base + ('z' - text[i]);
        }
    }
    return text;
}
 
int main() {
    char text[] = "hello world";
    printf("Encoded text: %s\n", atbashCipher(text));
    return 0;
}
#include <stdio.h>
#include <ctype.h>

char *atbashCipher(char *text) {
    for (int i = 0; text[i] != '\0'; i++) {
        if (isalpha(text[i])) {
            char base = islower(text[i]) ? 'a' : 'A';
            text[i] = base + ('z' - text[i]);
        }
    }
    return text;
}

int main() {
    char text[] = "hello world";
    printf("Encoded text: %s\n", atbashCipher(text));
    return 0;
}

A Simple Atbash Cipher in Python

1
2
3
4
5
6
7
def atbash_cipher(text):
    cipher = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zyxwvutsrqponmlkjihgfedcba')
    return text.translate(cipher)
 
text = "hello world"
encoded_text = atbash_cipher(text)
print(encoded_text) 
def atbash_cipher(text):
    cipher = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zyxwvutsrqponmlkjihgfedcba')
    return text.translate(cipher)

text = "hello world"
encoded_text = atbash_cipher(text)
print(encoded_text) 

A Simple Atbash Cipher in Rust

fn atbash_cipher(text: &str) -> String {
    text.chars()
        .map(|c| {
            if c.is_alphabetic() {
                let base = if c.is_lowercase() { 'a' } else { 'A' };
                base + (('z' as u8) - (c as u8)) as char
            } else {
                c
            }
        })
        .collect()
}

fn main() {
    let text = "hello world";
    let encoded_text = atbash_cipher(text);
    println!("Encoded text: {}", encoded_text);
}

A Simple Atbash Cipher in PHP

1
2
3
4
5
6
7
8
function atbash_cipher($text) {
    $cipher = str_rot13($text);  // Using ROT13 for simplicity
    return $cipher;
}
 
$text = "hello world";
$encoded_text = atbash_cipher($text);
echo "Encoded text: $encoded_text\n";
function atbash_cipher($text) {
    $cipher = str_rot13($text);  // Using ROT13 for simplicity
    return $cipher;
}

$text = "hello world";
$encoded_text = atbash_cipher($text);
echo "Encoded text: $encoded_text\n";

A Simple Atbash Cipher in JavaScript

1
2
3
4
5
6
7
8
9
function atbashCipher(text) {
    return text.replace(/[a-z]/gi, char =>
        String.fromCharCode('a'.charCodeAt(0) + ('z'.charCodeAt(0) - char.charCodeAt(0)))
    );
}
 
const text = "hello world";
const encoded_text = atbashCipher(text);
console.log("Encoded text:", encoded_text);
function atbashCipher(text) {
    return text.replace(/[a-z]/gi, char =>
        String.fromCharCode('a'.charCodeAt(0) + ('z'.charCodeAt(0) - char.charCodeAt(0)))
    );
}

const text = "hello world";
const encoded_text = atbashCipher(text);
console.log("Encoded text:", encoded_text);

A Simple Atbash Cipher in VBScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function atbashCipher(text)
    Dim result, i
    For i = 1 To Len(text)
        Select Case Asc(Mid(text, i, 1))
            Case 97 To 122  'a-z'
                result = result & Chr(122 - Asc(Mid(text, i, 1)) + 97)
            Case 65 To 90  'A-Z'
                result = result & Chr(90 - Asc(Mid(text, i, 1)) + 65)
            Case Else
                result = result & Mid(text, i, 1)
        End Select
    Next
    atbashCipher = result
End Function
 
MsgBox atbashCipher("hello world")
Function atbashCipher(text)
    Dim result, i
    For i = 1 To Len(text)
        Select Case Asc(Mid(text, i, 1))
            Case 97 To 122  'a-z'
                result = result & Chr(122 - Asc(Mid(text, i, 1)) + 97)
            Case 65 To 90  'A-Z'
                result = result & Chr(90 - Asc(Mid(text, i, 1)) + 65)
            Case Else
                result = result & Mid(text, i, 1)
        End Select
    Next
    atbashCipher = result
End Function

MsgBox atbashCipher("hello world")

A Simple Atbash Cipher in C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
 
static string atbashCipher(string text) {
    string result = "";
    foreach (char c in text) {
        if (char.IsLetter(c)) {
            char base = char.IsLower(c) ? 'a' : 'A';
            result += (char)(base + ('z' - c));
        } else {
            result += c;
        }
    }
    return result;
}
 
Console.WriteLine(atbashCipher("hello world"));
using System;

static string atbashCipher(string text) {
    string result = "";
    foreach (char c in text) {
        if (char.IsLetter(c)) {
            char base = char.IsLower(c) ? 'a' : 'A';
            result += (char)(base + ('z' - c));
        } else {
            result += c;
        }
    }
    return result;
}

Console.WriteLine(atbashCipher("hello world"));

A Simple Atbash Cipher in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class AtbashCipher {
    public static String atbashCipher(String text) {
        StringBuilder result = new StringBuilder();
        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                char base = Character.isLowerCase(c) ? 'a' : 'A';
                result.append((char)(base + ('z' - c)));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }
 
    public static void main(String[] args) {
        String text = "hello world";
        String encodedText = atbashCipher(text);
        System.out.println("Encoded text: " + encodedText);
    }
}
public class AtbashCipher {
    public static String atbashCipher(String text) {
        StringBuilder result = new StringBuilder();
        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                char base = Character.isLowerCase(c) ? 'a' : 'A';
                result.append((char)(base + ('z' - c)));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String text = "hello world";
        String encodedText = atbashCipher(text);
        System.out.println("Encoded text: " + encodedText);
    }
}

A Simple Atbash Cipher in Go

package main

import (
	"fmt"
	"strings"
)

func atbashCipher(text string) string {
    var result strings.Builder
    for _, c := range text {
        if c >= 'a' && c <= 'z' {
            result.WriteRune('a' + ('z' - c))
        } else if c >= 'A' && c <= 'Z' {
            result.WriteRune('A' + ('Z' - c))
        } else {
            result.WriteRune(c)
        }
    }
    return result.String()
}

func main() {
	text := "hello world"
	encodedText := atbashCipher(text)
	fmt.Println("Encoded text:", encodedText)
}

A Simple Atbash Cipher in BASH

Here’s a Bash implementation of the Atbash cipher. It might not be the most concise for larger projects, but it effectively demonstrates the cipher’s logic in Bash.

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
function atbash_cipher() {
    local text="$1"  # Capture the input text
    local result=""
 
    for (( i=0; i<${#text}; i++ )); do 
        char="${text:$i:1}"
 
        # Check if the character is a letter
        if [[ $char =~ [a-zA-Z] ]]; then
            base_char=$( [[ $char =~ [A-Z] ]] && echo 'A' || echo 'a' )
            offset=$(( 'z' - $char ))  # Calculate offset from 'z' or 'Z'
            encoded_char=$(printf \\$(printf '%03o' $(( $(printf '%d' "'$base_char") + $offset))))
            result+="$encoded_char"
        else
            result+="$char"  # Non-letter characters added without modification        
        fi
    done
 
    echo "$result"
}
 
# Example usage
text="hello world"
encoded=$(atbash_cipher "$text")
echo "Encoded text: $encoded"
function atbash_cipher() {
    local text="$1"  # Capture the input text
    local result=""

    for (( i=0; i<${#text}; i++ )); do 
        char="${text:$i:1}"

        # Check if the character is a letter
        if [[ $char =~ [a-zA-Z] ]]; then
            base_char=$( [[ $char =~ [A-Z] ]] && echo 'A' || echo 'a' )
            offset=$(( 'z' - $char ))  # Calculate offset from 'z' or 'Z'
            encoded_char=$(printf \\$(printf '%03o' $(( $(printf '%d' "'$base_char") + $offset))))
            result+="$encoded_char"
        else
            result+="$char"  # Non-letter characters added without modification        
        fi
    done

    echo "$result"
}

# Example usage
text="hello world"
encoded=$(atbash_cipher "$text")
echo "Encoded text: $encoded"

Explanation:

  • Function Definition: The code defines a function named atbash_cipher.
  • Input Text: local text="$1" captures the first argument passed to the function.
  • Iteration: The for loop iterates over each character of the input text.
  • Character Check: The if statement uses a regular expression to determine if the current character is a letter.
  • Base Character: Determines if the base character is 'A' (uppercase) or 'a' (lowercase).
  • Offset Calculation: Calculates the offset of the current character from 'z' or 'Z'.
  • Character Encoding:
    • Uses printf to compute the octal representation of the encoded character.
    • The inner printf '%d' "'$base_char" gets the ASCII value of the base character.
  • Appending to Result Builds the encoded result string.
  • Output: The echo "$result" prints the encoded text.

String Cipher Algorithms

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
1020 words
Last Post: Teaching Kids Programming - Algorithmic Runtime and Space Complexity
Next Post: Teaching Kids Programming - Merging Two Sorted List

The Permanent URL is: A Simple Atbash Cipher Implementation

Leave a Reply