简体   繁体   中英

Why does RSA produce different results with same key and message?

I will post my code. Sorry for the confusion.

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());
} ...

That's the code in an action on a button. Everytime that I run this code, with the same keys, texto1 on encryption returns a different result like [B@52a0b1e1 or [B@3e55abb3

The toString() method of arrays in Java doesn't display the content of the array. Instead, it shows the component type and an identifier based on the location of the array in memory.

If you want to see the content of the array, you have to iterate over its elements. And, in this case, you'll have to decide how you want to encode the byte elements to text. It looks like you are trying to do this with your variable teste , but I'd recommend something like this:

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

This will generate a hexadecimal representation of your ciphertext. You can't create a String from random 8-bit values as you attempt with the variable texto , because the bytes will generally not form valid UTF-8 encoding sequences. You'll end up with a lot of replacement characters in the text ( ).

With a hex (or base-64) encoding, you will see that the cipher text still varies randomly. That's because RSA's PKCS #1 padding schemes uses random data to pad the message before encryption. This deliberate feature of RSA prevents an attacker from recognizing when the same message is being sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM