Julius Caesar发明的较早的加密术,举个例子:
明文: meet me after the toga party
密文: PHHW PH DIWHU WKH WRJD SDUWB
其实就是讲每个字母往后移3位, 如: a->d, e->h;对于最后的三个字母采取循环模式,xyz->abc.
那么可以得到加密公式为:
C = E(3,p)=(p+3)%26
注:
E-> encode 加密
p:明文字母
C:密文
% : 取膜
对应的解密算法:
p = D(C-3+26)%26
注:在解密算法中为什么需要加上26, 请看下面的实现代码:
1 public class Caesar { 2 public static final int KEY = 3; 3 private static int charToInt(char c){ 4 return (int)c - 97; 5 } 6 public static String encode(String input){ 7 char[] chars = input.toLowerCase(Locale.ENGLISH).toCharArray(); 8 char[] outputChars = new char[chars.length]; 9 for(int i = 0 ; i < chars.length; i++){10 int charInt = (int)chars[i];11 if (charInt < 97 || charInt > 122){12 outputChars[i] = chars[i];13 }else {14 outputChars[i] = (char) ((charToInt(chars[i]) + KEY) % 26 + 97);15 }16 }17 return new String(outputChars);18 }19 public static String decode(String input, int key){20 char[] chars = input.toCharArray();21 char[] outputs = new char[chars.length];22 for(int i = 0 ; i < chars.length ; i++){23 int value = (int)chars[i] - 97;24 if (value < 0 || value > 25){25 outputs[i] = chars[i];26 }else {27 outputs[i] = (char)((value - key + 26)%26 + 97);//如果不加26,value-key 可能为负数。28 }29 }30 return new String(outputs);31 }32 public static String[] decode(String input){33 String decode;34 String[] encodes = new String[25];35 for(int i = 1 ; i < 26; i++){36 decode = Caesar.decode(input,i);37 System.out.println("key = "+i + ", the decode string is :" +decode);38 encodes[i-1] = decode;39 }40 return encodes;41 }42 public static void main(String[] args){43 String input = "I am Jerry.";44 String encode = Caesar.encode(input);45 System.out.println(encode);46 String[] decode = Caesar.decode(encode);47 }48 }
这就是最简单的Caesar加密,在后面的章节里面,我们在慢慢加强。
-Jerry(wellmaxwang)