密钥字密码

来源:互联网 发布:高中生搭配衣服知乎 编辑:程序博客网 时间:2024/05/28 05:19
密钥字密码技术:


利用一个密钥字来构造替换作为密钥,先将密钥字作为首段密文,
然后将之后未在字母表中出现过的字母依次写在此密钥字之后,构造出一个字母替换表
当密文为英文单词时,最多可以有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 
1 0