Caesar Cipher in Cryptography - GeeksforGeeks (2024)

Table of Contents
C++ Java Python3 C# PHP Javascript References

Last Updated : 11 May, 2023

Improve

Improve

Like Article

Like

Save

Report

  • The Caesar cipher is a simple encryption technique that was used by Julius Caesar to send secret messages to his allies. It works by shifting the letters in the plaintext message by a certain number of positions, known as the “shift” or “key”.
  • The Caesar Cipher technique is one of the earliest and simplest methods of encryption technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter with a fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on. The method is apparently named after Julius Caesar, who apparently used it to communicate with his officials.
  • Thus to cipher a given text we need an integer value, known as a shift which indicates the number of positions each letter of the text has been moved down.
    The encryption can be represented usingmodular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letterby a shiftncan be described mathematically as.
  • For example, if the shift is 3, then the letter A would be replaced by the letter D, B would become E, C would become F, and so on. The alphabet is wrapped around so that after Z, it starts back at A.
  • Here is an example of how to use the Caesar cipher to encrypt the message “HELLO” with a shift of 3:
  1. Write down the plaintext message: HELLO
  2. Choose a shift value. In this case, we will use a shift of 3.
  3. Replace each letter in the plaintext message with the letter that is three positions to the right in the alphabet.

H becomes K (shift 3 from H)

E becomes H (shift 3 from E)

L becomes O (shift 3 from L)

L becomes O (shift 3 from L)

O becomes R (shift 3 from O)

4.The encrypted message is now “KHOOR”.

  • To decrypt the message, you simply need to shift each letter back by the same number of positions. In this case, you would shift each letter in “KHOOR” back by 3 positions to get the original message, “HELLO”.


Caesar Cipher in Cryptography - GeeksforGeeks (1)
(Encryption Phase with shift n)

Caesar Cipher in Cryptography - GeeksforGeeks (2)
(Decryption Phase with shift n)

Caesar Cipher in Cryptography - GeeksforGeeks (3)

Examples :

Text : ABCDEFGHIJKLMNOPQRSTUVWXYZShift: 23Cipher: XYZABCDEFGHIJKLMNOPQRSTUVWText : ATTACKATONCEShift: 4Cipher: EXXEGOEXSRGI

Advantages:

  • Easy to implement and use thus, making suitable for beginners to learn about encryption.
  • Can be physically implemented, such as with a set of rotating disks or a set of cards, known as a scytale, which can be useful in certain situations.
  • Requires only a small set of pre-shared information.
  • Can be modified easily to create a more secure variant, such as by using a multiple shift values or keywords.

Disadvantages:

  • It is not secure against modern decryption methods.
  • Vulnerable to known-plaintext attacks, where an attacker has access to both the encrypted and unencrypted versions of the same messages.
  • The small number of possible keys means that an attacker can easily try all possible keys until the correct one is found, making it vulnerable to a brute force attack.
  • It is not suitable for long text encryption as it would be easy to crack.
  • It is not suitable for secure communication as it is easily broken.
  • Does not provide confidentiality, integrity, and authenticity in a message.

Features of caesar cipher:

  1. Substitution cipher: The Caesar cipher is a type of substitution cipher, where each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.
  2. Fixed key: The Caesar cipher uses a fixed key, which is the number of positions by which the letters are shifted. This key is known to both the sender and the receiver.
  3. Symmetric encryption: The Caesar cipher is a symmetric encryption technique, meaning that the same key is used for both encryption and decryption.
  4. Limited keyspace: The Caesar cipher has a very limited keyspace of only 26 possible keys, as there are only 26 letters in the English alphabet.
  5. Vulnerable to brute force attacks: The Caesar cipher is vulnerable to brute force attacks, as there are only 26 possible keys to try.
  6. Easy to implement: The Caesar cipher is very easy to implement and requires only simple arithmetic operations, making it a popular choice for simple encryption tasks.

Rules for the Caesar Cipher:

  1. Choose a number between 1 and 25. This will be your “shift” value.
  2. Write down the letters of the alphabet in order, from A to Z.
  3. Shift each letter of the alphabet by the “shift” value. For example, if the shift value is 3, A would become D, B would become E, C would become F, and so on.
  4. Encrypt your message by replacing each letter with the corresponding shifted letter. For example, if the shift value is 3, the word “hello” would become “khoor”.
  5. To decrypt the message, simply reverse the process by shifting each letter back by the same amount. For example, if the shift value is 3, the encrypted message “khoor” would become “hello”.

Algorithm for Caesar Cipher:
Input:

  1. Choose a shift value between 1 and 25.
  2. Write down the alphabet in order from A to Z.
  3. Create a new alphabet by shifting each letter of the original alphabet by the shift value. For example, if the shift value is 3, the new alphabet would be:
  4. 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
    D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
  5. Replace each letter of the message with the corresponding letter from the new alphabet. For example, if the shift value is 3, the word “hello” would become “khoor”.
  6. To decrypt the message, shift each letter back by the same amount. For example, if the shift value is 3, the encrypted message “khoor” would become “hello”.

Procedure:

  • Traverse the given text one character at a time .
  • For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text.
  • Return the new string generated.

A program that receives a Text (string) and Shift value( integer) and returns the encrypted text.

C++

// A C++ program to illustrate Caesar Cipher Technique

#include <iostream>

using namespace std;

// This function receives text and shift and

// returns the encrypted text

string encrypt(string text, int s)

{

string result = "";

// traverse text

for (int i = 0; i < text.length(); i++) {

// apply transformation to each character

// Encrypt Uppercase letters

if (isupper(text[i]))

result += char(int(text[i] + s - 65) % 26 + 65);

// Encrypt Lowercase letters

else

result += char(int(text[i] + s - 97) % 26 + 97);

}

// Return the resulting string

return result;

}

// Driver program to test the above function

int main()

{

string text = "ATTACKATONCE";

int s = 4;

cout << "Text : " << text;

cout << "\nShift: " << s;

cout << "\nCipher: " << encrypt(text, s);

return 0;

}

Java

//A Java Program to illustrate Caesar Cipher Technique

class CaesarCipher

{

// Encrypts text using a shift of s

public static StringBuffer encrypt(String text, int s)

{

StringBuffer result= new StringBuffer();

for (int i=0; i<text.length(); i++)

{

if (Character.isUpperCase(text.charAt(i)))

{

char ch = (char)(((int)text.charAt(i) +

s - 65) % 26 + 65);

result.append(ch);

}

else

{

char ch = (char)(((int)text.charAt(i) +

s - 97) % 26 + 97);

result.append(ch);

}

}

return result;

}

// Driver code

public static void main(String[] args)

{

String text = "ATTACKATONCE";

int s = 4;

System.out.println("Text : " + text);

System.out.println("Shift : " + s);

System.out.println("Cipher: " + encrypt(text, s));

}

}

 
 

Python3

#A python program to illustrate Caesar Cipher Technique

def encrypt(text,s):

result = ""

# traverse text

for i in range(len(text)):

char = text[i]

# Encrypt uppercase characters

if (char.isupper()):

result += chr((ord(char) + s-65) % 26 + 65)

# Encrypt lowercase characters

else:

result += chr((ord(char) + s - 97) % 26 + 97)

return result

#check the above function

text = "ATTACKATONCE"

s = 4

print ("Text : " + text)

print ("Shift : " + str(s))

print ("Cipher: " + encrypt(text,s))

 
 

C#

// A C# Program to illustrate Caesar Cipher Technique

using System;

using System.Text;

public class CaesarCipher

{

// Encrypts text using a shift on s

public static StringBuilder encrypt(String text, int s)

{

StringBuilder result= new StringBuilder();

for (int i=0; i<text.Length; i++)

{

if (char.IsUpper(text[i]))

{

char ch = (char)(((int)text[i] +

s - 65) % 26 + 65);

result.Append(ch);

}

else

{

char ch = (char)(((int)text[i] +

s - 97) % 26 + 97);

result.Append(ch);

}

}

return result;

}

// Driver code

public static void Main(String[] args)

{

String text = "ATTACKATONCE";

int s = 4;

Console.WriteLine("Text : " + text);

Console.WriteLine("Shift : " + s);

Console.WriteLine("Cipher: " + encrypt(text, s));

}

}

/* This code contributed by PrinciRaj1992 */

 
 

PHP

<?php

// A PHP program to illustrate Caesar

// Cipher Technique

// This function receives text and shift

// and returns the encrypted text

function encrypt($text, $s)

{

$result = "";

// traverse text

for ($i = 0; $i < strlen($text); $i++)

{

// apply transformation to each

// character Encrypt Uppercase letters

if (ctype_upper($text[$i]))

$result = $result.chr((ord($text[$i]) +

$s - 65) % 26 + 65);

// Encrypt Lowercase letters

else

$result = $result.chr((ord($text[$i]) +

$s - 97) % 26 + 97);

}

// Return the resulting string

return $result;

}

// Driver Code

$text = "ATTACKATONCE";

$s = 4;

echo "Text : " . $text;

echo "\nShift: " . $s;

echo "\nCipher: " . encrypt($text, $s);

// This code is contributed by ita_c

?>

 
 

Javascript

<script>

//A Javascript Program to illustrate Caesar Cipher Technique

// Encrypts text using a shift on s

function encrypt(text, s)

{

let result=""

for (let i = 0; i < text.length; i++)

{

let char = text[i];

if (char.toUpperCase(text[i]))

{

let ch = String.fromCharCode((char.charCodeAt(0) + s-65) % 26 + 65);

result += ch;

}

else

{

let ch = String.fromCharCode((char.charCodeAt(0) + s-97) % 26 + 97);

result += ch;

}

}

return result;

}

// Driver code

let text = "ATTACKATONCE";

let s = 4;

document.write("Text : " + text + "<br>");

document.write("Shift : " + s + "<br>");

document.write("Cipher: " + encrypt(text, s) + "<br>");

// This code is contributed by avanitrachhadiya2155

</script>

 
 

Output

Text : ATTACKATONCEShift: 4Cipher: EXXEGOEXSRGI

Time complexity: O(N) where N is length of the given text
Auxiliary space: O(N)

How to decrypt?
We can either write another function decrypt similar to encrypt, that’ll apply the given shift in the opposite direction to decrypt the original text.However we can use the cyclic property of the cipher under modulo, hence we can simply observe

Cipher(n) = De-cipher(26-n)

Hence, we can use the same function to decrypt, instead, we’ll modify the shift value such thatshift = 26-shift (Refer to this for a sample run in C++).



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Caesar Cipher in Cryptography - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 6326

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.