【问题标题】:How to change an encrypted message back to decrypted message?如何将加密消息更改回解密消息?
【发布时间】:2021-04-21 01:40:53
【问题描述】:
这是我用来加密用户在文本框中输入的消息的代码。我想知道如何制作这样的代码,但取而代之的是,获取一条加密消息,将其插入一个新文本框中,然后将其转换为解密消息。
private void btnDecryptActionPerformed(java.awt.event.ActionEvent evt) {
String origMessage;
String encMessage = "";
char tempChar;
int tempAscii;
origMessage = txtDecrypt.getText();
for (int i = 0; i < origMessage.length(); i = i + 1) {
tempChar = origMessage.charAt(i);
tempAscii = (int) tempChar;
tempAscii = tempAscii + 3;
tempChar = (char) tempAscii;
encMessage = encMessage + tempChar;
}
if (origMessage.length() < 30) {
fTxtEncrypt.setText(encMessage);
} else {
fTxtEncrypt.setText("Must be less than 30 characters...");
}
}
【问题讨论】:
标签:
java
string
encryption
caesar-cipher
【解决方案1】:
凯撒密码将每个字符移动一定数量的字符。要解密此消息,您必须将它们向后移动相同数量的字符:
public static void main(String[] args) {
String encrypted = caesarCipher("message", 3);
String decrypted = caesarCipher(encrypted, -3);
System.out.println(encrypted); // phvvdjh
System.out.println(decrypted); // message
}
public static String caesarCipher(String source, int shift) {
StringBuilder target = new StringBuilder(source.length());
for (int i = 0; i < source.length(); i++) {
target.append((char) (source.charAt(i) + shift));
}
return target.toString();
}
【解决方案2】:
解密需要tempAscii - 3
示例:
public class Test {
public static void main(String args[]) throws Exception {
String origMessage = "Hello world";
String encMessage = encrypt(origMessage);
System.out.println("encrypt message :" + encMessage);
System.out.println("decrypt message :" + decrypt(encMessage));
}
static String decrypt(String encMessage) throws Exception {
return encryptOrDecrypt(encMessage, "decrypt");
}
static String encrypt(String encMessage) throws Exception {
return encryptOrDecrypt(encMessage, "encrypt");
}
private static String encryptOrDecrypt(String message, String type)
throws Exception {
char tempChar;
int tempAscii;
String resultMessage = "";
for (int i = 0; i < message.length(); i = i + 1) {
tempChar = message.charAt(i);
tempAscii = (int) tempChar;
if (type.equals("encrypt")) {
tempAscii = tempAscii + 3;
} else {
tempAscii = tempAscii - 3;
}
tempChar = (char) tempAscii;
resultMessage = resultMessage + tempChar;
}
if (message.length() < 30) {
return resultMessage;
} else {
throw new Exception("Must be less than 30 characters...");
}
}
}
输出:
encrypt message :Khoor#zruog
decrypt message :Hello world