Skip to content

Instantly share code, notes, and snippets.

@theabhayprajapati
Created September 1, 2022 14:29
Show Gist options
  • Save theabhayprajapati/e6b2847a059cb2f0a86b348585bd2683 to your computer and use it in GitHub Desktop.
Save theabhayprajapati/e6b2847a059cb2f0a86b348585bd2683 to your computer and use it in GitHub Desktop.
Made a Algorithm for cryptography using principles of Caedar Cipher, where we want to encrypt a message then for that we make a key and for every letter in the message we increase it's alphabet with +key letter e.g for "a" and key is 10 then the encrypt word will be "k".
package DataStructures;
public class CaesarCipher {
static String encrypt(String msg, int key){
StringBuilder encrypted = new StringBuilder(msg);
String alphabets = "ABCDEFGHIJKLMNOPQRSTVUWXYZ";
String smallalphabets = alphabets.toLowerCase();
String shiftedAplhabets = alphabets.substring(key) + alphabets.substring(0, key);
for( int i =0; i< encrypted.length(); i++){
char curChar = encrypted.charAt(i);
int idx = alphabets.indexOf(curChar);
if(idx==-1){
idx = smallalphabets.indexOf(curChar);
}
if(idx !=-1){
char newChar;
if(isUppercased(String.valueOf(curChar))){
newChar = shiftedAplhabets.charAt(idx);
}else {
newChar = shiftedAplhabets.toLowerCase().charAt(idx);
}
encrypted.setCharAt(i, newChar);
}
}
return encrypted.toString();
}
static boolean isUppercased(String str){
return str == str.toUpperCase();
}
public static void main(String[] args) {
String msg = "There is a cake on the table";
System.out.println(encrypt(msg,12));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment