Why can't CipherOutputStream write to ByteArrayOutputStream?

I am trying to encrypt a string and store encrypted bytes in a primitive byte array using a CipherOutputStream , which is supported by ByteArrayOutputStream , but the size of the ByteArrayOutputStream object remains equal to zero and it does not encode any bytes after something is written to the CipherOutputStream object. Here is the code.

 ByteArrayOutputStream out = new ByteArrayOutputStream(); CipherOutputStream cos = new CipherOutputStream(out, c); PrintWriter pw = new PrintWriter(cos); pw.println("Write something"); cos.flush(); out.flush(); System.out.println(out.size()); pw.close(); 

So, I tried to make a comparison by changing ByteArrayOutputStream to FileOutputStream using the code below. It turned out that the encrypted bytes are written to the target file. Does anyone know why I cannot use ByteArrayOutputStream here? Can you offer a solution?

 FileOutputStream out = new FileOutputStream("/path/encrypted.txt"); CipherOutputStream cos = new CipherOutputStream(out, c); PrintWriter pw = new PrintWriter(cos); pw.println("Write something"); pw.close(); 
+4
source share
2 answers

The only difference between these fragments is that in the first case you check the contents before closing the stream, while in the second case after closing. So, I think you need to close the thread before checking.

+4
source

The problem is encryption.

  Cipher cipher = Cipher.getInstance("RSA"); 

It has no indentation. Use

  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 

instead

0
source

Source: https://habr.com/ru/post/1335577/


All Articles