Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Vigenere {
- private final int SIZE = 26;
- private final int BASE = 65;
- private char[][] cryptex = new char[SIZE][SIZE];
- // constructors ========================================================
- public Vigenere() {
- // generate Vigenere cryptex
- for (int row = 0; row < SIZE; row++) {
- int i = 0;
- for (int col = 0; col < SIZE; col++) {
- cryptex[row][col] = (char)(('A' + row + i++) % SIZE + BASE);
- }
- }
- }
- // getters/setters =====================================================
- // methods =============================================================
- public char encrypt(char letter, char key) {
- return cryptex[letter % SIZE][key % SIZE];
- }
- public String encrypt(String message, String key) {
- StringBuilder sb = new StringBuilder();
- message = message.toUpperCase();
- key = key.toUpperCase();
- for (int i = 0, j = 0; i < message.length(); i++) {
- if (message.charAt(i) >= 'A' && message.charAt(i) <= 'Z') {
- sb.append(encrypt(message.charAt(i), key.charAt(j++ % key.length())));
- }
- else
- sb.append(message.charAt(i));
- }
- return sb.toString();
- }
- public char decrypt(char letter, char key) {
- int index = findLetter(letter, key);
- return cryptex[index][0];
- }
- public String decrypt(String cipher, String key) {
- StringBuilder sb = new StringBuilder();
- cipher = cipher.toUpperCase();
- key = key.toUpperCase();
- for (int i = 0, j = 0; i < cipher.length(); i++) {
- if (cipher.charAt(i) >= 'A' && cipher.charAt(i) <= 'Z') {
- sb.append(decrypt(cipher.charAt(i), key.charAt(j++ % key.length())));
- }
- else
- sb.append(cipher.charAt(i));
- }
- return sb.toString();
- }
- // helper methods ======================================================
- private int findLetter(char letter, char key) {
- for (int i = 0; i < SIZE; i++) {
- if (cryptex[i][key % SIZE] == letter)
- return i;
- }
- return -1;
- }
- }
Add Comment
Please, Sign In to add comment