Search code examples
javacsvencryptionbouncycastle

BouncyCastle openPGP encrypt byte[] array as csv file


I have gotten my code to be able to load in a public key, and encrypt a byte[] array with a public key someone else has provided. However, when i decrypt the file, it doesn't have a .csv extension. I can open it in Excel and it looks like a csv once I open it, but the file just doesn't have any extension associated to it, so I have to weirdly open it in Excel.

enter image description here

I've also attached my code below and I just couldn't figure out where to modify it so that when I decrypt it using Kleopatra, it shows with a .csv extension. I tried to change my output stream to a .csv from a .gpg file, but then it throws an error saying that it could not determine whether this is a OpenPGP signature. I think I have to do something with the lData.open() method, but the only options I can put there are PGPLiteralData.TEXT, BINARY, and UTF8. Maybe this has to do with adding a signature to the file?

Btw, for the code below, the public key is already loaded into a variable called pubkey.

byte[] bytesArray = getAccessChannels(customerAlias);

OutputStream out = new FileOutputStream("/path/to/file/eData.gpg");
Security.addProvider(new BouncyCastleProvider());
ByteArrayOutputStream bOut = new ByteArrayOutputStream();

PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut); // open it with the final destination
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

OutputStream pOut = lData.open(cos, PGPLiteralData.TEXT, "Report.csv", bytesArray.length, new Date());
pOut.write(bytesArray);

lData.close();
comData.close();

PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setSecureRandom(new SecureRandom()));
cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(pubKey));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.close();

Solution

  • Nevermind, I just needed to change the file extension to eData.csv.gpg...this took me a whole 2 days