Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Keyword Cipher
3.
Encryption
3.1.
Procedure
3.2.
Program
3.3.
C++
3.4.
Input
3.5.
Output
4.
Decryption
4.1.
Procedure
4.2.
Program
4.3.
C++
4.4.
Java
4.5.
Python
4.6.
Javascript
4.7.
C#
4.8.
Input
4.9.
Output
5.
Frequently Asked Questions
5.1.
What are Ciphers?
5.2.
What is a Key?
5.3.
What is a keyword cipher?
5.4.
What ciphers use a key?
6.
Conclusion
Last Updated: May 22, 2024
Easy

Keyword Cipher

Author Anant Dhakad
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In the captivating world of cryptography, where secrets are masked and messages are disguised, keyword ciphers offer a fascinating glimpse into the art of encryption. These ciphers, while not the most complex, hold historical significance and provide a fun introduction to the concepts of code-breaking.

Keyword Cipher

Keyword Cipher

A keyword cipher is basically a form of monoalphabetic substitution. A keyword is used to determine the letter mapping from plain to ciphertext. First, the repeated letters in the keyword are removed, then the cipher alphabet is generated. For generating cipher alphabet keyword is matched with A, B, C etc., until all the letters of the keywords are used up after which the standard alphabetical letters are used in order, excluding those which are already in the key.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Encryption

Encryption is done by replacing letters in the input text using the alphabet mapping generated by the input keyword.

Let's take an example. Let the keyword be “Kryptos” and the input text is “Knowledge is Power”. 

Here mapping from plain alphabets to ciphered alphabet will be

Plain:         A B C D E F G H I  J  K L M N O P Q  R S T  U V W X Y Z

Ciphered:  K R Y P T O S A B C D E F G H  I   J  L  M N Q U V W X Z

Now we will replace the input text letter by letter according to the mapping generated through the keyword. So the ciphered text of “Knowledge is Power” will be “DGHVETPST BM IHVTL”.

Procedure

1. Generate the mapping from plain text to ciphered text using the keyword. (Done using processKey(key) function).

2. Iterate over every letter of the input text and replace the letter with a ciphered letter using mapping. (Done using keywordCipher(text, key) function.)

3. Finally print the ciphered text.

Program

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

/* This preprocesses the key, it removes all repeated characters and
appends remaining alphabetical characters. */
string processKey(string key){
   // convert the key into UPPERCASE characters
   transform(key.begin(), key.end(), key.begin(), ::toupper);

   // for storing finally processed key
   string finalKey = "";

   // first attach all character from the key in order
   // and avoid their repeacted occurences.
   vector<int>vis(26, false);
   for(auto c: key){
       if(isalpha(c) && !vis[c-'A']){
           finalKey += c;
           vis[c-'A'] = true;
       }
   }

   // Now attach remaining alphabets.
   for(int i=0; i<26; i++){
       if(!vis[i]){
           finalKey += char(i+'A');
       }
   }

   // return the final preprocessed key.
   return finalKey;
}

/* This function encrypts the input text using keyword cipher. */
string keywordCipher(string text, string key){
   // convert the Text into UPPERCASE characters
   transform(text.begin(), text.end(), text.begin(), ::toupper);

   // ciphering the input text;
   for(auto &c: text){
       if(isalpha(c)){
           c = key[c-'A'];
       }
   }

   /* Return encrypted text */
   return text;
}

int main(){
   // Taking key input
   string key;
   getline(cin, key);
   cout << "Input Key: " << key << endl;

   // Taking text input
   string text;
   getline(cin, text);
   cout << "Input Text: " << text << endl;

   /* Remove all repeated character from the key and attach remaing characters */
   key = processKey(key);

   /* Encrypted the text using Keyword Cipher */
   string encryptedText = keywordCipher(text, key);
   cout << "Encrypted Text: " << encryptedText << endl;

   return 0;
}

Input

secret
Zombie Here

Output

Input Key: secret
Input Text: Zombie Here
Encrypted Text: ZLJEFT DTOT


Check this article, Fibonacci Series in Python here.

Decryption

Decryption is done by replacing letters in the ciphered text using the alphabet mapping generated by the input keyword.

Let's take an example. Let the keyword be “Kryptos” and the input ciphered is “DGHVETPST BM IHVTL”. 

Here mapping from plain alphabets to ciphered alphabet will be

Plain:         A B C D E F G H I  J  K L M N O P Q  R S T  U V W X Y Z

Ciphered:  K R Y P T O S A B C D E F G H  I   J  L  M N Q U V W X Z

Now we will replace the input ciphered text letter by letter according to the mapping generated through the keyword. So the decrypted text of “DGHVETPST BM IHVTL” will be “Knowledge is Power”.

Procedure

1. Generate the mapping from plain text to ciphered text using the keyword. (Done using processKey(key) function).

2. Iterate over every letter of the input ciphered text and replace the letter with a plain letter using mapping. (Done using keywordCipher(text, key) function.)

3. Finally print the decrypted text.

Program

  • C++
  • Java
  • Python
  • Javascript
  • C#

C++

#include <bits/stdc++.h>
using namespace std;

/* This preprocesses the key, it removes all repeated characters and
appends remaining alphabetical characters. */
string processKey(string key){
   // convert the key into UPPERCASE characters
   transform(key.begin(), key.end(), key.begin(), ::toupper);

   // for storing finally processed key
   string finalKey = "";

   // first attach all character from the key in order
   // and avoid their repeacted occurences.
   vector<int>vis(26, false);
   for(auto c: key){
       if(isalpha(c) && !vis[c-'A']){
           finalKey += c;
           vis[c-'A'] = true;
       }
   }

   // Now attach remaining alphabets.
   for(int i=0; i<26; i++){
       if(!vis[i]){
           finalKey += char(i+'A');
       }
   }

   // return the final preprocessed key.
   return finalKey;
}

/* This function decrypts the input encrypted text using keyword cipher. */
string keywordCipher_Decryption(string text, string key){
   // convert the Text into UPPERCASE characters
   transform(text.begin(), text.end(), text.begin(), ::toupper);

   // get the mapping from ciphered character to english characters.
   vector<int>charToIdx(26, -1);
   for(int i=0; i<26; i++){
       charToIdx[key[i]-'A'] = i;
   }

   // ciphering the input text;
   for(auto &c: text){
       if(isalpha(c)){
           c = char(charToIdx[c-'A'] + 'A');
       }
   }

   /* Return decrypted text */
   return text;
}

int main(){
   // Taking key input
   string key;
   getline(cin, key);
   cout << "Input Key: " << key << endl;

   // Taking text input
   string text;
   getline(cin, text);
   cout << "Input Encrypted Text: " << text << endl;

   /* Remove all repeated character from the key and attach remaing characters */
   key = processKey(key);

   /* Decrypting the text using Keyword Cipher */
   string decryptedText = keywordCipher_Decryption(text, key);
   cout << "Decrypted Text: " << decryptedText << endl;

   return 0;
}

Java

import java.util.Arrays;
import java.util.stream.Collectors;

public class KeywordCipher {

public static String processKey(String key) {
key = key.toUpperCase();
StringBuilder finalKey = new StringBuilder();
boolean[] visited = new boolean[26];

for (char c : key.toCharArray()) {
if (Character.isLetter(c) && !visited[c - 'A']) {
finalKey.append(c);
visited[c - 'A'] = true;
}
}

for (int i = 0; i < 26; i++) {
if (!visited[i]) {
finalKey.append((char) (i + 'A'));
}
}

return finalKey.toString();
}

public static String keywordCipherDecryption(String text, String key) {
text = text.toUpperCase();
int[] charToIdx = new int[26];
Arrays.fill(charToIdx, -1);

for (int i = 0; i < 26; i++) {
charToIdx[key.charAt(i) - 'A'] = i;
}

StringBuilder decryptedText = new StringBuilder();
for (char c : text.toCharArray()) {
if (Character.isLetter(c)) {
c = (char) (charToIdx[c - 'A'] + 'A');
}
decryptedText.append(c);
}

return decryptedText.toString();
}

public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);

System.out.print("Input Key: ");
String key = scanner.nextLine();

System.out.print("Input Encrypted Text: ");
String text = scanner.nextLine();

key = processKey(key);
String decryptedText = keywordCipherDecryption(text, key);

System.out.println("Decrypted Text: " + decryptedText);
}
}

Python

def process_key(key):
key = key.upper()
final_key = ""
visited = [False] * 26

for c in key:
if c.isalpha() and not visited[ord(c) - ord('A')]:
final_key += c
visited[ord(c) - ord('A')] = True

for i in range(26):
if not visited[i]:
final_key += chr(i + ord('A'))

return final_key

def keyword_cipher_decryption(text, key):
text = text.upper()
char_to_idx = [-1] * 26

for i in range(26):
char_to_idx[ord(key[i]) - ord('A')] = i

decrypted_text = ""
for c in text:
if c.isalpha():
decrypted_text += chr((char_to_idx[ord(c) - ord('A')] + ord('A')))
else:
decrypted_text += c

return decrypted_text

if __name__ == "__main__":
key = input("Input Key: ")
text = input("Input Encrypted Text: ")

key = process_key(key)
decrypted_text = keyword_cipher_decryption(text, key)

print("Decrypted Text:", decrypted_text)

Javascript

function processKey(key) {
key = key.toUpperCase();
const finalKey = [];
const visited = new Array(26).fill(false);

for (const c of key) {
if (/[A-Z]/.test(c) && !visited[c.charCodeAt(0) - 'A'.charCodeAt(0)]) {
finalKey.push(c);
visited[c.charCodeAt(0) - 'A'.charCodeAt(0)] = true;
}
}

for (let i = 0; i < 26; i++) {
if (!visited[i]) {
finalKey.push(String.fromCharCode(i + 'A'.charCodeAt(0)));
}
}

return finalKey.join('');
}

function keywordCipherDecryption(text, key) {
text = text.toUpperCase();
const charToIdx = new Array(26).fill(-1);

for (let i = 0; i < 26; i++) {
charToIdx[key.charCodeAt(i) - 'A'.charCodeAt(0)] = i;
}

let decryptedText = '';
for (const c of text) {
if (/[A-Z]/.test(c)) {
decryptedText += String.fromCharCode((charToIdx[c.charCodeAt(0) - 'A'.charCodeAt(0)] + 'A'.charCodeAt(0)));
} else {
decryptedText += c;
}
}

return decryptedText;
}

function main() {
const key = prompt("Input Key: ");
const text = prompt("Input Encrypted Text: ");

const processedKey = processKey(key);
const decryptedText = keywordCipherDecryption(text, processedKey);

console.log("Decrypted Text:", decryptedText);
}

main();

C#

using System;
using System.Collections.Generic;
using System.Linq;

public class KeywordCipher
{
public static string ProcessKey(string key)
{
key = key.ToUpper();
StringBuilder finalKey = new StringBuilder();
bool[] visited = new bool[26];

foreach (char c in key)
{
if (char.IsLetter(c) && !visited[c - 'A'])
{
finalKey.Append(c);
visited[c - 'A'] = true;
}
}

for (int i = 0; i < 26; i++)
{
if (!visited[i])
{
finalKey.Append((char)(i + 'A'));

Input

secret
zljeft dtOT

Output

Input Key: secret
Input Encrypted Text: zljeft dtOT
Decrypted Text: ZOMBIE HERE

Frequently Asked Questions

What are Ciphers?

Ciphering is the process of transforming data into an unreadable format. In other words, it is an algorithm that is responsible for data encryption and decryption.

What is a Key?

A Key in cryptography is a piece of data that is used in combination with an algorithm (a cypher) to convert plaintext to ciphertext (encryption) and vice versa (decryption).

What is a keyword cipher?

A keyword cipher is a simple substitution cipher where a secret keyword dictates how letters are encrypted. 

What ciphers use a key?

Many ciphers rely on a secret key for encryption and decryption. This includes common ciphers like the Caesar cipher, Vigenère cipher, and even some modern ciphers use keys for secure communication. 

Conclusion

In this article, we have extensively discussed Keyword Cipher. Keyword ciphers, while not the most complex encryption methods, offer a fascinating glimpse into the world of cryptography. 

We hope that this blog has helped you enhance your knowledge regarding Keyword Cipher and if you would like to learn more, check out our articles on the platform Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Substitution Cipher
Next article
Advanced Encryption Standard
Live masterclass