Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CipherKey {
- private String key = "I LOVE ME";
- private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; // Initializing the alphabet as a String for later use
- public CipherKey(){
- };
- public void setKey (String key){
- boolean isValid = true;
- for (char c : key.toCharArray()) { // Making sure its only uppercase letters and setting isValid to false if it encounters an invalid character
- if (((int)c > 90 || (int)c < 65) && (int)c != 32){
- isValid = false;
- }
- }
- if(key.length() < 1){
- isValid = false;
- }
- if(isValid) {
- this.key = key;
- }
- }
- public String encrypt(String phrase){
- int times = (phrase.length() / this.key.length()) + 1;
- String k = "";
- if(phrase.length()> this.key.length()) {
- for (int i = 0; i < times; i++) {
- k += this.key;
- }
- } else {
- k = this.key;
- }
- String finalKey = k.substring(0, phrase.length());
- String encrypted ="";
- for (int i = 0; i < phrase.length(); i++) {
- if((int)((alphabet.indexOf(finalKey.toCharArray()[i]+1)+ phrase.toCharArray()[i])) > 126){
- encrypted += (char)((alphabet.indexOf(finalKey.toCharArray()[i])+1 + phrase.toCharArray()[i])-95);
- } else {
- encrypted += (char)(alphabet.indexOf(finalKey.toCharArray()[i])+1 + phrase.toCharArray()[i]);
- }
- }
- return encrypted;
- }
- public String decrypt ( String phrase){
- int times = (phrase.length() / this.key.length()) + 1;
- String k = "";
- if(phrase.length()>this.key.length()) {
- for (int i = 0; i < times; i++) {
- k += this.key;
- }
- } else {
- k = this.key;
- }
- String finalKeyDecrypt = k.substring(0, phrase.length());
- String decrypted = "";
- for (int i = 0; i < phrase.length() ; i++) {
- decrypted += (char) (phrase.toCharArray()[i] - (alphabet.indexOf(finalKeyDecrypt.toCharArray()[i])+1));
- }
- return decrypted;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment