38 lines
1.2 KiB
Java
38 lines
1.2 KiB
Java
package com.crypto;
|
|
public class Caesar {
|
|
|
|
public static String encode(String plaintext, int key){
|
|
String alphabet = "abcdefghijklmnopqrstuvwxyz";
|
|
char encoded[] = plaintext.toCharArray();
|
|
|
|
for(int i = 0; i < plaintext.length(); i++){
|
|
encoded[i] = alphabet.charAt(alphabet.indexOf(encoded[i]) + key % 26);
|
|
}
|
|
return String.valueOf(encoded);
|
|
}
|
|
|
|
public static String[] decode(String ciphertext){
|
|
String alphabet = "abcdefghijklmnopqrstuvwxyz";
|
|
char encoded[] = ciphertext.toCharArray();
|
|
|
|
char decoded[] = new char[ciphertext.length()];
|
|
String bruteforce[] = new String[26];
|
|
|
|
for(int key = 0; key < alphabet.length(); key++){
|
|
|
|
for(int i = 0; i < ciphertext.length(); i++){
|
|
char current = encoded[i];
|
|
int pos = alphabet.indexOf(current);
|
|
if(pos != -1) {
|
|
int newpos = (pos + key) % 26;
|
|
decoded[i] = alphabet.charAt(newpos);
|
|
} else
|
|
decoded[i] = current;
|
|
}
|
|
bruteforce[key] = String.valueOf(decoded);
|
|
}
|
|
return bruteforce;
|
|
|
|
}
|
|
}
|