欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java密码之凯撒加密

程序员文章站 2024-03-16 18:20:04
...

java-凯撒加密

package com.sgg.Kaiser;

public class KaiserDemo {

    public static void main(String[] args) {
        //定义原文
        String input = "Hello World!";
        //原文右移3位
        int key = 3;
        //抽取快捷键:ctrl alt m
        String s = encryptKaiser(input,key);
        System.out.println("加密 = " + s);
        String s1 = decryptKaiser(s, key);
        System.out.println("明文 = " + s1);

    }

    /**
     *解密
     * @param s 密文
     * @param key **
     * @return
     */
    private static String decryptKaiser(String s, int key) {
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            int b = aChar;
            //偏移数据
            b -= key;
            char newb = (char) b;
            sb.append(newb);
        }
        return sb.toString();
    }

    /**
     * 解密
     * @param input 原文
     * @return
     */
    private static String encryptKaiser(String input,int key) {
        //把字符串变成字节数组
        char[] chars =  input.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            int b = aChar;
            //往右移动3位
            b = b + key;
            char newb = (char) b;
            sb.append(newb);
        }
        //System.out.println("密文==" + sb.toString());
        return sb.toString();
    }
}