org.bouncycastle.openpgp.PGPLiteralData Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPLiteralData. 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: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 7 votes vote down vote up
public static byte[] decrypt( final byte[] encryptedMessage, final InputStream secretKeyRing,
                              final String secretPwd ) throws PGPException
{
    try
    {
        final PGPLiteralData msg = asLiteral( encryptedMessage, secretKeyRing, secretPwd );
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        Streams.pipeAll( msg.getInputStream(), out );
        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in decrypt", e );
    }
}
 
Example #3
Source File: PGPSign.java    From peer-os with Apache License 2.0 6 votes vote down vote up
private static void produceSign( byte[] data, BCPGOutputStream bcOut, PGPSignatureGenerator signGen )
        throws IOException, PGPException
{
    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();

    OutputStream os = literalGen.open( bcOut, PGPLiteralData.BINARY, "", data.length, new Date() );

    InputStream is = new ByteArrayInputStream( data );

    int ch;

    while ( ( ch = is.read() ) >= 0 )
    {
        signGen.update( ( byte ) ch );
        os.write( ch );
    }

    literalGen.close();

    signGen.generate().encode( bcOut );
}
 
Example #4
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
private static PGPLiteralData asLiteral( final byte[] message, final InputStream secretKeyRing,
                                         final String secretPwd ) throws IOException, PGPException
{
    PGPPrivateKey key = null;
    PGPPublicKeyEncryptedData encrypted = null;
    final PGPSecretKeyRingCollection keys =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRing ),
                    new JcaKeyFingerprintCalculator() );
    for ( final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects( message );
          ( key == null ) && i.hasNext(); )
    {
        encrypted = i.next();
        key = getPrivateKey( keys, encrypted.getKeyID(), secretPwd );
    }
    if ( key == null )
    {
        throw new IllegalArgumentException( "secret key for message not found." );
    }
    final InputStream stream = encrypted
            .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( provider ).build( key ) );
    return asLiteral( stream );
}
 
Example #5
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void encrypt(String sourceFile, String targetFile, Collection<Key> recipients,
		ProgressHandler optionalProgressHandler, InputStreamSupervisor optionalInputStreamSupervisor,
		OutputStreamSupervisor optionalOutputStreamSupervisor) throws UserRequestedCancellationException {
	try {
		InputStreamSupervisor inputStreamSupervisor = optionalInputStreamSupervisor != null
				? optionalInputStreamSupervisor
				: new InputStreamSupervisorImpl();
		OutputStreamSupervisor outputStreamSupervisor = optionalOutputStreamSupervisor != null
				? optionalOutputStreamSupervisor
				: new OutputStreamSupervisorImpl();

		Updater progress = null;
		if (optionalProgressHandler != null) {
			progress = Progress.create("action.encrypt", optionalProgressHandler);
			progress.updateStepInfo("progress.preparingKeys");
		}

		PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
				buildKeysListForEncryption(recipients));

		OutputStream out = new BufferedOutputStream(outputStreamSupervisor.get(targetFile));
		InputStream in = inputStreamSupervisor.get(sourceFile);
		doEncryptFile(in, SourceInfo.fromFile(sourceFile), out, dataGenerator, progress, PGPLiteralData.BINARY);
		out.close();
		in.close();
	} catch (Throwable t) {
		File fileToDelete = new File(targetFile);
		if (fileToDelete.exists() && !fileToDelete.delete()) {
			log.warn("Failed to delete file after failed encryption: " + targetFile);
		}
		Throwables.throwIfInstanceOf(t, UserRequestedCancellationException.class);
		throw new RuntimeException("Encryption failed", t);
	}
}
 
Example #6
Source File: Crypt.java    From cloudsync with GNU General Public License v2.0 5 votes vote down vote up
public String encryptText(String text) throws FileIOException
{
	final ByteArrayOutputStream output = new ByteArrayOutputStream();
	final byte[] bytes = text.getBytes();
	_encryptData(output, new ByteArrayInputStream(bytes), bytes.length, PGPLiteralData.CONSOLE, null, ENCRYPT_ALGORITHM, ENCRYPT_ARMOR);

	text = Base64.encodeBase64String(output.toByteArray());
	text = text.replace('/', '_');
	return text;
}
 
Example #7
Source File: GPGFileDecryptor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Move to the next {@link InputStream} if available, otherwise set {@link #currentUnderlyingStream} to null to
 * indicate that there is no more data.
 * @throws IOException
 */
private void moveToNextInputStream() throws IOException {
  Object pgpfObject = this.pgpFact.nextObject();

  // no more data
  if (pgpfObject == null) {
    this.currentUnderlyingStream = null;
    return;
  }

  if (pgpfObject instanceof PGPCompressedData) {
    PGPCompressedData cData = (PGPCompressedData) pgpfObject;

    try {
      this.pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
    } catch (PGPException e) {
      throw new IOException("Could not get the PGP data stream", e);
    }

    pgpfObject = this.pgpFact.nextObject();
  }

  if (pgpfObject instanceof PGPLiteralData) {
    this.currentUnderlyingStream = ((PGPLiteralData) pgpfObject).getInputStream();
  } else if (pgpfObject instanceof PGPOnePassSignatureList) {
    throw new IOException("encrypted message contains PGPOnePassSignatureList message - not literal data.");
  } else if (pgpfObject instanceof PGPSignatureList) {
    throw new IOException("encrypted message contains PGPSignatureList message - not literal data.");
  } else {
    throw new IOException("message is not a simple encrypted file - type unknown.");
  }
}
 
Example #8
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 #9
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * ***********************************************
 */
private static PGPLiteralData asLiteral( final InputStream clear ) throws IOException, PGPException
{
    final PGPObjectFactory plainFact = new PGPObjectFactory( clear, new JcaKeyFingerprintCalculator() );
    final Object message = plainFact.nextObject();
    if ( message instanceof PGPCompressedData )
    {
        final PGPCompressedData cData = ( PGPCompressedData ) message;
        final PGPObjectFactory pgpFact =
                new PGPObjectFactory( cData.getDataStream(), new JcaKeyFingerprintCalculator() );
        // Find the first PGPLiteralData object
        Object object = null;
        for ( int safety = 0; ( safety++ < 1000 ) && !( object instanceof PGPLiteralData );
              object = pgpFact.nextObject() )
        {
            //ignore
        }
        return ( PGPLiteralData ) object;
    }
    else if ( message instanceof PGPLiteralData )
    {
        return ( PGPLiteralData ) message;
    }
    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: " + message.getClass().getName() );
    }
}
 
Example #10
Source File: FileMetadata.java    From jpgpj with MIT License 5 votes vote down vote up
/** Constructs a metadata object from Bouncy Castle message data. */
public FileMetadata(PGPLiteralData data) {
    this(data.getFileName(), Format.byCode((char) data.getFormat()));

    Date modificationTime = data.getModificationTime();
    if (modificationTime != null) {
        setLastModified(modificationTime.getTime());
    }
}
 
Example #11
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String encryptText(String sourceText, Collection<Key> recipients) {
	try {
		PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
				buildKeysListForEncryption(recipients));

		SourceInfo encryptionSourceInfo = new SourceInfo("text.asc", sourceText.length(),
				System.currentTimeMillis());
		ByteArrayOutputStream pOut = new ByteArrayOutputStream();
		ByteArrayInputStream pIn = new ByteArrayInputStream(sourceText.getBytes("UTF-8"));
		ArmoredOutputStream armoredOut = new ArmoredOutputStream(pOut);
		doEncryptFile(pIn, encryptionSourceInfo, armoredOut, dataGenerator, null, PGPLiteralData.BINARY);
		pIn.close();
		armoredOut.flush();
		armoredOut.close();
		return pOut.toString();
	} catch (Throwable t) {
		throw new RuntimeException("Encryption failed", t);
	}
}
 
Example #12
Source File: PGPDecrypt.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private static InputStream getInputStream( PGPPrivateKey privateKey, PGPPublicKeyEncryptedData pgpEncData )
        throws PGPException, IOException
{
    InputStream is = pgpEncData
            .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( "BC" ).build( privateKey ) );

    JcaPGPObjectFactory objectFactory = new JcaPGPObjectFactory( is );

    Object message = objectFactory.nextObject();

    PGPCompressedData compressedData = ( PGPCompressedData ) message;

    JcaPGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory( compressedData.getDataStream() );

    PGPLiteralData literalData = ( PGPLiteralData ) pgpObjectFactory.nextObject();

    return literalData.getInputStream();
}
 
Example #13
Source File: PGPVerify.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private static InputStream getInputStream( JcaPGPObjectFactory objectFactory ) throws IOException
{
    PGPLiteralData literalData = ( PGPLiteralData ) objectFactory.nextObject();

    return literalData.getInputStream();
}
 
Example #14
Source File: PGPEncrypt.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private static byte[] compress( byte data[] ) throws IOException
{
    PGPCompressedDataGenerator compressGen = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    OutputStream compressOut = compressGen.open( bos );

    OutputStream os =
            new PGPLiteralDataGenerator().open( compressOut, PGPLiteralData.BINARY, "", data.length, new Date() );

    os.write( data );

    os.close();

    compressGen.close();

    return bos.toByteArray();
}
 
Example #15
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static byte[] sign( byte[] message, PGPSecretKey secretKey, String secretPwd, boolean armor )
        throws PGPException
{
    try
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream theOut = armor ? new ArmoredOutputStream( out ) : out;

        PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 )
                        .setProvider( provider ) );

        sGen.init( PGPSignature.BINARY_DOCUMENT, pgpPrivKey );

        Iterator it = secretKey.getPublicKey().getUserIDs();
        if ( it.hasNext() )
        {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            spGen.setSignerUserID( false, ( String ) it.next() );
            sGen.setHashedSubpackets( spGen.generate() );
        }

        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator( PGPCompressedData.ZLIB );

        BCPGOutputStream bOut = new BCPGOutputStream( cGen.open( theOut ) );

        sGen.generateOnePassVersion( false ).encode( bOut );

        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        OutputStream lOut =
                lGen.open( bOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] );         //
        InputStream fIn = new ByteArrayInputStream( message );
        int ch;

        while ( ( ch = fIn.read() ) >= 0 )
        {
            lOut.write( ch );
            sGen.update( ( byte ) ch );
        }

        lGen.close();

        sGen.generate().encode( bOut );

        cGen.close();

        theOut.close();

        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in sign", e );
    }
}
 
Example #16
Source File: RydeFileEncoding.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private PgpFileInputStream(PGPLiteralData literal) {
  super("PgpFileReader", literal.getDataStream());
  filename = literal.getFileName();
  modified = new DateTime(literal.getModificationTime(), UTC);
}
 
Example #17
Source File: Encryptor.java    From desktopclient-java with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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();
}
 
Example #18
Source File: RydeFileEncoding.java    From nomulus with Apache License 2.0 2 votes vote down vote up
/**
 * Opens an InputStream to a PGP file blob's data.
 *
 * <p>The result includes the file's metadata - the file name and modification time.
 *
 * <p>TODO(b/110465964): document where the input comes from / output goes to. Something like
 * documenting that input is the result of openDecompressor and the result is the final file
 * (Ghostryde) / goes into openTarDecoder (RyDE).
 *
 * @param input from where to read the file blob.
 */
@CheckReturnValue
static PgpFileInputStream openPgpFileReader(@WillNotClose InputStream input) {
  return new PgpFileInputStream(PgpUtils.readSinglePgpObject(input, PGPLiteralData.class));
}