加密java caesar密码
我用java编写了caesar密码,但在用户输入密钥后,它不会加密任何东西
这是我的密码
public class CaesarCipher
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText, int shiftKey)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText, int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0)
{
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
System.out.println(encrypt(message, 3));
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}
运行:
Enter The Plain Text:
Reem LA
Enter The Key:
2
The Cipher Text
# 1 楼答案
# 2 楼答案
这可能是最简单的方法,也是最容易理解的方法:
# 3 楼答案
试试这个:
这将适用于所有按字母顺序排列的字符串。。。但根据您的程序,这会将原始消息转换为小写。所以这不是纯粹的加密,因为您的程序不区分大小写
如果您希望您的程序区分大小写,以下是程序:
希望这能提供一些想法。祝你一切顺利
# 4 楼答案
使用
indexOf
不是很有效。。。您可以对char
值进行整数运算以获得它们的索引我在代码中加入了注释来解释更多内容,但这就是我想到的
输出应该类似于