您的位置:首页 > 编程语言 > Java开发

Java字串加密

2015-10-24 16:00 316 查看
[b]古罗马皇帝凯撒在打仗时曾经使用过以下方法加密军事情报: [/b]
              



请编写一个程序,使用上述算法加密或解密用户输入的英文字串。

package 字串加密;

import javax.swing.JOptionPane;
public class Password {
public static void main(String args[])
{
String password;
password = JOptionPane.showInputDialog("请输入要加密或者要破解的字符串:");

String output;
output = "字符串:"+password;
char[] c = new char[password.length()];
password.getChars(0, password.length(), c,0);

//加密
for(int i=0;i<password.length();i++)
{
if(c[i]=='x')
c[i]='a';
else if(c[i]=='y')
c[i]='b';
else if(c[i]=='z')
c[i]='c';
else if (c[i] == ' ')
c[i]=c[i];
else
c[i]+=3;
}
output=new String(c);

//解密
char[] d = new char[password.length()];
password.getChars(0, password.length(), d,0);
for(int i=0;i<password.length();i++)
{
if(d[i]=='c')
d[i]='z';
else if(d[i]=='b')
d[i]='y';
else if(d[i]=='a')
d[i]='x';
else if(d[i] == ' ')
d[i]=d[i];
else
d[i]-=3;
}
String o=new String(d);

output +="\n\n解密后的字符串是:"+o;//定义输出格式

JOptionPane.showMessageDialog(
null,"加密后的字符串是:"+output,"字符串"+password,
JOptionPane.PLAIN_MESSAGE);

System.exit(0);

}
}


结果截图:







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: