Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA Hello World Program... why isn't it working

I'm trying to understand RSA in java - but I can't figure out why this code doesn't print "Hello, World" I'm trying to make sure I understand correctly by generating a keypair, encrypting "Hello World" and decrypting it. I'm having a devil of a time figuring out what I'm doing wrong

import java.security.*;
import java.math.BigInteger;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.crypto.Cipher;

public class testrsa
{
 public static void main(String [] args)
 {
   try
   {
     byte[] cipherData, plainData;
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(4096);
     KeyPair kp = kpg.genKeyPair();
     Key publicKey = kp.getPublic();
     Key privateKey = kp.getPrivate();

      Cipher cipher1 = Cipher.getInstance("RSA");
      cipher1.init(Cipher.ENCRYPT_MODE, publicKey);
      cipherData = cipher1.doFinal("Hello, Word".getBytes());

      Cipher cipher2 = Cipher.getInstance("RSA");
      cipher2.init(Cipher.DECRYPT_MODE, privateKey);
      plainData = cipher2.doFinal(cipherData);

     System.out.print(plainData.toString());

     }
     catch(Exception ex)
     {
        System.out.print(ex.toString());
     }

 }
}
like image 564
Christopher Barnes Avatar asked Apr 22 '26 21:04

Christopher Barnes


1 Answers

Change

System.out.print(plainData.toString());

To

System.out.print(new String(plainData));

And you win!

Explanation

plainData, the return of doFinal is a byte[]. What you saw when you used the toString() method (something like [B@75589559) wasn't corrupted decryption, but how Java implements byte[]'s toString() method.

In the code I suggested, you're creating a new string with the bytes you're providing -- and this does what you had wanted.

like image 114
jedwards Avatar answered Apr 24 '26 12:04

jedwards



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!