gpt4 book ai didi

java - 给出了替代密码加密器代码,但没有解密器

转载 作者:行者123 更新时间:2023-11-30 08:13:09 25 4
gpt4 key购买 nike

给出加密代码

// encrypt looks up the character at the appropriate place
// in the encryption String and substitutes it.
public void encrypt (StringBuilder text)
{
for (int i=0; i<text.length(); i++)
{
char ch = text.charAt(i);
if ('A' <= ch && ch <= 'Z')
{
int index = ALPHABET.indexOf(ch);
text.setCharAt(i, encryptionString.charAt(index));
}
}
}

我如何修改上面的代码以使其解密?

public class SubstitutionCipher
{
// The alphabet as a String. We use this for both
// encoding and decoding
public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// The encryption string is how we represent the table
// of values. The first character in the String
// is substituted for 'A', the second for 'B', etc.
private String encryptionString;

/**
* Constructor for objects of class Substitution
*/
public SubstitutionCipher(String substitutionString)
{
if (substitutionString.length() != 26)
{
System.out.println ("Illegal substitution string "
+ substitutionString);
encryptionString = ALPHABET;
}
else
{
encryptionString = substitutionString;
}
}

// encrypt looks up the character at the appropriate place
// in the encryption String and substitutes it.
public void encrypt (StringBuilder text)
{
for (int i=0; i<text.length(); i++)
{
char ch = text.charAt(i);
if ('A' <= ch && ch <= 'Z')
{
int index = ALPHABET.indexOf(ch);
text.setCharAt(i, encryptionString.charAt(index));
}
}
}

// decrypt looks up the character at the appropriate place
// in the alphabet and substitutes it.
public void decrypt (StringBuilder text)
{


for (int i=0; i<text.length(); i++)
{
char ch = text.charAt(i);
if ('A' <= ch && ch <= 'Z')
{
int index = ALPHABET.indexOf(ch);
text.setCharAt(i, encryptionString.charAt(index));
}
}
}

}

最佳答案

在解密中,您必须执行加密的逆操作,但在您的代码中,您正在做同样的事情,因此将其更改为:

public void decrypt (StringBuilder text)
{
for (int i=0; i<text.length(); i++)
{
char ch = text.charAt(i);
if ('A' <= ch && ch <= 'Z')
{
int index =encryptionString.indexOf(ch);
text.setCharAt(i, ALPHABET.charAt(index));
}
}
}

关于java - 给出了替代密码加密器代码,但没有解密器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com