凱撒密碼 是最古老的替換加密技術之一,核心思想是將字母表中的每個字母向後(或向前)固定位移 k 位。本文實現經典的 位移 3 位 版本(k=3),僅處理英文字母,保持大小寫不敏感(統一轉小寫處理)。
import java.util.regex.Pattern;
public class CaesarCipher {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private static final int LEN = ALPHABET.length();
private static final int SHIFT = 3; // 經典位移量
public static void main(String[] args) {
String plain = "newyork";
String encrypted = encrypt(plain);
String decrypted = decrypt(encrypted);
System.out.println("明文: " + plain);
System.out.println("密文: " + encrypted); // qhzbrun
System.out.println("解密: " + decrypted); // newyork
}
/** 加密:字母後移 3 位 */
public static String encrypt(String plainText) {
if (plainText == null || plainText.isEmpty()) {
System.out.println("輸入為空");
return null;
}
if (!isAlphaOnly(plainText)) {
System.out.println("僅支持英文字母");
return null;
}
StringBuilder sb = new StringBuilder();
String lower = plainText.toLowerCase();
for (char c : lower.toCharArray()) {
int idx = ALPHABET.indexOf(c);
// 處理邊界:x,y,z 循環到 a,b,c
int newIdx = (idx + SHIFT) % LEN;
sb.append(ALPHABET.charAt(newIdx));
}
return sb.toString();
}
/** 解密:字母前移 3 位 */
public static String decrypt(String cipherText) {
if (cipherText == null || cipherText.isEmpty()) {
System.out.println("輸入為空");
return null;
}
if (!isAlphaOnly(cipherText)) {
System.out.println("僅支持英文字母");
return null;
}
StringBuilder sb = new StringBuilder();
String lower = cipherText.toLowerCase();
for (char c : lower.toCharArray()) {
int idx = ALPHABET.indexOf(c);
// 處理邊界:a,b,c 循環到 x,y,z
int newIdx = (idx - SHIFT + LEN) % LEN;
sb.append(ALPHABET.charAt(newIdx));
}
return sb.toString();
}
/** 驗證是否純英文字母 */
private static boolean isAlphaOnly(String s) {
return Pattern.matches("^[A-Za-z]+$", s);
}
}
| 場景 | 索引計算 | 示例 (SHIFT=3) |
|---|---|---|
| 加密 | (index + SHIFT) % 26 | x(23) → (23+3)%26=0 → a |
| 解密 | (index - SHIFT + 26) % 26 | a(0) → (0-3+26)%26=23 → x |
關鍵點:使用模運算 % LEN 實現字母表循環,避免原代碼中繁瑣的 if (a == LEN-1) a = -1 邊界判斷。
k(仿射密碼、維熱納密碼)本文提供了簡潔、健壯、可擴展的凱撒密碼 Java 實現。通過模運算優雅處理邊界,正則驗證輸入,代碼結構清晰,適合初學者理解對稱加密基本原理與字符串處理技巧。