首页 > 解决方案 > 如何从 JTextfield 中取回解密的字符串

问题描述

我已经在 J​​ava 中实现了 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并且加密失败。

标签: javastringswingrsajtextfield

解决方案


推荐阅读