0% found this document useful (0 votes)
24 views7 pages

Java Caesar Cipher Implementation

The document discusses two classic cryptography programs in Java: 1) The Caesar Cipher program which encrypts and decrypts text by shifting each letter by a number of places in the alphabet (called the key). It includes functions for encryption and decryption. 2) The Rot13 program which encrypts text by rotating each letter 13 places. It reads input files and performs the encryption.

Uploaded by

Shoffar Amrullah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views7 pages

Java Caesar Cipher Implementation

The document discusses two classic cryptography programs in Java: 1) The Caesar Cipher program which encrypts and decrypts text by shifting each letter by a number of places in the alphabet (called the key). It includes functions for encryption and decryption. 2) The Rot13 program which encrypts text by rotating each letter 13 places. It reads input files and performs the encryption.

Uploaded by

Shoffar Amrullah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java-KriptografiKlasik

Berbagai Program Kriptografi Klasik

Caesar Cipher
Program : [Link]

import [Link];

/**
* Program CaesarCipher
*/

public class CaesarCipher {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
String str;
String key;
int keyLength;

[Link]("Enter message: ");


str = [Link]();
[Link]("Enter encryption key: ");
key = [Link]();
keyLength = [Link](key);

// Pengulangan terus-menerus dari pilihan 'Enrypt' and 'Decrypt'


for (;;) {
[Link]("[Link]\[Link]\[Link]...");
int choice = [Link]();
switch (choice) {
case 1:
/*
* send input string keyLength to encrypt() method to encrypt it returns
* 'Encrypted' string
*/
[Link]("Encrypted message..." + encrypt(str, keyLength));
break;
case 2:
// send retrived string from encrypt() method and keyLength to decrypt() method
// it returns 'Decrypted' string
[Link]("Decryptedmessage..." + decrypt(encrypt(str, keyLength),
keyLength));
break;
case 3:
// exit from the program
[Link](0);
[Link]();
break;
default:
[Link]("Invalid option..");
}
}
}

Page 1 of 7
Java-KriptografiKlasik
public static String encrypt(String str, int keyLength) {
String encrypted = "";
for (int i = 0; i < [Link](); i++) {
// stores ascii value of character in the string at index 'i'
int c = [Link](i);
// encryption logic for uppercase letters
if ([Link](c)) {
c = c + (keyLength % 26);
// if c value exceeds the ascii value of 'Z' reduce it by subtracting 26([Link]
// alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if (c > 'Z')
c = c - 26;
}
// encryption logic for lowercase letters
else if ([Link](c)) {
c = c + (keyLength % 26);
// if c value exceeds the ascii value of 'z' reduce it by subtracting 26([Link]
// alphabets) to keep in boundaries of ascii values of 'a' and 'z'
if (c > 'z')
c = c - 26;
}
// concatinate the encrypted characters/strings
encrypted = encrypted + (char) c;
}
return encrypted;
}

public static String decrypt(String str, int keyLength) {


String decrypted = "";
for (int i = 0; i < [Link](); i++) {
// stores ascii value of character in the string at index 'i'
int c = [Link](i);
// decryption logic for uppercase letters
if ([Link](c)) {
c = c - (keyLength % 26);
// if c value deceed the ascii value of 'A' increase it by adding 26([Link]
// alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if (c < 'A')
c = c + 26;
}
// decryption logic for uppercase letters
else if ([Link](c)) {
c = c - (keyLength % 26);
// if c value deceed the ascii value of 'A' increase it by adding 26([Link]
// alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if (c < 'a')
c = c + 26;
}
// concatinate the decrypted characters/strings
decrypted = decrypted + (char) c;
}
return decrypted;
}
}

Program [Link]

import [Link]; Page 2 of 7


Java-KriptografiKlasik
import [Link];

/**
* CaesarCipherProgram
*
*/
public class CaesarCipherProgram {

public static void main(String[] args) {


Scanner input = new Scanner([Link]);
while (true) {
[Link]("[Link]\[Link]\[Link]...");
int choice = [Link]();

switch (choice) {
case 1:
// Masuk ke fungsi Enkripsi
Eknripsi();
break;
case 2:
// Masuk ke fungsi Dekripsi
Dekripsi();
break;
case 3:
// exit from the program
[Link](0);
break;
default:
[Link]("Invalid option..");
}
}
}

// Fungsi untuk melakukan enkripsi metode Caesar


public static void Eknripsi() {
Scanner sc = new Scanner([Link]);
[Link]("Masukkan pesan plaintext : ");
String plaintext = [Link]();
[Link]("Masukkan nilai dimana karakter plaintext akan di-shifted : ");
int shift = [Link]();
String ciphertext = "";
char alphabet;

for (int i = 0; i < [Link](); i++) {


// Shift one character at a time
alphabet = [Link](i);

// if alphabet lies between a and z


if (alphabet >= 'a' && alphabet <= 'z') {
// shift alphabet
alphabet = (char) (alphabet + shift);
// if shift alphabet greater than 'z'
if (alphabet > 'z') {
// reshift to starting position
alphabet = (char) (alphabet + 'a' - 'z' - 1);
}
ciphertext = ciphertext + alphabet;
}
Page 3 of 7
Java-KriptografiKlasik
// if alphabet lies between 'A'and 'Z'
else if (alphabet >= 'A' && alphabet <= 'Z') {
// shift alphabet
alphabet = (char) (alphabet + shift);

// if shift alphabet greater than 'Z'


if (alphabet > 'Z') {
// reshift to starting position
alphabet = (char) (alphabet + 'A' - 'Z' - 1);
}
ciphertext = ciphertext + alphabet;
} else {
ciphertext = ciphertext + alphabet;
}

}
[Link]("ciphertext : " + ciphertext);
}

// Fungsi untuk melakukan Dekripsi metode Caesar


public static void Dekripsi() {
Scanner sc = new Scanner([Link]);
[Link]("Masukkan pesan ciphertext : ");
String ciphertext = [Link]();
[Link]("Masukkan nilai shift : ");
int shift = [Link]();
String decryptMessage = "";

for (int i = 0; i < [Link](); i++) {


// Shift one character at a time
char alphabet = [Link](i);
// if alphabet lies between a and z
if (alphabet >= 'a' && alphabet <= 'z') {
// shift alphabet
alphabet = (char) (alphabet - shift);

// shift alphabet lesser than 'a'


if (alphabet < 'a') {
// reshift to starting position
alphabet = (char) (alphabet - 'a' + 'z' + 1);
}
decryptMessage = decryptMessage + alphabet;
}
// if alphabet lies between A and Z
else if (alphabet >= 'A' && alphabet <= 'Z') {
// shift alphabet
alphabet = (char) (alphabet - shift);

// shift alphabet lesser than 'A'


if (alphabet < 'A') {
// reshift to starting position
alphabet = (char) (alphabet - 'A' + 'Z' + 1);
}
decryptMessage = decryptMessage + alphabet;
} else {
decryptMessage = decryptMessage + alphabet;
}
}
Page 4 of 7
Java-KriptografiKlasik
[Link]("decrypt message : " + decryptMessage);
}
}

Rot13
Program [Link]

import [Link].*;

/**
* Rot13
*
*/
public class Rot13 {

public static void main(String[] args) throws IOException {


if ([Link] >= 1) {
for (String file : args) {
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
rot13(in, [Link]);
}
}
} else {
rot13([Link], [Link]);
}
}

private static void rot13(InputStream in, OutputStream out) throws IOException {


int ch;
while ((ch = [Link]()) != -1) {
[Link](rot13((char) ch));
}
}

private static char rot13(char ch) {


if (ch >= 'A' && ch <= 'Z') {
return (char) (((ch - 'A') + 13) % 26 + 'A');
}
if (ch >= 'a' && ch <= 'z') {
return (char) (((ch - 'a') + 13) % 26 + 'a');
}
return ch;
}
}

Subtitution Cipher
Program [Link]

Page 5 of 7
Java-KriptografiKlasik

/**
* SubtitutionCipher
*/
public class SubtitutionCipher {

final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"


+ "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

static String text = "Here we have to do is there will be a input/source "


+ "file in which we are going to Encrypt the file by replacing every "
+ "upper/lower case alphabets of the source file with another "
+ "predetermined upper/lower case alphabets or symbols and save "
+ "it into another output/encrypted file and then again convert "
+ "that output/encrypted file into original/decrypted file. This "
+ "type of Encryption/Decryption scheme is often called a "
+ "Substitution Cipher.";

public static void main(String[] args) {


String enc = encode(text);
[Link]("Encoded: " + enc);
[Link]("\nDecoded: " + decode(enc));
}

static String encode(String s) {


StringBuilder sb = new StringBuilder([Link]());

for (char c : [Link]())


[Link]([Link]((int) c - 32));

return [Link]();
}

static String decode(String s) {


StringBuilder sb = new StringBuilder([Link]());

for (char c : [Link]())


[Link]((char) ([Link]((int) c) + 32));

return [Link]();
}
}

Vigenere Cipher
Program [Link]

Page 6 of 7
Java-KriptografiKlasik

/**
* VigenereCipher
*/
public class VigenereCipher {

public static void main(String[] args) {


String key = "VIGENERECIPHER";
String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
String enc = encrypt(ori, key);
[Link](enc);
[Link](decrypt(enc, key));
}

static String encrypt(String text, final String key) {


String res = "";
text = [Link]();
for (int i = 0, j = 0; i < [Link](); i++) {
char c = [Link](i);
if (c < 'A' || c > 'Z')
continue;
res += (char) ((c + [Link](j) - 2 * 'A') % 26 + 'A');
j = ++j % [Link]();
}
return res;
}

static String decrypt(String text, final String key) {


String res = "";
text = [Link]();
for (int i = 0, j = 0; i < [Link](); i++) {
char c = [Link](i);
if (c < 'A' || c > 'Z')
continue;
res += (char) ((c - [Link](j) + 26) % 26 + 'A');
j = ++j % [Link]();
}
return res;
}
}

Page 7 of 7

Common questions

Powered by AI

Caesar Cipher uses a single key for encryption by shifting each character by a fixed number, which can be constant for the entire text . In contrast, the Vigenère Cipher uses a key that is a word or phrase, and each letter of the key shifts the text's corresponding letter . Hence, the Vigenère Cipher applies a different shift for each character in the text, thus providing more security compared to the static, single-shift Caesar Cipher .

The Caesar Cipher program handles invalid user input for operation choices by using a default case in a switch statement. If the user selects an option that is not recognized (not 1, 2, or 3), it prints "Invalid option.." and continues the loop allowing the user to try again .

The primary limitation of using a fixed key length in Caesar Cipher is its predictability and ease of breaking. Since it uses a single shift value for the entire message, it's vulnerable to frequency analysis and brute force attacks with only 26 possible keys. In contrast, the Vigenère Cipher's use of a dynamic key approach, where the key itself is a sequence of letters, increases the complexity of decryption without knowing the key, making it resistant to simple frequency analysis .

The Substitution Cipher differs from the Caesar and Vigenère ciphers by replacing each letter in the plaintext with a corresponding letter in the cipher alphabet. Unlike Caesar, which applies a uniform shift, or Vigenère, which varies shifts based on a key, Substitution Cipher can use any permutation of the alphabet, increasing the number of possible keys drastically . This makes it significantly harder to break through frequency analysis compared to the simpler and more predictable structure of Caesar and Vigenère ciphers .

ROT13 cipher is simple because it is a special case of the Caesar Cipher with a fixed shift of 13 positions. Encryption and decryption are the same operation, making it symmetric. Each letter is shifted by 13 places in the alphabet, and applying the same shift again returns the original text .

The re-shifting of characters in the Caesar Cipher ensures that the encrypted letters stay within the bounds of the alphabet. For encryption, if a character exceeded 'Z' or 'z', it is wrapped back to the start of the alphabet by subtracting 26. Similarly, during decryption, if subtracting the shift moves a character before 'A' or 'a', it adds 26 to stay within the valid range .

The substitution key directly impacts the security complexity of the Substitution Cipher as it determines how characters from the original text are transformed into their cipher equivalents. With 52 possible characters for each position (upper and lower case), there are an enormous number of potential permutations, making it impractical to break the cipher through brute force. However, if an attacker uncovers part of the key or notes frequent letter substitutions, the security could be compromised, especially if the key doesn't distribute frequencies uniformly .

The Rot13 implementation processes characters directly as they are read and written, making it efficient for in-place transformation without additional storage. However, using I/O stream operations can introduce overhead, particularly with numerous or large files, due to the time costs of accessing disk storage, which often dominates the CPU time needed to perform the ROT13 computation .

In the Caesar Cipher Java implementation, ASCII values are used to calculate the new position of each character after shifting it by the key length. The program adjusts the ASCII value of each character based on the shift and checks boundaries for uppercase ('A' to 'Z') and lowercase ('a' to 'z') characters to handle the wrap-around effect properly .

The Vigenère Cipher mitigates the repetitive pattern weakness found in the Caesar Cipher by employing a key composed of multiple letters, which varies the shift for each character based on the corresponding key character. This method disrupts easily recognizable letter occurrence patterns, such as those found in Caesar continuously using a single shift for all letters. By modulating the shift, the Vigenère Cipher creates encrypted texts that are far less susceptible to frequency analysis, making it a more robust encryption method against cryptanalysis .

You might also like