Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String of byte array to byte array (rsa and java)

Tags:

java

I am working on a web service, and I want to send a byte array as a String, then get the original byte array.

I explain again, my server side has the role of encrypting a message, so I have a byte array.

 Cipher cipher = Cipher.getInstance("RSA");
 cipher.init(cipher.ENCRYPT_MODE,clefPrivee);
 byte[] cipherText= cipher.doFinal(msgEnOctets);

then to send this encrypted message, I send it as a String because I am sending an entire data frame

code :

cipherText.toString();

So I have the array as a string but nothing has changed.

How can I get my original painting back?

thanks

like image 693
hunk tomas Avatar asked Aug 19 '20 14:08

hunk tomas


People also ask

Can we convert string to byte array in Java?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.

Can we convert string to byte?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.

Which method is used to convert a string to an array of bytes?

String class has getBytes() method which can be used to convert String to byte array in Java. getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

How to convert string to byte array in Java?

We can use String class getBytes () method to encode the string into a sequence of bytes using the platform’s default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

How is a byte array initialized in Java?

The byte array will be initialized (init) to 0 when you allocate it. All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialized to 0, arrays of booleans are initialized to false and arrays of reference types are initialized to null. how to init byte array example

What is a byte array used for?

A byte array is an array of bytes. You could use a byte array to store a collection of binary data ( byte [] ), for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

Can we use any charset for decoding a byte array?

However, we can't just use any charset for decoding a byte array. In particular, we should use the charset that encoded the String into the byte array. We can also convert a byte array to a String in many ways.


2 Answers

A common way to send byte array is to encode it in Base64 before sending it, on the other side when receiving the string it must be decoded the Base64 to get the original byte array. For example:

Sender:

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE,clefPrivee);
byte[] cipherText= cipher.doFinal(msgEnOctets);
return Base64.getEncoder().encodeToString(cipherText);

Receiver:

public void getMessage(String message) {
    byte[] decodeMessage = Base64.getDecoder().decode(message);
    //...
}
like image 164
JUAN CALVOPINA M Avatar answered Oct 28 '22 00:10

JUAN CALVOPINA M


Please do NOT use the conversion from @andy jason (https://stackoverflow.com/a/63489562/8166854) as a byte array (especially when used with data used for encryption) cannot get converted to a string and vice verse with new String(bytes, charset).

One method for a byte array -> String -> byte array conversion is to use the Base64-encoding:

result:

ByteToString and reverse test
bytes: ee99c01c47185dbd6b62dd9bcfed94d7

method as by comment andy jason
s: ��G]�kbݛ���
tab:   efbfbdefbfbd1c47185defbfbd6b62dd9befbfbdefbfbdefbfbd
bytes equal to tab: false

method with base64
s2: 7pnAHEcYXb1rYt2bz+2U1w==
tab2:   ee99c01c47185dbd6b62dd9bcfed94d7
bytes equal to tab2: true

code:

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class ByteToString {
    public static void main(String[] args) {
        System.out.println("https://stackoverflow.com/questions/63489517/string-of-byte-array-to-byte-array-rsa-and-java");
        System.out.println("ByteToString and reverse test");
        byte[] bytes = new byte[16];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(bytes);
        System.out.println("bytes: " + bytesToHex(bytes));

        // method by andy jason
        System.out.println("\nmethod as by comment andy jason");
        Charset charset = StandardCharsets.UTF_8;
        String s = new String(bytes, charset);
        System.out.println("s: " + s);
        byte [] tab = s.getBytes (charset);
        System.out.println("tab:   " + bytesToHex(tab));
        System.out.println("bytes equal to tab: " + Arrays.equals(bytes, tab));

        // method with base64
        System.out.println("\nmethod with base64");
        String s2 = Base64.getEncoder().encodeToString(bytes);
        System.out.println("s2: " + s2);
        byte[] tab2 = Base64.getDecoder().decode(s2);
        System.out.println("tab2:   " + bytesToHex(tab2));
        System.out.println("bytes equal to tab2: " + Arrays.equals(bytes, tab2));

    }
    private static String bytesToHex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        return result.toString();
    }
}
like image 36
Michael Fehr Avatar answered Oct 28 '22 00:10

Michael Fehr