Muhannad
Muhannad

Reputation: 455

from string to byte array and then to string

I'm trying to simulate the RSA encryption and decryption I want the encryption method to

  1. Take the string
  2. convert it into byte []
  3. do the RSA function (as I will show in the following code)
  4. return the byte [] as a string

what I have now and it works but with receiving and returning byte [] (not string)

   public byte[] encrypt (byte[] message){

   byte [] t= ((new BigInteger(message)).modPow(e, N)).toByteArray();

  return (t);

}

the decrypt method I want it to

  1. receive the returned String from encrypt()
  2. convert it into byte[]
  3. do the RSA on the byte[] to get the original byte []
  4. return the original string what I have up until now

        public byte [] decrypt (byte [] message) {
    
         byte[] data= ((new BigInteger(message)).modPow(d, N)).toByteArray();
    
         return data;
          }
    

these 2 methods work, but I need to create a byte [] in my main class and use byte[]Str.getbyte() to encrypt and new String(byte []) to encrypt .....

I want my main to deal with only strings. When I use such a decrypt(String message) code

    public String decrypt (String message) {

       byte[] data= ((new BigInteger(message.getBytes())).modPow(d, N)).toByteArray();

    return data.toString();
    } 

it doesn't give me the original text as it does with decrypt(byte [] message), but it returns something like B@79f0a8b

I'm sure I'm missing something related to converting the text into byte[] and vice versa, but I'm not sure what am I missing.

I would love to hear from you.

(sorry for my English)

Upvotes: 1

Views: 518

Answers (1)

Pavlo K.
Pavlo K.

Reputation: 371

What the reason of string values for encrypted result? You can easy convert byte[] to String and reverse it if you try to search: byte[] to String java. But is there real reason to do it?

Maybe you want something like:

public byte[] encrypt (String message);
public String decrypt (byte[] message);

Then you will manipulate with string input and will be able to get string decrypt result. But there is no reason to manipulate with encrypted data in strings, it looks like redundant operation: your string will be unreadable and algorithm work with byte[]. Just convert encrypt input and decrypt output.

Upvotes: 1

Related Questions