package VJNY.yuanma;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class VJNY extends JFrame{
public void init(){
JFrame f = new JFrame("维吉尼亚密码");
JPanel p = new JPanel();
JLabel jl1 = new JLabel("明文:");
JLabel jl2 = new JLabel("密钥:");
JLabel jl3 = new JLabel("密文:");
final JTextField jtf1 = new JTextField(30);
final JTextField jtf2 = new JTextField(30);
final JTextField jtf3 = new JTextField(30);
JButton jb = new JButton("确认");
Box b1 = Box.createHorizontalBox();
Box b2 = Box.createHorizontalBox();
Box b3 = Box.createHorizontalBox();
Box b4 = Box.createHorizontalBox();
b1.add(jl1);
b1.add(jtf1);
b2.add(jl2);
b2.add(jtf2);
b3.add(jl3);
b3.add(jtf3);
b4.add(jb);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.setLayout(new FlowLayout());
f.setBounds(400, 400, 400, 400);
f.add(p);
f.setVisible(true);
f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int[][] vj = createVJNY();
//先去除明文中的空格,保存在testStr中
String testStr1 = change(jtf1.getText());
//先去除明文中的空格,保存在testStr中
String testStr2 = change(jtf2.getText());
//获取明文文本,去除中间空格,并将其分割为字符数组
char[] temp1 = testStr1.toCharArray();
//获取密钥文本,对比明文长度,并去除中间空格
char[] temp2 = compare(testStr1, testStr2).toCharArray();
String str = "";
int t1 = 0,t2 = 0;
for(int i = 0 ;i<temp1.length;i++){
for(int j = 0 ;j<temp2.length;j++){
//记录行的ASCLL码
t1 = (int)temp1[i]-97;
//记录列的ASCLL码
t2 = (int)temp2[i]-97;
}
str += (char)vj[t1][t2]+"";
}
jtf3.setText(str);
for(int i = 0;i<temp2.length;i++){
System.out.print(temp2[i]+"");
}
System.out.println();
System.out.println(testStr1);
}
});
}
//去除字符串中间空格
public static String change(String s){
String[] str=s.split(" ");
String temp = "";
for(String i : str){
temp+=i;
}
return temp;
}
//对比字符串长度,s1为明文,s2为密钥
public static String compare(String s1,String s2){
if(s1.length()<s2.length()){
s2+=s2.substring( 0,s1.length());
}
else{
for(int i = 0;i<s1.length()/s2.length();i++){
s2 += s2;
}
s2+=s2.substring(0, s1.length()%s2.length());
}
return s2;
}
//建立维吉尼亚矩阵
public int[][] createVJNY(){
int[][] vj = new int[26][26];
vj[0][0]=0;
for(int i = 0 ; i < 26 ;i++){
for(int j = 0 ; j < 26;j++){
vj[i][j]=i+j+65;
if(vj[i][j]>90){
vj[i][j] = (j+i+65-26);
}
else{
vj[i][j] = j+i+65;
}
//System.out.print(vj[i][j]+" ");
}
System.out.println();
}
return vj;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
VJNY vjny = new VJNY();
vjny.init();
}
}
中间的代码实现步骤都已用注释写出,如果有其他方法,也可评论大家一起讨论。