首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現凱撒密碼加解密算法完整代碼與原理解析

     編輯:Java 相關知識

凱撒密碼原理

凱撒密碼 是最古老的替換加密技術之一,核心思想是將字母表中的每個字母向後(或向前)固定位移 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) % 26x(23) → (23+3)%26=0 → a
解密(index - SHIFT + 26) % 26a(0) → (0-3+26)%26=23 → x

關鍵點:使用模運算 % LEN 實現字母表循環,避免原代碼中繁瑣的 if (a == LEN-1) a = -1 邊界判斷。

安全性分析與擴展建議

  • 極不安全:鍵空間僅 25 種(排除位移 0),極易暴力破解。
  • 僅教學用途:理解替換密碼、模運算、字符編碼處理。
  • 擴展方向:
    • 支援大小寫保持、數字、標點符號
    • 可配置位移量 k(仿射密碼、維熱納密碼)
    • 結合現代加密(AES、RSA)實現混合加密體系

總結

本文提供了簡潔、健壯、可擴展的凱撒密碼 Java 實現。通過模運算優雅處理邊界,正則驗證輸入,代碼結構清晰,適合初學者理解對稱加密基本原理與字符串處理技巧。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved