有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中使用BouncyCastle PGP实用程序的增量加密

我正在尝试编写一个加密文件,该文件将使用gpg解密,并将以增量方式而不是在一个块中写入行。我已经在GnuPG中生成了密钥,并且正在使用公钥进行加密。下面是我用来加密的方法:

  public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey,
            String fileName,boolean withIntegrityCheck, boolean armor)
            throws IOException, PGPException, NoSuchProviderException {
        if (fileName == null) {
            fileName = PGPLiteralData.CONSOLE;
        }

        ByteArrayOutputStream encOut = new ByteArrayOutputStream();

        OutputStream out = encOut;
        if (armor) {
            out = new ArmoredOutputStream(out);
        }

        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();

        // we want to generate compressed data. This might be a user option
        // later,
        // in which case we would pass in bOut.
        OutputStream pOut = lData.open(cos, // the compressed output stream
                PGPLiteralData.BINARY, fileName, // "filename" to store
                clearData.length, // length of clear data
                new Date() // current time
                );
        pOut.write(clearData);

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

        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_192).setSecureRandom(new SecureRandom()));


        cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));

        byte[] bytes = bOut.toByteArray();

        OutputStream cOut = cPk.open(out, bytes.length);

        cOut.write(bytes); // obtain the actual bytes from the compressed stream

        cOut.close();

        out.close();

        return encOut.toByteArray();
    }

我有一个小的原型测试类来使用这种方法,如下所示:

            PGPPublicKey pubKey = PGPEncryptionTools.readPublicKeyFromCol(new FileInputStream(appProp.getKeyFileName()));

        byte[] encryptbytes = PGPEncryptionTools.encrypt("\nthis is some test text".getBytes(), pubKey, null, true, false);
        byte[] encryptbytes2 = PGPEncryptionTools.encrypt("\nmore test text".getBytes(), pubKey, null, true, false);

        FileOutputStream fos = new FileOutputStream("C:/Users/me/workspace/workspace/spring-batch-project/resources/encryptedfile.gpg");
        fos.write(encryptbytes);
        fos.write(encryptbytes2);
        fos.flush();
        fos.close();

这将创建encryptedfile.gpg,但当我转到GnuPG对文件进行解密时,它可以工作,但它只输出第一行“这是一些测试文本”

如何修改此代码,使其能够对这两行进行加密并让GnuPG对其进行解密


共 (1) 个答案

  1. # 1 楼答案

    每次调用PGPEncryptionTools.encrypt(...)方法时,都会生成多条独立的OpenPGP消息。要仅输出一条OpenPGP消息(GnuPG也会在一次运行中对其进行解密),请将所有纯文本写入一个流(在代码中称为pOut),并且在最后将最后一个字节写入流之前不要关闭该流