恺撒密码Java 实现
恺撒密码Java 实现
前言
下图摘取《犯罪大师》谜题关卡
一、Java实现
代码如下(示例):
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 ONE = 1;
/*
* TODO 程序主体
* dense 加密解密标识 0:加密 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));
}
}
加密和解密:
二、Python实现
伪代码如下(示例):
# 恺撒密码表
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")
ZERO = 0
ONE = 1
def mainBodyOfTheProgram(value, key, dense):
list = []
if value == None:
return
for f in value:
for index, value in enumerate(objeStrings):
if f == value:
list.append(index)
result = ""
fatherKey = 0
for f in list:
if dense == ZERO:
fatherKey = f + key
if dense == ONE:
if f <= key:
fatherKey = abs((f - key) + len(objeStrings))
else:
fatherKey = f - key
if fatherKey >= len(objeStrings):
result += objeStrings[abs((fatherKey) - len(objeStrings))]
continue
result += objeStrings[abs(fatherKey)]
return result
if __name__ == "__main__":
print("恺撒密码加密:%s " % mainBodyOfTheProgram("LOVE", 10, 0))
# result = mainBodyOfTheProgram("LOVE", 2, 0)
print("恺撒密码解密:%s " % mainBodyOfTheProgram(mainBodyOfTheProgram("LOVE", 10, 0), 10, 1))
加密和解密:
总结
学习记录