1

In my case the out put stream is basically FileOutputStream. Hence for this code:

ByteArrayOutputStream bos = (ByteArrayOutputStream) streamToEncrypt;

(Where streamToEncrypt is OutputStream) is getting this exception:

java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ByteArrayOutputStream

All I need to do is to get the byte array out of this outputstream. I do NOT have access to the file at this level. All I have is this output stream that I have to encrypt before pushing it to the file

3
  • Possible duplicate of write content in a byte array to a file and read the byte from file back to byte array Commented Oct 4, 2016 at 19:04
  • To get the contents of a file, you have to read it. If you want to get a byte[] from an OutputStream, use a ByteArrayOutputStream, that is what it for. Commented Oct 4, 2016 at 19:05
  • CipherInputStream and CipherOutputStream may prove helpful. Commented Oct 4, 2016 at 19:06

2 Answers 2

6

That simply doesn't make any sense.

A ByteArrayOutputStream takes the data you push into it ... and stores them within a byte array that you can retrieve later on.

A FileOutputStream takes data ... and pushes it into a file.

Those are two completely different classes; you simply can't cast one into the other! Thats like you trying to cast a String into an Integer; or turning an Apple into a Banana by saying "you apple, now be a banana". Simply wont work!

So, the real "answer" here: you should step back and clarify what exactly you intend to do with your data; and then you use that stream(s) matching that requirement(s).

Sign up to request clarification or add additional context in comments.

Comments

1

You don't get bytes out of an OutputStream. You get them out of an InputStream. You put bytes into an OutputStream.

If bytes have already been written to the OutputStream, it's too late. Opening the file again and reading from it is the only way for you to access those data.

If you want to encrypt an output stream, you should construct the stream and pass it to the code that writes to the stream.

Cipher enc = Cipher.getInstance("...");
enc.init(...);
try (OutputStream fos = Files.newOutputStream(path);
     OutputStream os = new CipherOutputStream(fos, enc)) {
   writingObject.write(os);
}

2 Comments

enc.init() needs a public key . I have the key in .asc format. May I get hint on how to create the key using that file/filePath ? I am using "BOUNCY CASTLE" . Thanks for your response
@Patty Ask separate question for that.

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.