Ciphertext - A virus
test banner

Post Top Ad

Responsive Ads Here

Ciphertext

Share This

TCS Coding Question  Slot 2 – Question 2

 The Caesar cipher is a type of substitution cipher in which each alphabet in the plaintext or messages is shifted by a number of places down the alphabet.

For example,with a shift of 1, P would be replaced by Q, Q would become R, and so on.

To pass an encrypted message from one person to another, it is first necessary that both parties have the ‘Key’ for the cipher, so that the sender may encrypt and the receiver may decrypt it.


Key is the number of OFFSET to shift the cipher alphabet. Key can have basic shifts from 1 to 25 positions as there are 26 total alphabets.


As we are designing custom Caesar Cipher, in addition to alphabets, we are considering numeric digits from 0 to 9. Digits can also be shifted by key places.


For Example, if a given plain text contains any digit with values 5 and keyy =2, then 5 will be replaced by 7, “-”(minus sign) will remain as it is. Key value less than 0 should result into “INVALID INPUT”


Example 1: 


Enter your PlainText: All the best


Enter the Key: 1


The encrypted Text is: Bmm uif Cftu


Write a function CustomCaesarCipher(int key, String message) which will accept plaintext and key as input parameters and returns its cipher text as output:



import java.util.Scanner;


public class Ciphertext {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println(" Enter your PlainText: ");

String plaintext = sc.nextLine();

System.out.println(" Enter the Key: ");

int shift = sc.nextInt();

String ciphertext = "";

char alphabet;

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

alphabet = plaintext.charAt(i);


if (alphabet >= 'a' && alphabet <= 'z') {

alphabet = (char) (alphabet + shift);

if (alphabet > 'z') {

alphabet = (char) (alphabet + 'a' - 'z' - 1);

}

ciphertext = ciphertext + alphabet;

} else if (alphabet >= 'A' && alphabet <= 'Z') {

alphabet = (char) (alphabet + shift);


if (alphabet > 'Z') {

alphabet = (char) (alphabet + 'A' - 'Z' - 1);

}

ciphertext = ciphertext + alphabet;

} else if (alphabet >= '0' && alphabet <= '9') {

alphabet = (char) (alphabet + shift);


if (alphabet > '9') {

alphabet = (char) (alphabet + '0' - '9' - 1);

}

ciphertext = ciphertext + alphabet;

} else {

ciphertext = ciphertext + alphabet;

}

}

System.out.println(" The encrypted Text is : " + ciphertext);

}

}




Output

Enter your PlainText: 

Avirusraj416

 Enter the Key: 

2

 The encrypted Text is : Cxktwutcl638


No comments:

Post a Comment

Post Bottom Ad

Responsive Ads Here

Pages