The Wayback Machine - https://web.archive.org/web/20240715215437/https://www.geeksforgeeks.org/autokey-cipher-symmetric-ciphers/
Open In App

Autokey Cipher | Symmetric Ciphers

Last Updated : 15 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de VigenÃĻre in 1586. In general, more secure than the Vigenere cipher. Example-1:

Plaintext = "HELLO"
Autokey = N
Ciphertext = "ULPWZ" 

Example-2:

Plaintext = "GEEKSFORGEEKS"
Autokey = P
Ciphertext = "VKIOCXTFXKIOC" 

In this cipher, the key is a stream of subkeys which is used to encrypt the corresponding character in the plaintext. As shown, the autokey is added at the first of the subkeys.

Let's explain Example 1:

Given plain text is : H E L L O
Key is              : N H E L L

Let's encrypt:

Plain Text(P)       : H   E   L   L   O
Corresponding Number: 7   4   11  11  14     
Key(K)              : N   H   E   L   L
Corresponding Number: 13  7   4   11  11      
                    ---------------------
Applying the formula: 20  11  15  22  25  

Corresponding 
Letters are         : U    L   P   W   Z

Hence Ciphertext is: ULPWZ

Let's decrypt:

Cipher Text(C)      : U   L   P   W   Z
Key(K)              : N   H   E   L   L
                    ---------------------
Applying the formula: H   E   L   L   O

Hence Plaintext is: HELLO 

Here’s the java code for Autokey Cipher. 

Java




// A JAVA program to illustrate
// Autokey Cipher Technique
 
// Importing required library
import java.lang.*;
import java.util.*;
 
public class AutoKey {
 
    private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
    public static void main(String[] args)
    {
        String msg = "HELLO";
        String key = "N";
 
        // This if statement is all about java regular expression
        // [] for range
        // // Extra \ is used to escape one \
        // \\d acts as delimiter
        // ? once or not at all
        // . Any character (may or may not match line terminators)
        if (key.matches("[-+]?\\d*\\.?\\d+"))
            key = "" + alphabet.charAt(Integer.parseInt(key));
        String enc = autoEncryption(msg, key);
 
        System.out.println("Plaintext : " + msg);
        System.out.println("Encrypted : " + enc);
        System.out.println("Decrypted : " + autoDecryption(enc, key));
    }
 
    public static String autoEncryption(String msg, String key)
    {
        int len = msg.length();
 
        // generating the keystream
        String newKey = key.concat(msg);
        newKey = newKey.substring(0, newKey.length() - key.length());
        String encryptMsg = "";
 
        // applying encryption algorithm
        for (int x = 0; x < len; x++) {
            int first = alphabet.indexOf(msg.charAt(x));
            int second = alphabet.indexOf(newKey.charAt(x));
            int total = (first + second) % 26;
            encryptMsg += alphabet.charAt(total);
        }
        return encryptMsg;
    }
 
    public static String autoDecryption(String msg, String key)
    {
        String currentKey = key;
        String decryptMsg = "";
 
        // applying decryption algorithm
        for (int x = 0; x < msg.length(); x++) {
            int get1 = alphabet.indexOf(msg.charAt(x));
            int get2 = alphabet.indexOf(currentKey.charAt(x));
            int total = (get1 - get2) % 26;
            total = (total < 0) ? total + 26 : total;
            decryptMsg += alphabet.charAt(total);
            currentKey += alphabet.charAt(total);
        }
        return decryptMsg;
    }
}


C#




// A C# program to illustrate
// Autokey Cipher Technique
using System;
using System.Text.RegularExpressions;
 
public class AutoKey {
 
  private static String alphabet
    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
  public static void Main(string[] args)
  {
    String msg = "HELLO";
    String key = "N";
 
    // This if statement is all about C# regular
    // expression
    // [] for range
    // // Extra \ is used to escape one \
    // \\d acts as delimiter
    // ? once or not at all
    // . Any character (may or may not match line
    // terminators)
    Regex w = new Regex("[-+]?d*.?d+");
    if (w.IsMatch(key))
      key = "" + alphabet[Int32.Parse(key) % 26];
    string enc = autoEncryption(msg, key);
 
    Console.WriteLine("Plaintext : " + msg);
    Console.WriteLine("Encrypted : " + enc);
    Console.WriteLine("Decrypted : "
                      + autoDecryption(enc, key));
  }
 
  public static string autoEncryption(string msg,
                                      string key)
  {
    int len = msg.Length;
 
    // generating the keystream
    string newKey = key + msg;
    newKey = newKey.Substring(0, newKey.Length
                              - key.Length);
    string encryptMsg = "";
 
    // applying encryption algorithm
    for (int x = 0; x < len; x++) {
      int first = alphabet.IndexOf(msg[x]);
      int second = alphabet.IndexOf(newKey[x]);
      int total = (first + second) % 26;
      encryptMsg += alphabet[total];
    }
    return encryptMsg;
  }
 
  public static string autoDecryption(string msg,
                                      string key)
  {
    string currentKey = key;
    string decryptMsg = "";
 
    // applying decryption algorithm
    for (int x = 0; x < msg.Length; x++) {
      int get1 = alphabet.IndexOf(msg[x]);
      int get2 = alphabet.IndexOf(currentKey[x]);
      int total = (get1 - get2) % 26;
      total = (total < 0) ? total + 26 : total;
      decryptMsg += alphabet[total];
      currentKey += alphabet[total];
    }
    return decryptMsg;
  }
}
 
// This code is contributed by karandeep1234.


Output:

Plaintext : HELLO
Encrypted : ULPWZ
Decrypted : HELLO


Similar Reads

Traditional Symmetric Ciphers
The two types of traditional symmetric ciphers are Substitution Cipher and Transposition Cipher. The following flowchart categories the traditional ciphers: 1. Substitution Cipher: Substitution Ciphers are further divided into Mono-alphabetic Cipher and Poly-alphabetic Cipher. First, let's study about mono-alphabetic cipher. Mono-alphabetic Cipher
3 min read
Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
1. Monoalphabetic Cipher : A monoalphabetic cipher is any cipher in which the letters of the plain text are mapped to cipher text letters based on a single alphabetic key. Examples of monoalphabetic ciphers would include the Caesar-shift cipher, where each letter is shifted based on a numeric key, and the atbash cipher, where each letter is mapped
2 min read
Difference between AES and DES ciphers
What is AES? It stands for Advanced Encryption Standard, developed in 2001. As triple-DES was found to be slow, AES was created and is six times faster than the triple DES. It is one of the most widely used symmetric block cipher algorithm used nowadays. It works on bytes rather than bits. What is DES? It stands for Data Encryption Standard, develo
2 min read
Stream Ciphers
In stream cipher, one byte is encrypted at a time while in block cipher ~128 bits are encrypted at a time. Initially, a key(k) will be supplied as input to pseudorandom bit generator and then it produces a random 8-bit output which is treated as keystream. The resulted keystream will be of size 1 byte, i.e., 8 bits. Stream ciphers are fast because
4 min read
Latin alphabet cipher
The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest techniques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each letter of a given text is substituted by its corresponding number as represented in its alphabetical order. For Example, we have given a string as "hello everyone", then it
5 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Substitution Cipher
Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B w
7 min read
Feistel Cipher
Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as de
3 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values &amp; Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read