📄 caesar.java
字号:
/**
* 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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -