Problems with encrypt and decrypt - java

I'm trying to write code in Java that will encrypt file. I had used example from this site:
http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html
Everything works fine but I need code that will overwrite original file with encrypted one. I'd changed only this:
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("original.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("original.txt");
FileOutputStream fos2 = new FileOutputStream("original.txt");
Encryption works, but after decryption decrypted file is empty.
Can someone explain me what's the problem and how to solve it?
Thanks !

You shouldn't read and overwrite the same file simultaneously with FileInputStream and FileOutputStream. Often, you'll get lucky, but the behavior is going to vary based on the underlying system, and that's not good. Instead, write to a temporary file, then move the temporary file to the location of the original file.

Related

Encrypting large files (2GB) using AES/CBC/PKCS5padding

I have very large file about 2GB and i want to encrypt it by cutting it on chunks, if I read it at once its too big and my JVM throws OutOfMemory Error. I am using AES/CBC/PKCS5padding. Can you recommend me a way to do it? I read about CipherStreams but I am not sure if they would work. Thanks in advance!
I am using this strategy right now, but its not working for bigger files.
try (FileInputStream input = new FileInputStream(in);
FileOutputStream output = new FileOutputStream(out)) {
byte[] encoded = cipher.doFinal(ByteStreams.toByteArray(input));
output.write(encoded);
}
Create a CipherOutputStream wrapping your FileOuputStream.
Use Files.copy() to copy your file to this CipherOutputStream.
Done.
Read the javadoc for details.

Trying to sign a pdf document with java. Why is the signature invalid in the PDF files?

I'm currently working with PDFs on a Java application that makes some modifications to PDF Documents.
Currently, the signing of these PDFs is working, as I am using classes such as FileInputStream and FileOutputStream. Basically, I copy the original documents from a source folder, and then put them in a output folder, with. I am using PDDocument class with pdfbox 1.8.9
However, I want to use the same file, meaning I don't pretend to copy the PDFs anymore. I want to grab the document, sign it, and overwrite the original one.
Since I learned that having FileInputStream and FileOutputStream pointing at the same file is not a good idea, I simply tried to use the File class.
I tried the following:
File file = new File(locOriginal);
PDDocument doc = PDDocument.load(file);
PDSignature signature = new PDSignature();
Overlay overlay = new Overlay();
//The signature itself. It has not been modified
signature.setFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); // default filter
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
if (msg.getAreaNegocio().startsWith("A")) {
signature.setName(this.campoCertificadoAcquiring);
signature.setLocation(this.localCertificadoAcquiring);
signature.setReason(this.razaoCertificadoAcquiring);
}else {
signature.setName(this.campoCertificadoIssuing);
signature.setLocation(this.localCertificadoIssuing);
signature.setReason(this.razaoCertificadoIssuing);
}
// register signature dictionary and sign interface
doc.addSignature(signature,this);
doc.saveIncremental(file.getAbsolutePath());
doc.close();
My PDF file does get overwritten as intended, yet, the signature is not valid anymore when I open the file. I read these questions... Does it relate to any of these issues? What can I do to solve to this?
PDFBox 1.8.10: Fill and Sign PDF produces invalid signatures
PDFBox - opening and saving a signed pdf invalidates my signature
Thanks for the help!
The 1.8.* saveIncremental(filename) was buggy until PDFBox 1.8.16. This is described in PDFBOX-4312 but is confusing because the user deleted most of his own messages and had multiple other problems. If you insist on using an outdated version (that has a security issue), then try this code instead of calling saveIncremental(filename):
//BEWARE: do not "optimize" this method by using buffered streams,
// because COSStandardOutputStream only allows seeking
// if a FileOutputStream is passed, see PDFBOX-4312.
FileInputStream fis = new FileInputStream(fileName);
byte[] ba = IOUtils.toByteArray(fis);
fis.close();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(ba);
fis = new FileInputStream(fileName);
saveIncremental(fis, fos);
And no, I don't think that the questions you linked to related to your issue.
Btw I don't consider overwriting the original file to be a good idea. You are risking the loss of your file if there is an error or a power loss.
See also the comment by mkl: setFilter() is usually called with parameter PDSignature.FILTER_ADOBE_PPKLITE.

in Java Programming, will the file (.txt, .ser etc) get overwritten when we rewrite on existing file?

if I Do like this:
FileOutputStream fos=new FileOutputStream("cse.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(Dictionary);
and Again if I write the same file using the another object of Same type Dictionary on the same file like
FileOutputStream fos=new FileOutputStream("cse.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(List);
Will that file get overwritten ?
If you write simply:
FileOutputStream fos=new FileOutputStream("cse.txt");
Then the old data will be lost and will get overridden by the new data.
However, if you write:
FileOutputStream fos=new FileOutputStream("cse.txt", true);
Then the old data will NOT be lost and the new data will be appended to the old one.
Here, the second argument true indicates that the bytes will be appended to the end of the file rather than overwriting the complete file.
See the documentation

How to convert InputStream to a PDF in Java, without damaging the file?

I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.
Here is the current code:
InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl());
byte[] buffer = new byte[pAdESStream.available()];
pAdESStream.read(buffer);
File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.
Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?
Hello it might be a bit late but you can use PDFBOX api (or itextpdf)
https://www.tutorialkart.com/pdfbox/create-write-text-pdf-file-using-pdfbox/
here is a tuto of the process gl

smb file writing in local drive from network drive is not working

I am trying to write a file in my local drive which is available in a network drive on a server. I can write this image and I can see even the size of the file available. But, when I'm opening the file it says preview not available. Content of the file is not coming.
Code which I read the network file
SmbFileInputStream sfis = null;
sfis = new SmbFileInputStream(serverFile);
fileBytes = new byte[(int) serverFile.length()];
sfis.read(fileBytes);
Code which I write the file in my local drive
FileOutputStream fos;
fos = new FileOutputStream(tempFile);
fos.write(fileBytes);
I also tried with file.copyTo method by giving my local file like a smbfile.
serverFile.copyTo(ss);
I figured it out and it works fine.
Change first two lines to
InputStream sfis = new SmbFileInputStream(serverFile);
real change is reference of the variable is now
InputStream

Categories