恺撒密码Java/Python实现

package com.hjc.demo.logic.caesarpassword;

import java.util.Arrays;

import java.util.Objects;

/**

  * @Classname CaesarPassword

  * @Description TODO

  * @Date 2021/7/23 14:09

  * @Created by Mr.He

  * TODO 恺撒密码

  */

public class CaesarPassword {

     /* 恺撒密码表 */

     final String[] objeStrings = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

     final int ZERO = 0;

     final int >

     /*

      * TODO 程序主体

      *  dense 加密解密标识    0 :外汇跟单gendan5.com加密 1 :解密

      *  value 密文

      *  key 密匙

      */

     public String mainBodyOfTheProgram(String value, int key, int dense) {

         if (value == null) {

             return null;

         }

         int[] ints = new int[value.length()];

         for (int i = 0; i < value.length(); i++) {

             char c = value.charAt(i);

             ints[i] = elementIndex(objeStrings, String.valueOf(c));

         }

         int fatherKey = 0;

         String result = "";

         for (int i : ints) {

             if (Objects.equals(dense, ZERO)) {

                 fatherKey = i + key;

             }

             if (Objects.equals(dense, ONE)) {

                 if (i <= key) {

                     fatherKey = Math.abs((i - key) + objeStrings.length);

                 } else {

                     fatherKey = i - key;

                 }

             }

             if (fatherKey >= objeStrings.length) {

                 result += objeStrings[Math.abs((fatherKey) - objeStrings.length)];

                 continue;

             }

             result += objeStrings[Math.abs((fatherKey))];

         }

         return result;

     }

     /*

      * TODO 获取下标

      * */

     public int elementIndex(String[] ints, String value) {

         for (int i = 0; i < ints.length; i++) {

             if (Objects.equals(ints[i], value)) {

                 return i;

             }

         }

         return -1;

     }

     public static void main(String[] args) {

         CaesarPassword caesarPassword = new CaesarPassword();//NQXG

         System.out.println(" 恺撒密码加密 " + caesarPassword.mainBodyOfTheProgram("LOVE", 2, 0));

         System.out.println(" 恺撒密码解密 " + caesarPassword.mainBodyOfTheProgram(caesarPassword.mainBodyOfTheProgram("LOVE", 2, 0), 2, 1));

     }

}


请使用浏览器的分享功能分享到微信等