Java 类org.bouncycastle.openpgp.PGPEncryptedDataGenerator 实例源码

项目:base    文件:PGPEncryptionUtil.java   
public static byte[] encrypt( final byte[] message, final PGPPublicKey publicKey, boolean armored )
        throws PGPException
{
    try
    {
        final ByteArrayInputStream in = new ByteArrayInputStream( message );
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        final PGPLiteralDataGenerator literal = new PGPLiteralDataGenerator();
        final PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );
        final OutputStream pOut =
                literal.open( comData.open( bOut ), PGPLiteralData.BINARY, "filename", in.available(), new Date() );
        Streams.pipeAll( in, pOut );
        comData.close();
        final byte[] bytes = bOut.toByteArray();
        final PGPEncryptedDataGenerator generator = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true )
                                                                                   .setSecureRandom(
                                                                                           new SecureRandom() )

                                                                                   .setProvider( provider ) );
        generator.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setProvider( provider ) );
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out;
        OutputStream cOut = generator.open( theOut, bytes.length );
        cOut.write( bytes );
        cOut.close();
        theOut.close();
        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in encrypt", e );
    }
}
项目:jpgpj    文件:Encryptor.java   
/**
 * Wraps with stream that outputs encrypted data packet.
 */
protected OutputStream encrypt(OutputStream out, FileMetadata meta)
throws IOException, PGPException {
    if (log.isLoggable(Level.FINEST))
        log.finest("using encryption algorithm " + encryptionAlgorithm);

    if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted)
        return null;

    List<Key> keys = ring.getEncryptionKeys();
    if (Util.isEmpty(keys) && Util.isEmpty(symmetricPassphrase))
        throw new PGPException("no suitable encryption key found");

    PGPEncryptedDataGenerator generator = buildEncryptor();
    for (Key key : keys)
        generator.addMethod(buildPublicKeyEncryptor(key));

    if (!Util.isEmpty(symmetricPassphrase))
        generator.addMethod(buildSymmetricKeyEncryptor());

    return generator.open(out, getEncryptionBuffer(meta));
}
项目:Camel    文件:PGPDataFormatTest.java   
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException,
        UnsupportedEncodingException {
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
            .setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath)));
    OutputStream encOut = encGen.open(bos, new byte[512]);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]);

    try {
        litOut.write("Test Message Without Compression".getBytes("UTF-8"));
        litOut.flush();
    } finally {
        IOHelper.close(litOut);
        IOHelper.close(encOut, bos);
    }
}
项目:CryptMeme    文件:ByteArrayHandler.java   
public static void main(String[] args) throws Exception
{
    Security.addProvider(new BouncyCastleProvider());

    String passPhrase = "Dick Beck";
    char[] passArray = passPhrase.toCharArray();

    byte[] original = "Hello world".getBytes();
    System.out.println("Starting PGP test");
    byte[] encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.CAST5, true);

    System.out.println("\nencrypted data = '"+new String(encrypted)+"'");
    byte[] decrypted= decrypt(encrypted,passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");

    encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.AES_256, false);

    System.out.println("\nencrypted data = '"+new String(org.bouncycastle.util.encoders.Hex.encode(encrypted))+"'");
    decrypted= decrypt(encrypted, passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");
}
项目:irma_future_id    文件:ByteArrayHandler.java   
public static void main(String[] args) throws Exception
{
    Security.addProvider(new BouncyCastleProvider());

    String passPhrase = "Dick Beck";
    char[] passArray = passPhrase.toCharArray();

    byte[] original = "Hello world".getBytes();
    System.out.println("Starting PGP test");
    byte[] encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.CAST5, true);

    System.out.println("\nencrypted data = '"+new String(encrypted)+"'");
    byte[] decrypted= decrypt(encrypted,passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");

    encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.AES_256, false);

    System.out.println("\nencrypted data = '"+new String(org.bouncycastle.util.encoders.Hex.encode(encrypted))+"'");
    decrypted= decrypt(encrypted, passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");
}
项目:bc-java    文件:ByteArrayHandler.java   
public static void main(String[] args) throws Exception
{
    Security.addProvider(new BouncyCastleProvider());

    String passPhrase = "Dick Beck";
    char[] passArray = passPhrase.toCharArray();

    byte[] original = "Hello world".getBytes();
    System.out.println("Starting PGP test");
    byte[] encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.CAST5, true);

    System.out.println("\nencrypted data = '"+new String(encrypted)+"'");
    byte[] decrypted= decrypt(encrypted,passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");

    encrypted = encrypt(original, passArray, "iway", PGPEncryptedDataGenerator.AES_256, false);

    System.out.println("\nencrypted data = '"+new String(org.bouncycastle.util.encoders.Hex.encode(encrypted))+"'");
    decrypted= decrypt(encrypted, passArray);

    System.out.println("\ndecrypted data = '"+new String(decrypted)+"'");
}
项目:jpgpj    文件:Encryptor.java   
/**
 * Builds a PGPEncryptedDataGenerator
 * for the configured encryption algorithm.
 */
protected PGPEncryptedDataGenerator buildEncryptor() {
    int algo = encryptionAlgorithm.ordinal();
    BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(algo);
    builder.setWithIntegrityPacket(true);
    return new PGPEncryptedDataGenerator(builder);
}
项目:base    文件:PGPEncrypt.java   
private static PGPEncryptedDataGenerator getEncryptedGenerator( PGPPublicKey publicKey )
{
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder( PGPEncryptedData.CAST5 ).setWithIntegrityPacket( true )
                                                                    .setSecureRandom( new SecureRandom() )
                                                                    .setProvider( "BC" ) );

    encGen.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setProvider( "BC" ) );

    return encGen;
}
项目:mq-mft    文件:CryptDecryptUtil.java   
/**
* Encrypt the given file 
* @param unencryptedFileName - Name of the unecrypted file
* @param encryptedFileName - Name of the encrypted file, will have .enc as extension
* @throws IOException 
* @throws NoSuchProviderException
* @throws PGPException
* @throws CryptDecryptException 
*/
  public void encryptFile(final String unencryptedFileName, final String encryptedFileName)
      throws IOException, NoSuchProviderException, PGPException, CryptDecryptException {
    if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Entry");

    // Initialise PGP provider and read public key
    if(!initialized) initialise(false);

FileOutputStream encrytedFile = new FileOutputStream(encryptedFileName);

// Compress the input plain text file in ZIP format.
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
      PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(unencryptedFileName) );
      comData.close();

      // Encrypt the file using Triple-DES algorithm
      BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
      dataEncryptor.setWithIntegrityPacket(false);
      dataEncryptor.setSecureRandom(new SecureRandom());
      PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
      encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
      byte[] bytes = bOut.toByteArray();
      OutputStream cOut = encryptedDataGenerator.open(encrytedFile, bytes.length);
      cOut.write(bytes);
      cOut.close();
      encrytedFile.close();

      if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Exit");
  }
项目:nomulus    文件:Ghostryde.java   
/**
 * Opens a new {@link Encryptor} (Writing Step 1/3)
 *
 * <p>This is the first step in creating a ghostryde file. After this method, you'll want to
 * call {@link #openCompressor(Encryptor)}.
 *
 * @param os is the upstream {@link OutputStream} to which the result is written.
 * @param publicKey is the public encryption key of the recipient.
 * @throws IOException
 * @throws PGPException
 */
@CheckReturnValue
public Encryptor openEncryptor(@WillNotClose OutputStream os, PGPPublicKey publicKey)
    throws IOException, PGPException {
  PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
      new JcePGPDataEncryptorBuilder(CIPHER)
         .setWithIntegrityPacket(USE_INTEGRITY_PACKET)
         .setSecureRandom(getRandom())
         .setProvider(PROVIDER_NAME));
  encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
  return new Encryptor(encryptor.open(os, new byte[bufferSize]));
}
项目:nomulus    文件:BouncyCastleTest.java   
@Test
public void testEncryptDecrypt_ExplicitStyle() throws Exception {
  int bufferSize = 64 * 1024;

  // Alice loads Bob's "publicKey" into memory.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();

  // Alice encrypts the secret message for Bob using his "publicKey".
  PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
      new BcPGPDataEncryptorBuilder(AES_128));
  encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
  byte[] encryptedData;
  try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
    try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
      output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
    }
    encryptedData = output.toByteArray();
  }
  logger.info("Encrypted data: " + dumpHex(encryptedData));

  // Bob loads his "privateKey" into memory.
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
  try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
    assertThat(encDataList.size()).isEqualTo(1);
    PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
    assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID());
    assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID());
    try (InputStream original =
        encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
      assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
          .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    }
  }
}
项目:Camel    文件:PGPDataFormatTest.java   
@Test
public void testExceptionDecryptorIncorrectInputFormatSymmetricEncryptedData() throws Exception {

    byte[] payload = "Not Correct Format".getBytes("UTF-8");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
            .setSecureRandom(new SecureRandom()).setProvider(getProvider()));

    encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator("pw".toCharArray()));

    OutputStream encOut = encGen.open(bos, new byte[1024]);
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
    OutputStream comOut = new BufferedOutputStream(comData.open(encOut));
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[1024]);
    litOut.write(payload);
    litOut.flush();
    litOut.close();
    comOut.close();
    encOut.close();
    MockEndpoint mock = getMockEndpoint("mock:exception");
    mock.expectedMessageCount(1);
    template.sendBody("direct:subkeyUnmarshal", bos.toByteArray());
    assertMockEndpointsSatisfied();

    checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format.");
}
项目:geocaching    文件:StringEncryptor.java   
public String encryptString(PGPPublicKey key, String clearText)
        throws IOException, PGPException {

    byte[] clearData = clearText.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream encOut = new ByteArrayOutputStream();
    OutputStream out = new ArmoredOutputStream(encOut);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
            PGPCompressedDataGenerator.ZIP);
    OutputStream cos = comData.open(bOut);
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

    OutputStream pOut = lData.open(cos, PGPLiteralData.BINARY,
            PGPLiteralData.CONSOLE, clearData.length, new Date());
    pOut.write(clearData);

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

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
                    .setWithIntegrityPacket(true)
                    .setSecureRandom(new SecureRandom()).setProvider(BouncyCastleProvider.PROVIDER_NAME));

    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key)
            .setProvider(BouncyCastleProvider.PROVIDER_NAME));

    byte[] bytes = bOut.toByteArray();
    OutputStream cOut = encGen.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();
    out.close();

    return new String(encOut.toByteArray());
}
项目:base    文件:PGPEncryptionUtil.java   
public static byte[] signAndEncrypt( final byte[] message, final PGPSecretKey secretKey, final String secretPwd,
                                     final PGPPublicKey publicKey, final boolean armored ) throws PGPException
{
    try
    {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true )
                                                                                   .setSecureRandom(
                                                                                           new SecureRandom() )
                                                                                   .setProvider( provider ) );

        encryptedDataGenerator.addMethod(
                new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setSecureRandom( new SecureRandom() )
                                                                         .setProvider( provider ) );

        final OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out;
        final OutputStream encryptedOut = encryptedDataGenerator.open( theOut, new byte[4096] );

        final PGPCompressedDataGenerator compressedDataGenerator =
                new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );
        final OutputStream compressedOut = compressedDataGenerator.open( encryptedOut, new byte[4096] );
        final PGPPrivateKey privateKey = secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
        final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 )
                        .setProvider( provider ) );
        signatureGenerator.init( PGPSignature.BINARY_DOCUMENT, privateKey );
        final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
        if ( it.hasNext() )
        {
            final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID( false, ( String ) it.next() );
            signatureGenerator.setHashedSubpackets( spGen.generate() );
        }
        signatureGenerator.generateOnePassVersion( false ).encode( compressedOut );
        final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        final OutputStream literalOut = literalDataGenerator
                .open( compressedOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] );
        final InputStream in = new ByteArrayInputStream( message );
        final byte[] buf = new byte[4096];
        for ( int len; ( len = in.read( buf ) ) > 0; )
        {
            literalOut.write( buf, 0, len );
            signatureGenerator.update( buf, 0, len );
        }
        in.close();
        literalDataGenerator.close();
        signatureGenerator.generate().encode( compressedOut );
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        theOut.close();
        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in signAndEncrypt", e );
    }
}
项目:brownsocks-payments-enets    文件:BCPGPProvider.java   
@Override
public String signAndEncrypt(String message) throws IOException {

    try {
        /* Final < Armored < Crypted < Clear PGP */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ArmoredOutputStream armoredOutput = new ArmoredOutputStream(out);
        PGPEncryptedDataGenerator crypter = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.S2K_SHA1, new SecureRandom(), _provider);
        crypter.addMethod(getRemotePublicKey());
        BCPGOutputStream pgpOut = new BCPGOutputStream(crypter.open(armoredOutput, new byte[512]));

        /* Prepare for signing */
        PGPSignatureGenerator signer = new PGPSignatureGenerator(getSigningPublicKey().getAlgorithm(), 
                PGPUtil.SHA1, _provider
                );
        signer.initSign(PGPSignature.BINARY_DOCUMENT, getSigningPrivateKey());

        /* Output the standard header */
        signer.generateOnePassVersion(false).encode(pgpOut);

        /* Output the literal data */
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(true);
        literalDataGenerator.open(pgpOut, 'b', "bar", message.getBytes().length, new Date()).write(message.getBytes());

        /* Calculate signature and output it */
        signer.update(message.getBytes());
        signer.generate().encode(pgpOut);

        pgpOut.close();
        armoredOutput.close();
        out.close();

        byte[] result = out.toByteArray();

        // brain dead UMAPI adds an extra base64 encoding on top of the ASCII armored string. Go figure.
        return new String(Base64.encode(result));

    } catch (PGPException pgpException) {
        throw new IOException("PGP subsystem problem.", pgpException);

    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
        throw new IOException("Missing algorithm. Are you running a compatible JVM/Bouncycastle version?", noSuchAlgorithmException);

    } catch (SignatureException signatureException) {
        throw new IOException("PGP subsystem problem.", signatureException);

    } catch (NoSuchProviderException noSuchProviderException) {
        throw new IOException("Missing provider. Are you running a compatible JVM/Bouncycastle version?", noSuchProviderException);

    }


}
项目:subshare    文件:BcPgpEncoder.java   
private PGPEncryptedDataGenerator createEncryptedDataGenerator() {
    return new PGPEncryptedDataGenerator(
            new BcPGPDataEncryptorBuilder(getSymmetricEncryptionAlgorithm().getSymmetricKeyAlgorithmTag())
            .setWithIntegrityPacket(isWithIntegrityCheck())
            .setSecureRandom(new SecureRandom()));
}
项目:subshare    文件:GnuPgTest.java   
@Test
public void encryptAndDecrypt() throws Exception {
    // both keys have property encryptionKey==true
    final String[] keyIds = {
            "d7a92a24aa97ddbd", // master-key
            "a58da7d810b74edf" // sub-key
    };

    for (final String keyId : keyIds) {
        final PGPDataEncryptorBuilder encryptorBuilder = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.TWOFISH);
        final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(encryptorBuilder);
        final PGPKeyEncryptionMethodGenerator keyEncryptionMethodGenerator = new BcPublicKeyKeyEncryptionMethodGenerator(
                getPgpPublicKeyOrFail(bytesToLong(decodeHexStr(keyId))));

        encryptedDataGenerator.addMethod(keyEncryptionMethodGenerator);

        final byte[] plain = new byte[1 + random.nextInt(1024 * 1024)];
        random.nextBytes(plain);

        final File encryptedFile = File.createTempFile("encrypted_", ".tmp");
        try (final OutputStream encryptedOut = new FileOutputStream(encryptedFile);) {
            try (final OutputStream plainOut = encryptedDataGenerator.open(encryptedOut, new byte[1024 * 16]);) {
                plainOut.write(plain);
            }
        }

        final byte[] decrypted;
        try (InputStream in = new FileInputStream(encryptedFile)) {
            final PGPEncryptedDataList encryptedDataList = new PGPEncryptedDataList(new BCPGInputStream(in));
            final Iterator<?> encryptedDataObjects = encryptedDataList.getEncryptedDataObjects();
            assertThat(encryptedDataObjects.hasNext()).isTrue();
            final PGPPublicKeyEncryptedData encryptedData = (PGPPublicKeyEncryptedData) encryptedDataObjects.next();
            assertThat(encryptedDataObjects.hasNext()).isFalse();

            final PublicKeyDataDecryptorFactory dataDecryptorFactory = new BcPublicKeyDataDecryptorFactory(
                    getPgpPrivateKeyOrFail(encryptedData.getKeyID(), "test12345".toCharArray()));

            try (InputStream plainIn = encryptedData.getDataStream(dataDecryptorFactory);) {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                transferStreamData(plainIn, out);
                decrypted = out.toByteArray();
            }
        }

        assertThat(decrypted).isEqualTo(plain);

        encryptedFile.delete(); // delete it, if this test did not fail
    }
}
项目:bcpg-simple    文件:BcPGPSignEncryptTransform.java   
public void run(final char[] passphrase, final InputStream inputStream, final OutputStream outputStream) throws IOException, CryptoException {
  try {
    final OutputStream armor = new ArmoredOutputStream(outputStream);

    final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(
        SymmetricKeyAlgorithmTags.AES_128).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(new BouncyCastleProvider()));
    encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setSecureRandom(new SecureRandom()).setProvider(
        new BouncyCastleProvider()));

    final OutputStream encryptedOut = encryptedDataGenerator.open(armor, new byte[4096]);

    final PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
    final OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[4096]);

    final PGPPrivateKey privateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(new BouncyCastleProvider())
        .build(passphrase));

    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey()
        .getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(new BouncyCastleProvider()));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
    final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
    if (it.hasNext()) {
      final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
      spGen.setSignerUserID(false, (String) it.next());
      signatureGenerator.setHashedSubpackets(spGen.generate());
    }
    signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

    final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    final OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
    final byte[] buf = new byte[4096];
    for (int len = 0; (len = inputStream.read(buf)) > 0;) {
      literalOut.write(buf, 0, len);
      signatureGenerator.update(buf, 0, len);
    }
    literalDataGenerator.close();
    signatureGenerator.generate().encode(compressedOut);
    compressedDataGenerator.close();
    encryptedDataGenerator.close();
    armor.close();
  }
  catch (final Exception e) {
    throw new CryptoException(e);
  }

}
项目:desktopclient-java    文件:Encryptor.java   
/**
 * Encrypt, sign and write input stream data to output stream.
 * Input and output stream are closed.
 */
private static void encryptAndSign(
        InputStream plainInput, OutputStream encryptedOutput,
        PersonalKey myKey, List<PGPUtils.PGPCoderKey> receiverKeys)
        throws IOException, PGPException {

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    receiverKeys.forEach(key ->
        encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key.encryptKey)));

    OutputStream encryptedOut = encGen.open(encryptedOutput, new byte[BUFFER_SIZE]);

    // setup compressed data generator
    PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

    // setup signature generator
    int algo = myKey.getSigningAlgorithm();
    PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA256));
    sigGen.init(PGPSignature.BINARY_DOCUMENT, myKey.getPrivateSigningKey());

    PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
    spGen.setSignerUserID(false, myKey.getUserId());
    sigGen.setUnhashedSubpackets(spGen.generate());

    sigGen.generateOnePassVersion(false).encode(compressedOut);

    // Initialize literal data generator
    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    OutputStream literalOut = literalGen.open(
        compressedOut,
        PGPLiteralData.BINARY,
        "",
        new Date(),
        new byte[BUFFER_SIZE]);

    // read the "in" stream, compress, encrypt and write to the "out" stream
    // this must be done if clear data is bigger than the buffer size
    // but there are other ways to optimize...
    byte[] buf = new byte[BUFFER_SIZE];
    int len;
    while ((len = plainInput.read(buf)) > 0) {
        literalOut.write(buf, 0, len);
        sigGen.update(buf, 0, len);
    }

    literalGen.close();

    // generate the signature, compress, encrypt and write to the "out" stream
    sigGen.generate().encode(compressedOut);
    compGen.close();
    encGen.close();
}