凯撒密码(Java)

事实上就是把每个字母偏移一下而已,并且字符不限于a-zA-z,可以是别的,那就很显而易见了,代码如下:
定义一个Caesar密码类,成员变量只有密钥,也就是偏移量key

代码如下:

public class CaesarCrypto {

    private int key;
    
    public CaesarCrypto(int key) {
        // TODO Auto-generated constructor stub
        this.key = key;
    }
    
    public String getCipher(String plain) {
        char[] cipherChars = plain.toCharArray();
        for (int i = 0; i < cipherChars.length; i++) {
            cipherChars[i] = (char) (cipherChars[i] + this.key);
        }
        return new String(cipherChars);
    }
    
    public String getPlain(String cipher) {
        char[] cipherChars = cipher.toCharArray();
        for (int i = 0; i < cipherChars.length; i++) {
            cipherChars[i] = (char) (cipherChars[i] - this.key);
        }
        return new String(cipherChars);
    }
    
    public static void main(String[] args) {
        String text = "Java is the best language in the world!";
        System.out.println("明文:" + text);
        CaesarCrypto cc = new CaesarCrypto(4);
        String cipher = cc.getCipher(text);
        System.out.println("密文:" + cipher);
        System.out.println("解密" + cc.getPlain(cipher));
        
    }

}

结果如下:

明文:Java is the best language in the world!
密文:Neze$mw$xli$fiwx$perkyeki$mr$xli${svph%
解密Java is the best language in the world!
原文地址:https://www.cnblogs.com/zhaoke271828/p/13949951.html