如何在jruby9.1.2.0中使用gpg加密来加密文件?

时间:2016-11-25 09:23:54

标签: java ruby-on-rails encryption bouncycastle openpgp

我正在尝试使用gpg加密加密文件,然后在我的jruby项目中发送它。但是我找不到足够的资源。我尝试使用ruby-gpgme,但jruby不支持C库。我尝试阅读Bouncy Castle,但我被课程文档所震撼,并没有找到一篇加密文件的简单文章。

Vivek在this问题中的答案接近我的解决方案,但只有解密文件的解决方案。我目前正在关注this article并试图在jruby中连接java代码无济于事。我认为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

at

 PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);

如果你可以在整个jruby中使用gpg帮助我使用代码或加密文件,那将是一个很大的帮助。

更新1 ZIP值结果为整数值的常量,并列在this页面中。

更新2 我做到了这个功能:

PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
    encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); // encKey is class PGPPublicKey's instance

我有从OS生成的公钥。如何从我拥有的公钥字符串创建PGPPublic Key实例encKey

0 个答案:

没有答案