Skip to main content

2d Caesar Cipher (chars)

Cryptogrpahy Video Eplainationsโ€‹

The Caesar Cipherโ€‹

Programming a Caesar Cipherโ€‹

shift = 3

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

'Complete' Cypher Programโ€‹

class Main {
public static void main(String[] args) {
String message = "Hello World";
int offset=3;

StringBuilder result = new StringBuilder();
for (char character : message.toCharArray()) {
if (character != ' ') {
int originalAlphabetPosition = character - 'a';
int newAlphabetPosition = (originalAlphabetPosition + offset) % 26;
char newCharacter = (char) ('a' + newAlphabetPosition);
result.append(newCharacter);
} else {
result.append(character);
}
}
System.out.println(result);

}
}
๐Ÿงช Try the code out~!

Don't worrry about understanding the code yet! Since it goes over topics we didn't teach yet.

Exercise

  • Try Changing the message.
  • Try changing the offset

Breaking down the programโ€‹

class Main {
public static void main(String[] args) {
char character = 'a';
int offset=4;

int originalAlphabetPosition = character - 'a';
int newAlphabetPosition = (originalAlphabetPosition + offset);
char newCharacter = (char) ('a' + newAlphabetPosition);
System.out.println(newCharacter);

}
}

๐Ÿงช Try the code out~!
Exercise
  • Change Character from a into b what do you think it should print?
  • Change offset from 4 to 2 wha do you think it will be print?
But there is a bug!
  • What happens if we write as letter z?

Fixing Our Minimalist Cipherโ€‹

Here we have a simplified version of the program that only encodes one character.

Cypher

  • Modular Explaination
class Main {
public static void main(String[] args) {
char character = 'h';
int offset=4;

int originalAlphabetPosition = character - 'a';
int newAlphabetPosition = (originalAlphabetPosition + offset) % 26;
char newCharacter = (char) ('a' + newAlphabetPosition);
System.out.println(newCharacter);

}
}

๐Ÿงช Try the code out~!

Assigment: Asking for User Inputโ€‹

The following program prompts the user to enter a character and encrypt it using the caesar cypher.

import java.util.*;

class Main {
public static void main(String[] args) {

System.out.print("Enter a Character : ");
Scanner sc = new Scanner(System.in);
char character = sc.nextLine().charAt(0);
int offset=4;

int originalAlphabetPosition = character - 'a';
int newAlphabetPosition = (originalAlphabetPosition + offset) % 26;
char newCharacter = (char) ('a' + newAlphabetPosition);
System.out.println(newCharacter);

}
}



Please fix this program
  • So it asks what character to encrypt
  • So that it also ask whats the offset of this.

More about cryptographyโ€‹

On the future

I don't think we will be going over those this semester, but hopefully I will be populating the "blog" section with more cryptography related problems and solutions as it is pretty relevant for Computer Science.

Cryptogrpahy: Crash Course Computer Scienceโ€‹