当前位置 博文首页 > 蜗牛为梦想而生H:凯撒密码 | 加密解密

    蜗牛为梦想而生H:凯撒密码 | 加密解密

    作者:[db:作者] 时间:2021-09-07 19:09

    /**
     * @className: KaiSaCipher
     * @description: 凯撒密码加密解密
     **/
    @Component
    public class KaiSaCipher {
        public static void main(String[] args) {
            String str = "0hZEAMMTkyLjE2Ny4xMy41";
    
            KaiSaCipher kaiSaCipher = new KaiSaCipher();
            String encryption = kaiSaCipher.encryption(str);
            String decrypt = kaiSaCipher.decrypt(encryption);
    
            System.out.println("明文: " + str);
            System.out.println("密文: " + encryption);
            System.out.println("解密后: " + decrypt);
        }
    
        /**
         * 加密字符串
         */
        public String encryption(String str) {
            //生成区间随机数,偏移量
            int k = RandomUtil.randomInt(0, 9);
            String string = "";
            //base64加密
            string = Base64Util.encode(xun(str, string, k));
            return k + string;
        }
    
        /**
         * 解密字符串
         */
        public String decrypt(String str) {
            int n = Integer.parseInt(str.substring(0, 1));
            str = Base64Util.decode(str.substring(1));
            int k = -n;
            String string = "";
            return xun(str, string, k);
        }
    
        /**
         * 移位算法
         */
        private String xun(String str, String string, int k) {
            StringBuilder stringBuilder = new StringBuilder(string);
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c >= 'a' && c <= 'z')//如果字符串中的某个字符是小写字母
                {
                    c += k % 26;//移动key%26位
                    if (c < 'a')
                        c += 26;//向左超界
                    if (c > 'z')
                        c -= 26;//向右超界
                } else if (c >= 'A' && c <= 'Z')//如果字符串中的某个字符是大写字母
                {
                    c += k % 26;//移动key%26位
                    if (c < 'A')
                        c += 26;//向左超界
                    if (c > 'Z')
                        c -= 26;//向右超界
                } else if (c >= '0' && c <= '9')//字符串中数字
                {
                    c += k % 10;//移动key%26位
                    if (c < '0')
                        c += 10;//向左超界
                    if (c > '9')
                        c -= 10;//向右超界
                }
                stringBuilder.append(c);//将解密后的字符连成字符串
            }
            string = stringBuilder.toString();
            return string;
        }
    }
    
    RandomUtil,Base64Util为Hutool工具类, Hutool是一个小而全的Java工具类库Hutool工具类
    
    cs
    下一篇:没有了