org.bouncycastle.openpgp.PGPEncryptedDataGenerator Java Examples
The following examples show how to use
org.bouncycastle.openpgp.PGPEncryptedDataGenerator.
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 |
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: Encryptor.java From jpgpj with MIT License | 6 votes |
/** * Wraps with stream that outputs encrypted data packet. */ protected OutputStream encrypt(OutputStream out, FileMetadata meta) throws IOException, PGPException { EncryptionAlgorithm encAlgo = getEncryptionAlgorithm(); log.trace("using encryption algorithm {}", encAlgo); if (encAlgo == EncryptionAlgorithm.Unencrypted) return null; Ring encRing = getRing(); List<Key> keys = encRing.getEncryptionKeys(); char[] passChars = getSymmetricPassphraseChars(); if (Util.isEmpty(keys) && Util.isEmpty(passChars)) throw new PGPException("no suitable encryption key found"); PGPEncryptedDataGenerator generator = buildEncryptor(); for (Key key : keys) generator.addMethod(buildPublicKeyEncryptor(key)); if (!Util.isEmpty(passChars)) generator.addMethod(buildSymmetricKeyEncryptor()); return generator.open(out, getEncryptionBuffer(meta)); }
Example #3
Source File: GPGFileEncryptor.java From incubator-gobblin with Apache License 2.0 | 6 votes |
/** * Taking in an input {@link OutputStream} and a passPhrase, return an {@link OutputStream} that can be used to output * encrypted output to the input {@link OutputStream}. * @param outputStream the output stream to hold the ciphertext {@link OutputStream} * @param passPhrase pass phrase * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used. * @return {@link OutputStream} to write content to for encryption * @throws IOException */ public OutputStream encryptFile(OutputStream outputStream, String passPhrase, 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)); cPk.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()).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); } }
Example #4
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 5 votes |
@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 #5
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 5 votes |
@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: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 5 votes |
private static void doEncryptFile(InputStream pIn, SourceInfo encryptionSourceInfo, OutputStream out, PGPEncryptedDataGenerator encDataGen, Updater progress, char outputType) throws IOException, NoSuchProviderException, PGPException, UserRequestedCancellationException { OutputStream encryptedStream = encDataGen.open(out, new byte[BUFFER_SIZE]); PGPCompressedDataGenerator compressedDataGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); OutputStream compressedStream = compressedDataGen.open(encryptedStream); estimateFullOperationSize(encryptionSourceInfo, progress); writeFileToLiteralData(pIn, encryptionSourceInfo, compressedStream, outputType, new byte[BUFFER_SIZE], progress); compressedDataGen.close(); encryptedStream.close(); }
Example #7
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 5 votes |
private static PGPEncryptedDataGenerator buildEncryptedDataGenerator(Collection<PGPPublicKey> encKeys) { BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setSecureRandom(new SecureRandom()).setWithIntegrityPacket(true); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(builder); for (PGPPublicKey encKey : encKeys) { encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); } return encryptedDataGenerator; }
Example #8
Source File: Encryptor.java From jpgpj with MIT License | 5 votes |
/** * Builds a PGPEncryptedDataGenerator * for the configured encryption algorithm. */ protected PGPEncryptedDataGenerator buildEncryptor() { EncryptionAlgorithm encAlgo = getEncryptionAlgorithm(); BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(encAlgo.ordinal()); builder.setWithIntegrityPacket(true); return new PGPEncryptedDataGenerator(builder); }
Example #9
Source File: PGPEncrypt.java From peer-os with Apache License 2.0 | 5 votes |
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 #10
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 5 votes |
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 #11
Source File: BouncyCastleTest.java From nomulus with Apache License 2.0 | 5 votes |
@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.atInfo().log("Encrypted data: %s", 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); } } }
Example #12
Source File: PGPEncryptionUtil.java From OpenAs2App with BSD 2-Clause "Simplified" License | 5 votes |
public PGPEncryptionUtil(PGPPublicKey key, String payloadFilename, OutputStream out) throws PGPException, NoSuchProviderException, IOException { BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(payloadEncryptAlg); builder.setSecureRandom(new SecureRandom()); // create an encrypted payload and set the public key on the data // generator PGPEncryptedDataGenerator encryptGen = new PGPEncryptedDataGenerator(builder, supportPGP2_6); encryptGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key)); // open an output stream connected to the encrypted data generator // and have the generator write its data out to the ascii-encoding // stream byte[] buffer = new byte[BUFFER_SIZE]; // write data out using "ascii-armor" encoding if enabled - this is the normal PGP text output. encryptedOut = encryptGen.open(isArmor ? new ArmoredOutputStream(out) : out, buffer); // add a data compressor if compression is enabled else just write the encrypted stream to the literal PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); if (isCompressData) { // compress data. before encryption ... far better compression on unencrypted data. PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); compressedOut = compressor.open(encryptedOut); literalOut = literalGen.open(compressedOut, PGPLiteralDataGenerator.UTF8, payloadFilename, new Date(), new byte[BUFFER_SIZE]); } else { literalOut = literalGen.open(encryptedOut, PGPLiteralDataGenerator.UTF8, payloadFilename, new Date(), new byte[BUFFER_SIZE]); } }
Example #13
Source File: GPGFileEncryptor.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * 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); } }
Example #14
Source File: Encryptor.java From desktopclient-java with GNU General Public License v3.0 | 4 votes |
/** * 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 #15
Source File: BouncyCastleTest.java From nomulus with Apache License 2.0 | 3 votes |
@Test public void testEncryptDecrypt_KeyRingStyle() throws Exception { int bufferSize = 64 * 1024; // Alice loads Bob's "publicKey" into memory from her public key ring. PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY))); PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("[email protected]", true, true).next(); 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.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his chain of private keys into memory. PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY))); // 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); // Bob loads the private key to which the message is addressed. PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID())); try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }