📄 transpositioncipher.java
字号:
Appendix 1: Java source code for TranspositionCipher.java
/*
Wrtten by: H Yu
First written:05/11/07
Last modified:09/11/07
*/
import sheffield.*;
public class TranspositionCipher{
public static void main(String[] args){
EasyReader keyboard=new EasyReader();
EasyReader inputfiles=new EasyReader("plain.txt");
EasyWriter screen=new EasyWriter();
int lc,lp,lk;
String plaintext=new String();
//input cipherkey from the keyboard and put the letters into an array
String cipherkey=keyboard.readString("Please input the cipherkey: ");
lk=cipherkey.length();
String[] k=new String[lk];
for(int i=0;i<lk;i++) {
String ck= cipherkey.substring(i, i+1);
k[i]=ck;
}
//check if the cipher key is legal
boolean illegal=false;
for(int i=0;i<lk-1;i++){
for(int j=i+1;j<lk;j++){
boolean eq=k[i].equals(k[j]);
if(eq){
screen.println("The key should't be repeated!");
illegal=true;
}
}
}
if(!illegal){
//readin plaintext from the plain.txt
while(!inputfiles.eof()){
plaintext+=inputfiles.readString().trim()+' ';
}
plaintext=plaintext.trim()+' ';
//display the plaintext
screen.println();
screen.println("The plaintext is: ");
screen.println(plaintext);
//creat the matrix of the plaintext as the order of cipher key
lp= plaintext.length();
if(lp%lk==0)
lc=lp/lk;
else
lc=lp/lk+1;
String[][] s=new String[lk][lc];
String[] temp=new String[lc];
String tempk;
for(int i=0;i<lp;i++) {
String cp= plaintext.substring(i, i+1);
int r=i%lk,c=i/lk;
s[r][c]=cp;
}
//add random letters
int ln=lp%lk;
for(int i=ln;i<lk;i++){
double a=Math.random();
a=a*100%26+97;
s[i][lc-1]=s[i][lc-1].valueOf((char)a);
}
//display the matrix of the plaintext
screen.println();
screen.println("The matrix of the plaintext is:");
for(int j=0;j<lc;j++){
for(int t=0;t<lk;t++){
screen.print("\t"+" "+s[t][j]);
}
screen.println();
}
screen.println();
//reorder the cipher key and plaintext alphabetically
for(int i=0;i<lk-1;i++){
for(int j=i+1;j<lk;j++){
int comp=k[i].compareTo(k[j]);
if(comp>0){
tempk=k[i];
k[i]=k[j];
k[j]=tempk;
for(int t=0;t<lc;t++){
temp[t]=s[i][t];
s[i][t]=s[j][t];
s[j][t]=temp[t];
}
}
}
}
//display the the cipher key alphabetically and the ciphertext
screen.println("The ordered matrix with the key is:");
for(int t=0;t<lk;t++){
screen.print("\t"+" "+k[t]);
}
screen.println();
int number=1;
for(int t=0;t<lk;t++){
screen.print("\t"+"("+number+")");
number++;
}
screen.println();
for(int j=0;j<lc;j++){
for(int t=0;t<lk;t++){
screen.print("\t"+" "+s[t][j]);
}
screen.println();
}
//display the cipher text to the screen in upper case
screen.println();
screen.println("The cipher text is: ");
for(int t=0;t<lk;t++){
for(int j=0;j<lc;j++){
screen.print(s[t][j].toUpperCase());
}
}
screen.println();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -