caesar.java

来自「用JAVA编写的小的JAVA程序,是有关密码转换的.有2种算法.」· Java 代码 · 共 60 行

JAVA
60
字号
/**
 * En-/decryption with the caesar method
 */
public class Caesar extends Cipher {

	public Caesar() {}

	private String modifyChars(String text, int key) {
		StringBuffer result = new StringBuffer(text.length());

		//for every char
		for (int i = 0; i < text.length(); i++) {
			try {
				int index = alphabetIndex(text.charAt(i));

				//encrypt char
				index = (index + key) % ALPHABET.length;
				if (index < 0) index += ALPHABET.length;

				result.append(ALPHABET[index]);
			} catch (IllegalArgumentException e) {
				//Ignore this character
				System.err.println(e.getMessage());
			}
		}

		return result.toString();
	}

	/**
	 * @see Cipher#encrypt(java.lang.String)
	 */
	public String encrypt(String plaintext) {
		return modifyChars(plaintext, getIntKey());
	}

	/**
	 * @see Cipher#decrypt(java.lang.String)
	 */
	public String decrypt(String ciphertext) {
		return modifyChars(ciphertext, -getIntKey());
	}

	/**
	 * Returns the character's index in the cipher alphabet (allows an extended unsorted and discontiguous alphabet array)
	 *
	 * @param c The character
	 * @return the character's index in the cipher alphabet
	 * @throws IllegalArgumentException if the charater is not in the cipher alphabet
	 */
	private int alphabetIndex(char c) {
		for (int i = 0; i < ALPHABET.length; i++) {
			if (c == ALPHABET[i]) return i;
		}

		throw new IllegalArgumentException("The character \"" + c + "\" is not in the cipher alphabet.");
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?