1

我有一个 java 应用程序,您可以在其中输入一个字符串到一个文本框中,点击加密,它会在一个单独的文本框中显示加密的字符串。我将为此使用 AES 加密。问题是我无法让加密文本显示为字节,但文本框不会显示字节(只需要字符串)。下面是我的代码的一个尝试。

 public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}

private class HandleThat implements ActionListener{
 public void actionPerformed(ActionEvent eve){
 JTextField jtf; //user will enter string here
 JTextField jtf1; //this will show the encrypted text
 plaintext = jtf.getText();
 String error = "Error, you must provide some text"; 
        if(eve.getActionCommand().equals("Encrypt")){
            if(!jtf.getText().equals("")){
             try{   
             byte[] cipher = encrypt(plaintext, encryptionKey);
             for (int i=0; i<cipher.length; i++)

             jtf1.setText(cipher[i]); //here is where I get my error
            } catch (Exception e) {
            e.printStackTrace();}
        }else{
                label.setText(error);
        }
        }

错误 - “类 JTextComponent 中的方法 setText 不能应用于给定类型;必需:找到字符串:字节原因:无法通过方法调用转换将实际参数字节转换为字符串”

如何将密码从字节更改为字符串?

4

3 回答 3

2

如果要漂亮地打印值数组,请byte使用:

Arrays.toString(cipher)

如果您希望将密码解释为String,请使用:

new String(cipher)

于 2013-03-12T20:30:48.217 回答
1

这不是 API 内置的,因为通常密文包含不可打印的字符。您可能希望将加密文本编码为Base-64,特别是如果用户计划对其进行处理(例如通过电子邮件发送)。这将确保所有字符都是可打印的。

于 2013-03-12T21:23:13.590 回答
1

显示字节和字节数组的典型格式是十六进制显示。例如,许多加密应用程序以十六进制格式显示密钥。

您可以使用此 SO 答案中显示的方法转换byte[]String十六进制格式。

于 2013-03-12T20:42:59.547 回答