愷撒密碼Java/Python實現

專注的阿熊發表於2021-07-26

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));

     }

}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2783383/,如需轉載,請註明出處,否則將追究法律責任。

相關文章