我正在尝试在我的jruby项目中使用gpg加密来加密文件,但是我没有找到足够的资源。我尝试使用ruby-gpgme,但是jruby不支持C库。我试着阅读Bouncy Castle,但是我被类文档压倒了,没有找到一个简单的文章来对文件进行加密。
Vivek在这个问题的回答接近了我的解决方案,但只有解密文件的方法。我目前正在按照这篇文章的指导,试图将Java代码与jruby接口起来,但一直没有成功。我认为encryptFile
函数就是我需要的,如下所示:
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();
}
)
我遇到了以下错误:
NoMethodError: undefined method `ZIP' for Java::OrgBouncycastleOpenpgp::PGPCompressedData:Class
在
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
如果您能帮我编写代码或使用gpg在jruby中加密文件,那将是非常有帮助的。
更新1 ZIP值原来是一个整数常量,并列在这个页面中。
更新2 我已经完成了这个函数:
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); // encKey is class PGPPublicKey's instance
我有从操作系统生成的公钥。 我应该如何从我拥有的公钥字符串创建一个PGPPublic Key实例 encKey ?
ZIP
可能是一个类常量而不是一个方法。尝试使用PGPCompressedData::ZIP
来引用一个类常量,而不是使用.ZIP
来引用一个类方法。 - EnabrenTanePGPCompressedData.zip
会调用一个方法。你想引用类内部的常量。使用::
而不是.
应该可以解决问题。通过PGPCompressedData.constants.sort
和PGPCompressedData.methods.sort
来反思PGPCompressedData
也可能有所帮助。如果它是一个常量,将PGPCompressedData.ZIP
替换为PGPCompressedData::ZIP
就可以了。 - EnabrenTane