org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator Java Examples

The following examples show how to use org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 7 votes vote down vote up
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 );
    }
}
 
Example #2
Source File: PGPEncrypt.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #3
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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 );
    }
}
 
Example #4
Source File: GPGFileEncryptor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}.
 * @param outputStream {@link OutputStream} that will receive the encrypted content
 * @param keyIn keyring inputstream. This InputStream is owned by the caller.
 * @param keyId key identifier
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return an {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher)
    throws IOException {
  try {
    if (Security.getProvider(PROVIDER_NAME) == null) {
      Security.addProvider(new BouncyCastleProvider());
    }

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
        new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
            .setSecureRandom(new SecureRandom())
            .setProvider(PROVIDER_NAME));

    PGPPublicKey publicKey;
    PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
        new BcKeyFingerprintCalculator());
    publicKey = keyRings.getPublicKey(keyId);

    if (publicKey == null) {
      throw new IllegalArgumentException("public key for encryption not found");
    }

    cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME));

    OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    OutputStream _literalOut =
        literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]);

    return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
  } catch (PGPException e) {
    throw new IOException(e);
  }
}