Home > front end >  java encryptor with substitution cipher
java encryptor with substitution cipher

Time:02-05

I'm trying to understand how best to approach this question, I'm a newbie in java:

Write a java method which encrypts a message with a simple substitution cipher:

encryption and decryption

Input: 
payload = "Cat & 5 DogS"
Alpha arg = 5
Beta arg = 3

Output:
Payload enciphered = "nDU & 5 sVHp"

Explanation:
- "C" has a value 2,(2*5 3) & =13, 13 corresponds to 'n'.(lowercase since "C" is capitalized)
- "a" has a value of 0,(0*5 3) & = 3, 3 corresponds to "D" (capitalized because "a" is lowercase)
- "". "&", "", "5" and "" are unchanged. 

CodePudding user response:

@kiner_shah, you mean something like this:

public Substitute()

{ key = new byte[256];

for(int i = -128; i < 128; i  )
{
    list.add((byte)i);
}
Collections.shuffle(list);
Byte[] tmp = new Byte[256];
tmp = list.toArray(tmp);

for(int i = 0; i < 256; i  )
{
    key[i] = tmp[i];        
}

}

CodePudding user response:

Here is a basic approach to the problem. It's kind of lengthy but it works just fine. Let me know if you have any questions. In fact, the solution is actually in your explanation. I hope this code helps you. Happy coding!!

class Main {
  public static void main(String[] args) {
   
   String plainText = "Cat & 5 DogS";
   
   for (int i = 0; i < plainText.length(); i  ){       
        shiftCharacter(plainText.charAt(i));
   }

  }

public static void shiftCharacter(char toShift){

    char [] alphaL = {'a', 'b', 'c', 'd', 'e', 'f','g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '&', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    char [] alphaC = {'A', 'B', 'C', 'D', 'E', 'F','G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',' ', '&', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    char newChar;
    for (int i = 0; i < alphaL.length; i  ){

            if (alphaL[i] == toShift && i < 26){
                int index = ((i * 5   3)) % 26;
                newChar = alphaC[index];
                System.out.print(newChar);
            }
            else if (alphaC[i] == toShift && i < 26 ){
                int index = ((i * 5   3 )) % 26 ;
                newChar = alphaL[index];
                System.out.print(newChar);
            }
    
            else if (alphaL[i]  == toShift && i >= 26){
            newChar = alphaL[i];
            System.out.print(newChar);
        }
    }
    
}
}
  •  Tags:  
  • Related