1

I have been trying for couple of days and simply can't make it work. If I have a private and public key pair. I am just trying to encrypt a message using public key and then decrypt using private key. My code looks something like this:

    String message = "Secure Message";
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    Key privateKey = keyPair.getPrivate();
    Key publicKey = keyPair.getPublic();

    Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] encryptData = cipher.doFinal(message.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] decryptData = cipher.doFinal(encryptData);

    System.out.println(encryptData.toString());
    System.out.println(decryptData.toString());

But it doesn't seem to be working. Output I get is something like this:

    [B@4e33967b
    [B@1cdc8d59
2
  • 2
    Try Arrays.toString(encryptData);. Commented Jul 18, 2014 at 20:54
  • If someone may be interested, this is how I converted my encrypted byte arrays to String and then back to bytes. String encodedString = new String(Base64.encodeBase64(encryptData)); byte[] decodedBytes = Base64.decodeBase64(encodedString); Commented Jul 18, 2014 at 21:38

1 Answer 1

1

Two very minor issues with your code,

 // System.out.println(encryptData.toString());
 // System.out.println(decryptData.toString());

 System.out.println(Arrays.toString(encryptData));
 System.out.println(new String(decryptData));
  1. The encrypted string is in binary. So you probably would not enjoy seeing it directly mapped to ASCII. It looks like garbage.
  2. Java arrays do not override Object.toString(), so you are getting Object.toString() and that is basically the hashCode() and essentially a reference address.
  3. My second println() above outputs the expected "Secure Message" here.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.