public class Cryptogram {
//定义密码字库
private static final char[] code={'1','2','3','4','5',
'A','B','C','D','E',
'U','V','W','X','Y',
'Z','a','b','c','d',
'e','6','7','8','9',
'0','f','g','h','i',
'j','k','l','m','n',
'o','K','_','@','#',
'$','L','M','N','O',
'P','Q','R','S','T',
'p','q','r','s','t',
'u','v','w','x','y',
'z','F','G','H','I',
'J'};
//密钥
private static final int key=5;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] in={'e','3','w','7','p'};
char[] encryptcode=Cryptogram.encrypt(in);
System.out.print("encryptcode-----");
for(int i=0;i<encryptcode.length;i++)
System.out.print(encryptcode[i]);
System.out.println();
char[] decryptcode=Cryptogram.decrypt(encryptcode);
System.out.print("decryptcode-----");
for(int i=0;i<decryptcode.length;i++)
System.out.print(decryptcode[i]);
}
//加密算法
public static char[] encrypt(char[] data)
{
char[] tmp=new char[data.length];
for(int i=0;i<data.length;i++)
{
int k=Cryptogram.getIndex(data[i]);
int index=k+key;
if(index<code.length)
{
tmp[i]= code[index];
}
else
{
index=index-code.length;
tmp[i]= code[index];
}
}
return tmp;
}
private static int getIndex(char data)
{
for(int i=0;i<code.length;i++)
if(data==code[i])
return i;
return -1;
}
//解密算法
public static char[] decrypt(char[] data)
{
char[] tmp=new char[data.length];
for(int i=0;i<data.length;i++)
{
int k=Cryptogram.getIndex(data[i]);
int index=k-key;
if(index<0)
{
index=code.length+index;
tmp[i]=code[index];
}
else
{
tmp[i]=code[index];
}
}
return tmp;
}
}
java 加密解密算法
最新推荐文章于 2024-07-20 13:53:15 发布