为什么RSA使用相同的密钥和消息产生不同的结果?

Joã*_*ade 2 java arrays encryption rsa character-encoding

我会发布我的代码.对困惑感到抱歉.

StringBuilder texto1 = new StringBuilder("LALALLA");
byte[] x = texto1.toString().getBytes();
try {
  Cipher cifrado = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  cifrado.init(Cipher.ENCRYPT_MODE, key1.getPublic());
  x = cifrado.doFinal(x);
  String texto;
  texto = new String(x, "UTF-8");
  JOptionPane.showInputDialog(publicKey.toString());
  String teste = "";
  for (int i = 0; i < x.length; i++) {
    teste += x[i];
  }
  jTextPane1.setText(teste);
  //cifrado.init(Cipher.DECRYPT_MODE, privatekey);
  byte[] y;
  // x= texto.getBytes();
  //y = cifrado.doFinal(texto.getBytes());
  //texto = new String(y,"UTF-8");
  jTextPane2.setText(x.toString());
} ...
Run Code Online (Sandbox Code Playgroud)

这是按钮操作中的代码.每次运行此代码时,使用相同的密钥,texto1 on encryption会返回不同的结果,如[B@52a0b1e1[B@3e55abb3

eri*_*son 6

所述toString()阵列的在Java方法不显示阵列的内容.相反,它显示组件类型和基于阵列在内存中的位置的标识符.

如果要查看数组的内容,则必须迭代其元素.而且,在这种情况下,您必须决定如何将字节元素编码为文本.看起来你正试图用变量做这个teste,但我推荐这样的东西:

StringBuilder buf = new StringBuilder();
for (byte b : x) 
  buf.append(String.format("%02X", b));
String teste = buf.toString();
Run Code Online (Sandbox Code Playgroud)

这将生成密文的十六进制表示.String在尝试使用变量时texto,无法从随机的8位值创建,因为字节通常不会形成有效的UTF-8编码序列.你最终会在文本中找到很多替换字符( ).

使用十六进制(或base-64)编码,您将看到密文仍然随机变化.这是因为RSA的PKCS#1填充方案在加密之前使用随机数据填充消息.RSA的这一故意功能可防止攻击者识别何时发送相同的消息.