package aufgabe4; /** * Generic test class defining the caesar chiffre * _ _ _ _ * __ ___ __(_) |_| |_ ___ _ __ | |__ _ _ * \ \ /\ / / '__| | __| __/ _ \ '_ \ | '_ \| | | | * \ V V /| | | | |_| || __/ | | | | |_) | |_| | * \_/\_/ |_| |_|\__|\__\___|_| |_| |_.__/ \__, | * |___/ * ____ __ __ _ * / ___|_ _____ _ __ \ \ / /__ __ _ ___| | * \___ \ \ / / _ \ '_ \ \ \ / / _ \ / _` |/ _ \ | * ___) \ V / __/ | | | \ V / (_) | (_| | __/ | * |____/ \_/ \___|_| |_| \_/ \___/ \__, |\___|_| * |___/ * Licensed under the GPLv2 License, Version 2.0 (the "License"); * Copyright (c) Sven Vogel */ public class CaesarChiffre implements Chiffrierung { /** * How much to shift every character */ private final int shiftOffset; public CaesarChiffre(int shiftOffset) { this.shiftOffset = shiftOffset; } /** * Shift a character by a specified amount away from its UTF-8 representation * Performs a wraparound for lower case letters and return all other characters unchanged * @param ch the character to shift * @param off shift offset * @return the shifted character */ private char shiftCharacter(char ch, int off) { if (Character.isLowerCase(ch)) { return (char) wrapAddAround(ch, off, 'a', 'z'); } return ch; } /** * Sums k onto x and wraps the result around the domain of [min, max] * @param x lhs of sum * @param k rhs of sum * @param min minimum value to wrap around * @param max maximum value to wrap around * @return the result */ public static int wrapAddAround(int x, int k, int min, int max) { return Math.floorMod(Math.abs(x - min) + k, max - min + 1) + min; } @Override public char chiffrieren(char zeichen) { return shiftCharacter(zeichen, shiftOffset); } @Override public char dechiffrieren(char zeichen) { return shiftCharacter(zeichen, -shiftOffset); } }