/****************************************************************************** * This filter program encrypts/decrypts text using a Vigenere Cipher. * Input text is taken from standard input and output text is written * to standard output. Assume only ASCII input/output. * * The first command line argument is the password * The second command line argument is the encrypt "e" or decrypt "d" * mode. * * Copyright © 2017 Richard Lesh. All rights reserved. *****************************************************************************/ import org.pureprogrammer.Utils; public class VigenereCipher { static final String ALPHABET = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; static final int ALPHABET_LEN = Utils.cpLength(ALPHABET); static int shiftChar(int cp, int shift, boolean encrypt) { int newCp = cp; int pos = Utils.cpIndexOf(ALPHABET, cp); if (pos != -1) { if (encrypt) { pos = (pos + shift) % ALPHABET_LEN; } else { pos = (pos - shift + ALPHABET_LEN) % ALPHABET_LEN; } newCp = Utils.cpAt(ALPHABET, pos); } return newCp; } public static void main(String[] args) { if (args.length != 2) { System.out.println(Utils.join("", "Syntax: ", "VigenereCipher", " password e|d")); System.exit(1); } String password = args[0]; boolean encrypt = (args[1].equals("e") ); int passwordPos = 0; int passwordLen = Utils.cpLength(password); int c; while ((c = Utils.getchar()) != -1) { int pwdCp = Utils.cpAt(password, passwordPos % passwordLen); int shift = Utils.cpIndexOf(ALPHABET, pwdCp); if (shift != -1) { c = shiftChar(c, shift, encrypt); } System.out.print(String.valueOf(Character.toChars(c))); ++passwordPos; } } }