I am trying to encrypt file using gpg encryption before sending it in my jruby project. However I did not find adequate resources for it. I tried using ruby-gpgme but jruby did not support C libraries. I tried reading Bouncy Castle but I was overwhelmed by the class documentation and did not find a simple article for encrypting a file.
Vivek's answern in this question comes close to my solution, but there is only solution for decrypting the file. I am currently following this article and trying to interface the java code in jruby to no avail. I think the encryptFile
function is what I need which is as follows:
public static void encryptFile(
OutputStream out,
String fileName,
PGPPublicKey encKey,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException, PGPException
{
Security.addProvider(new BouncyCastleProvider());
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
PGPUtil.writeFileToLiteralData(
comData.open(bOut),
PGPLiteralData.BINARY,
new File(fileName) );
comData.close();
BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
dataEncryptor.setWithIntegrityPacket(withIntegrityCheck);
dataEncryptor.setSecureRandom(new SecureRandom());
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = encryptedDataGenerator.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
}
)
I am getting following error:
NoMethodError: undefined method `ZIP' for Java::OrgBouncycastleOpenpgp::PGPCompressedData:Class
at
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
It would be a great help if you can help me with the code or with the encrypting file using gpg in jruby as a whole.
Update 1 The ZIP value turns out to be constant of integer value and is listed in this page.
Update 2 I made it till the function:
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); // encKey is class PGPPublicKey's instance
I have public key generated from OS. How do I create a PGPPublic Key instance encKey
from the public key string I have?