我正在用 Java 制作随机替换密码。基本上,程序会要求您输入一个句子,您输入该句子,它会获取该句子并使用随机生成的字母表对其进行加密。用户可以选择加密或解密。加密后的密文随后显示在屏幕上。如果用户选择这样做,程序将解密密码并显示原始的纯文本消息。
这是我到目前为止所拥有的:
Random gen = new Random();
PrintWriter write = new PrintWriter(new File("CryptCode.txt"));
char[] chars = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
//'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] cryptList = new char[26];
int tracker = 0;
while(tracker < 26)
{
int num = gen.nextInt(26);
if(cryptList[num] == '\u0000')
{
cryptList[num] = chars[tracker];
tracker++;
}
}
for(int i = 0; i < 26; i++)
{
write.println(chars[i] + " " + cryptList[i]);
}
write.close();
这只是生成随机字母表。但我不知道如何实现实际的加密方法。我可以自己处理文件IO和给用户的提示。我只是不明白如何创建替换算法。任何帮助是极大的赞赏。一旦我有了加密方法,我可能就能找出解密方法,但到目前为止我不知道如何继续。谢谢!
最佳答案
我以前这样做过,这就是我的做法:
private static char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};
public static char[] shiftAlphabet(int shift)
{
char[] newAlpha = new char[26];
for (int i = 0; i < 26; i++)
{
if(((i + shift) < 26) && ((i + shift) >= 0))
{
newAlpha[i] = alphabet[i + shift];
}
else if ((i + shift) >= 26)
{
newAlpha[i] = alphabet[i + shift - 26];
}
}
return newAlpha;
}
public static String encrypt(String s, int shift)
{
String e = "";
for(int i = 0; i < s.length(); i++)
{
char letter = s.charAt(i);
if (letter != ' ')
{
int f = find(alphabet, letter);
if(((f + shift) < 26) && ((f + shift) >= 0))
{
letter = alphabet[f + shift];
}
else if ((f + shift) >= 26)
{
letter = alphabet[f + shift - 26];
}
e = e + String.valueOf(letter);
}
else
{
e = e + " ";
}
}
return e;
}
public static int find(char[] c, char c2)
{
int w = 0;
for(int i = 0; i < c.length; i++)
{
if(c[i] == (c2))
w = i;
}
return w;
}
第一个方法将字母表移动某个整数,第二个方法使用最后一个方法对消息进行加密,该方法查找字母在字母表中的位置(返回 0 到 25 之间的值)。因此,使用这些方法,在您的 main 方法中,您可以生成一个从 1 到 26 的随机数并将其用作“shift”变量,然后提示用户输入他/她想要加密的消息。
关于java - 随机替换密码 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22470823/