密鑰字密碼

密鑰字密碼技術:


利用一個密鑰字來構造替換作爲密鑰,先將密鑰字作爲首段密文,
然後將之後未在字母表中出現過的字母依次寫在此密鑰字之後,構造出一個字母替換表
當密文爲英文單詞時,最多可以有26!個不同的替換表(包括恆等變換)

如,當密鑰字爲cipher時,
明文字母  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
數組下標  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25


密文字母  c i   p  h e  r   a  b  d   f  g   j   k    l   m  n  o   q    s   t   u   v  w   x   y   z
數組下標  2 8 15 7 4 17  0  1  3   5  6  9  10 11 12 13 14 16 18 19 20 21 22 23 24 25


完整測試例子如下:


import java.util.ArrayList;
import java.util.Scanner;


public class 密鑰字密碼技術 {
public static String createTable(String cipher,char[] CharArrays){
StringBuffer tableBuffer=new StringBuffer(cipher);
for (int i = 0; i < CharArrays.length; i++) {
if(cipher.indexOf(CharArrays[i])==-1)
tableBuffer.append(CharArrays[i]);
}
return tableBuffer.toString();
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("第一行輸入密碼錶總數n\n"
+ "第二行輸入各明文字符\n"
+ "第三行輸入密鑰字\n"
+ "第四行輸入待加密明文");
int n=scan.nextInt();
char CharArrays[]=new char[n];
CharArrays=scan.next().toCharArray();
String cipher=scan.next();
scan.nextLine();
String normalStr=scan.nextLine();
String SecretTable=createTable(cipher, CharArrays);
String splitStrs[]=normalStr.split(" ");

ArrayList<Character> templist=new ArrayList<>();
System.out.println("加密後如下:");

for (int i = 0; i < splitStrs.length; i++) {
char normalChars[]=splitStrs[i].toCharArray();
for (int j = 0; j < normalChars.length; j++) {
normalChars[j]=SecretTable.charAt(j);//加密
System.out.print(normalChars[j]);
normalChars[j]=CharArrays[j];//解密
templist.add(normalChars[j]);
}
System.out.print(" ");
templist.add(' ');
}
System.out.println("\n解密後如下:");
for(Character o:templist){
System.out.print(o);
}
}
}
運行結果如下:


第一行輸入密碼錶總數n
第二行輸入各明文字符
第三行輸入密鑰字
第四行輸入待加密明文
26
abcdefghijklmnopqrstuvwxyz
cipher
abcdefghijklmnopqrstuvwxyz
加密後如下:
cipherabdfgjklmnoqstuvwxyz 
解密後如下:
abcdefghijklmnopqrstuvwxyz 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章