I was trying to do a Vigenere cipher program in java, and I encountered some problem with the encryption/decryption part of the code. I know how I should go about approaching the encryption/decryption, but I am having trouble putting that into code.
Let me start off by explaining the project:
For this project, I am creating a cipher program (Vigenere cipher is different than caesar cipher in that Vigenere allows the key to be a word rather than just a letter or number) that first prompt the user if he/she wants to encrypt or decrypt a message. Once the user makes the selection, the program prompts the user for a “key”. the key has to be lower case, and a word, not symbols or numbers. Then the program will ask the user for an input file that contains the message the user wants to decrypt or encrypt. Afterward, the program prompts the user for an output file name and store the decrypted/encrypted message in that file.
So let’s say the message is “Meet at 567” and the key is cats, and the user want to encrypt the message, the output should end up like “Oexl ct 567”
The encryptLine/decryptLine method of my code only needs to encrypt/decrypt one line of text. the other parts of my code will take care of other lines. For the code that I have done so far, the decryptLine is completely wrong, right now, I just want to focus on the encryptLine. Once I figure that out, figuring out the decryptLine shouldn’t be so hard. In the following, I have post comments in my encryptLine method as to what I am trying to do. The encryption works, it just has trouble when it encounter a space or symbols such as ?&%$. I know it has a lot of redundant code, but it is the best things I could come up with since I am new at this.
Thank you in advance for your help!!!
The problem is that, when you’re processing position
iwithinline, you’re expecting to be able to compute the position withinkeybased oni. This makes sense —key.charAt(i%(key.length()+1))is almost correct (though it actually would have to bekey.charAt(i%key.length()), without the+1, since the valid positions inkeyrange from0tokey.length()-1) — but it won’t work for you, because you want certain characters not to “count”, that is, you don’t want them to “use up” a character in thekey. So your position withinkeyis actually somewhat independent ofi, in that it also depends on what types of characters you’ve already seen inline.So really what you need is to have a completely separate index,
j, withinkey. Every time you process a letter fromline, you incrementj. You can then either use the modulus approach, and writekey.charAt(j%key.length()), or else simply resetjto0every time it would otherwise bekey.length().