直接上代码了.
[code="java"]import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
JTextField text1, text2, text3;
JButton btn1, btn2;
String key = "fantistic";
Main() {
//Initialize
super("Encrypt");
this.setSize(450, 490);
this.setLayout(new GridLayout());
text1 = new JTextField(16);
text2 = new JTextField();
text3 = new JTextField();
text3.setEditable(false);
btn1 = new JButton("Encrypt");
btn2 = new JButton("Decrypt");
//Layout
Box baseBox, boxV1, boxV2;
boxV1 = Box.createVerticalBox();
boxV1.add(btn1);
boxV1.add(Box.createVerticalStrut(8));
boxV1.add(btn2);
boxV1.add(Box.createVerticalStrut(16));
boxV2 = Box.createVerticalBox();
boxV2.add(Box.createVerticalStrut(4));
boxV2.add(text1);
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(text2);
boxV2.add(Box.createVerticalStrut(8));
boxV2.add(text3);
baseBox = Box.createHorizontalBox();
baseBox.add(boxV1);
baseBox.add(Box.createHorizontalStrut(10));
baseBox.add(boxV2);
setLayout(new FlowLayout());
add(baseBox);
validate();
setBounds(120, 125, 300, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//Event
btn1.addActionListener(new encrypt());
btn2.addActionListener(new decrypt());
}
private class encrypt implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = text1.getText();
char[] chr = new char[str.length()];
int len = chr.length;
StringBuffer bstr = new StringBuffer(str);
for (int i = 0; i < str.length(); i++) {
int q = (key.charAt(i % key.length()) >> (i % 32)) | (key.charAt(i % key.length()) << (32 - (i % 32)));
bstr.setCharAt(i, (char) (str.charAt(i) ^ q));
}
for (int i = 0; i < len; i++) {
chr[i] = bstr.charAt(len - 1 - i);
}
text3.setText(String.valueOf(chr));
}
}
private class decrypt implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = text2.getText();
char[] chr = new char[str.length()];
int len = chr.length;
StringBuffer bstr = new StringBuffer(str);
for (int i = 0; i < str.length(); i++) {
//左
int q = (key.charAt(i % key.length()) << (i % 32)) | (key.charAt(i % key.length()) >> (32 - (i % 32)));
bstr.setCharAt(i, (char) (str.charAt(i) ^ q));
}
for (int i = 0; i < len; i++) {
chr[i] = bstr.charAt(len - 1 - i);
}
text3.setText(String.valueOf(chr));
}
}
public static void main(String[] args) {
new Main();
}
}[/code]
[b]问题补充:[/b]
To 1 yayg,
请多输入几个字符.
.解密不回来...而且貌似加密时丢失字符...
[b]问题补充:[/b]
To wocsok,
那个顺序确实是有问题...
还有key.charAt移位也有问题.char 2byte.16位...都改成16还是无法解密..
[b]问题补充:[/b]
已经解决了。。不能用int q
用char就对 了。。