How to resolve the algorithm Caesar cipher step by step in the Modula-2 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Caesar cipher step by step in the Modula-2 programming language
Table of Contents
Problem Statement
Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Caesar cipher step by step in the Modula-2 programming language
Source code in the modula-2 programming language
MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
TYPE String = ARRAY[0..64] OF CHAR;
PROCEDURE Encrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t + key;
IF t>ORD('Z') THEN
t := t - 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t + key;
IF t>ORD('z') THEN
t := t - 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Encrypt;
PROCEDURE Decrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t - key;
IF t
t := t + 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t - key;
IF t
t := t + 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Decrypt;
VAR txt,enc : String;
VAR key : CARDINAL;
BEGIN
txt := "The five boxing wizards jump quickly";
key := 3;
WriteString("Original: ");
WriteString(txt);
WriteLn;
enc := Encrypt(txt, key);
WriteString("Encrypted: ");
WriteString(enc);
WriteLn;
WriteString("Decrypted: ");
WriteString(Decrypt(enc, key));
WriteLn;
ReadChar;
END CaesarCipher.
You may also check:How to resolve the algorithm Echo server step by step in the Ruby programming language
You may also check:How to resolve the algorithm Last Friday of each month step by step in the SQL programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Base64 decode data step by step in the Haxe programming language
You may also check:How to resolve the algorithm Rot-13 step by step in the Zoea Visual programming language