有 Java 编程相关的问题?

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

如何在Java中使用BouncyCastle PGP实用程序实现增量加密?

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对它们进行解密

上面是我用来解密代码的代码

public static void decryptFile(
        InputStream in,
        InputStream keyIn,
        char[] passwd,
        String defaultFileName)
        throws IOException, NoSuchProviderException {
    in = PGPUtil.getDecoderStream(in);

    try {
        JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
        PGPEncryptedDataList enc;

        Object o = pgpF.nextObject();
        //
        // the first object might be a PGP marker packet.
        //
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpF.nextObject();
        }

        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();

            sKey = findSecretKey(pgpSec, pbe.getKeyID(), passwd);
        }

        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }

        InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));

        JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);

        PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject();

        InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(compressedStream);

        Object message = pgpFact.nextObject();

        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;

            String outFileName = ld.getFileName();
            //if (outFileName.length() == 0) {
                outFileName = defaultFileName;
            //}

            InputStream unc = ld.getInputStream();
            OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));

            Streams.pipeAll(unc, fOut);

            fOut.close();
        } else if (message instanceof PGPOnePassSignatureList) {
            throw new PGPException("encrypted message contains a signed message - not literal data.");
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown.");
        }

        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                System.err.println("message failed integrity check");
            } else {
                System.err.println("message integrity check passed");
            }
        } else {
            System.err.println("no message integrity check");
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

共 (0) 个答案