java - 如何从 JTextfield 中取回解密的字符串
问题描述
我已经在 Java 中实现了 rsa 加密和解密,它工作得很好。但我的问题是,当我将加密字符串写入 JTextField 时,我无法从 JTextField 中取回正确的值以再次解密消息。
byte[]
这是我的代码,我相信我在转换值(和字符串)时做错了:
public static byte[] encrypt(String message, PublicKey pk) {
Cipher cipher= null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] chiffrat = null;
try {
chiffrat = cipher.doFinal(message.getBytes());
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return chiffrat;
}
public static String decrypt(byte[] chiffrat, PrivateKey sk)
{
byte[] dec = null;
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, sk);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
dec = cipher.doFinal(chiffrat);
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return new String(dec);
}
在我的 Window 类中:在我的 TextField 中编写加密字符串
JButton btnEncrypt = new JButton("Plaintext -> RSA");
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtEncryptionRSA.setText(new String(rsa.encrypt(pwboxEncryptionPlain.getText(), rsa.key.getPublic())));
}
});
这写d¿Åád6×Ãö† G0|ôw;-3—?Ó^xudC\Ö>Ós`H9ÅóÛ`¥
在我的 TextField 中。
尝试解密并在另一个 TextField 中写入:
JButton btnDecrypt = new JButton("RSA -> Plaintext");
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
byte[] encryptedmsg = txtEncryptionRSA.getText().getBytes();
System.out.println(encryptedmsg);
pwboxEncryptionPlain.setText(rsaClass.decrypt(encryptedmsg, rsa.key.getPrivate()));
}
});
这会打印出来:[B@abd4af7
并且加密失败。
解决方案
推荐阅读
- android - IllegalStateException:无法显示附加到不同 FragmentManager 的 Fragment
- python - 将视频通话功能与 Django 和 Django Channels 集成
- osgi - OSGI 捆绑包版本 (Apache Felix)
- javascript - 无法在生产模式下启动 sapper 应用程序
- android - 活动之间的过渡
- azure-devops - 在远程服务器上创建目录后 Azure DevOps 管道上传到 FTP
- java - Android 中的地图视图
- file - 读取和查找之间的区别(随机访问)
- clojure - 避免输出clojure函数
- jupyter-lab - 请使用不同的工作区。此工作区已在另一个 JupyterLab 窗口中使用。请输入另一个工作区名称