一、前言
凯撒密码,最早是由古罗马将军凯撒发明,用于军队中传递信息,是一种位移加密的密文算法。由于英文是26个字母,所以最多解密出现25种情况,用程序来讲还是很少的例举,比较简单。所以用代码实践,实现凯撒密码的加解密,简单破译凯撒密码
二、逻辑实现
private final static String codeRefer="ABCDEFGHIJKLMNOPQRSTUVWXYZ";//对照码/*** 凯撒密码加密解密* @param text 文本* @param offset 偏移量*/public static String KSMMEncryptionDecrypt(String text,int offset) {String result="";for(int i=0; i<text.length(); i++) {String code=text.substring(i,i+1);int index=codeRefer.indexOf(code);if(index!=-1){result+=KSMMDecryptToCode(index,offset);}else {result+=code;}}return result;}/*** 凯撒密码解密* @param ciphertext 密文*/public static List KSMMDecrypt(String ciphertext) {List resultList=new ArrayList<>();for(int j=1; j<codeRefer.length(); j++) {String result="";for(int i=0; i<ciphertext.length(); i++) {String code=ciphertext.substring(i,i+1);int index=codeRefer.indexOf(code);if(index!=-1){result+=KSMMDecryptToCode(index,j);}else {result+=code;}}resultList.add(result);}return resultList;}/*** 凯撒密码单个字符解密* @param index 字符下标* @param offset 偏移量* @return*/public static String KSMMDecryptToCode(int index,int offset) {String code="";index+=offset;if(index>=codeRefer.length()) {index%=codeRefer.length();}code=codeRefer.substring(index, index+1);return code;}
三、程序运行
public static void main(String[] args) throws Exception {// TODO Auto-generated method stubString text="我想说:what are you doing!";String ciphertext=KSMMEncryptionDecrypt(text.toUpperCase(),23);System.out.println("---密文:"+ciphertext);List<String> list=KSMMDecrypt(ciphertext.toUpperCase());for(String str:list) {System.out.println("---:"+str.toLowerCase());}}
ok,终了