2

I'm trying to decrypt a cipher encrytion using a java method however my code doesn't seem to be returning correctly. I have tried to reverse the encryption process but I can't see what I'm doing wrong. Apologies, I hope this isn't a stupid question.

public void decrypt()
{
    String cipherText = this.message;
    String key = this.KEY;
    String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
    int alphabetSize = alphabet.length();
    int textSize = cipherText.length();
    int keySize = key.length();
    StringBuilder decryptedText = new StringBuilder(textSize);

    for (int i = 0; i < textSize; i++)
    {
        char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
        char keyChar = key.charAt(i % keySize); // use key again if the end is reached
        int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string
         // decrypt the input text
        int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
        int shiftedPos = plainPos-keyPos;
        shiftedPos += alphabetSize;
        decryptedText.append(alphabet.charAt(shiftedPos));
    }

    this.message =  decryptedText.toString();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Bradley
  • 617
  • 2
  • 11
  • 26

2 Answers2

0
shiftedPos += alphabetSize;

Why you do this? I think you have to do this only if shiftedPos<0.

if(shiftedPos<0)
   shiftedPos += alphabetSize;

That's because if a=0 and b=1, (a-b)=-1 that means z. To work with the whole ASCII set you just have to replace the alpabeth string and size with all the ASCII characters in the correct order.

Daniela Mogini
  • 299
  • 1
  • 5
  • 17
0

Taken these lines:

    char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
    char keyChar = key.charAt(i % keySize); // use key again if the end is reached
    int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string

    int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
            int shiftedPos = plainPos-keyPos;
            shiftedPos += alphabetSize;

There's a few issues.

  1. plainPos is actually an encrypted value, don't mix them up.
  2. plainPos-keyPos should be equal to the decrypted value. You should then be modding that by alphabetSize, to get the right value.

Be careful when working on the naming convention. That can really cause some issues...

Aside from that, then I think your code is actually working right. I certainly can't see any issues. Try it out via an online encryptor/decryptor.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142