List of usage examples for org.bouncycastle.openpgp PGPCompressedDataGenerator open
public OutputStream open(OutputStream out, byte[] buffer) throws IOException, PGPException
From source file:com.arcusx.simplepgp.PgpDataEncryptor.java
public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName, InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput) throws IOException, PGPException { PGPCompressedDataGenerator comData = null; try {//from w w w.j a v a 2s . com OutputStream out = dataOut; PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn); if (isArmoredOutput) { out = new ArmoredOutputStream(out); } BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(new SecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey)); OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]); // Initialize compressed data generator PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( PGPCompressedData.ZIP); OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]); // Initialize signature generator final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn); PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey); PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder( senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator(); signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey)); signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate()); signatureGenerator.generateOnePassVersion(false).encode(compressedOut); // Initialize literal data generator PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, dataFileName, new Date(), new byte[BUFFER_SIZE]); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = dataIn.read(buf)) > 0) { literalOut.write(buf, 0, len); signatureGenerator.update(buf, 0, len); } dataIn.close(); literalDataGenerator.close(); // generate the signature, compress, encrypt and write to the "out" stream signatureGenerator.generate().encode(compressedOut); compressedDataGenerator.close(); encryptedDataGenerator.close(); if (isArmoredOutput) { out.close(); } } finally { if (comData != null) { comData.close(); } IOUtils.closeQuietly(dataOut); } }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@Test public void testCompressEncryptDecryptDecompress_KeyRingStyle() throws Exception { int bufsz = 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("eric@bouncycastle.org", 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[bufsz])) { PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(ZIP); try (OutputStream output3 = kompressor.open(output2, new byte[bufsz])) { output3.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); }/*w ww. ja v a 2 s .c o m*/ } encryptedData = output.toByteArray(); } logger.info("Encrypted data: " + 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))) { pgpFact = new BcPGPObjectFactory(original); PGPCompressedData kompressedData = (PGPCompressedData) pgpFact.nextObject(); try (InputStream orig2 = kompressedData.getDataStream()) { assertThat(CharStreams.toString(new InputStreamReader(orig2, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } } }
From source file:google.registry.rde.Ghostryde.java
License:Open Source License
/** * Opens a new {@link Compressor} (Writing Step 2/3) * * <p>This is the second step in creating a ghostryde file. After this method, you'll want to * call {@link #openOutput(Compressor, String, DateTime)}. * * @param os is the value returned by {@link #openEncryptor(OutputStream, PGPPublicKey)}. * @throws IOException//from w ww . ja v a2s . c o m * @throws PGPException */ @CheckReturnValue public Compressor openCompressor(@WillNotClose Encryptor os) throws IOException, PGPException { PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(COMPRESSION_ALGORITHM); return new Compressor(kompressor.open(os, new byte[bufferSize])); }
From source file:org.apache.nifi.processors.standard.util.PGPUtil.java
License:Apache License
public static void encrypt(InputStream in, OutputStream out, String algorithm, String provider, int cipher, String filename, PGPKeyEncryptionMethodGenerator encryptionMethodGenerator) throws IOException, PGPException { if (StringUtils.isEmpty(algorithm)) { throw new IllegalArgumentException("The algorithm must be specified"); }// w w w .ja v a2s . com final boolean isArmored = EncryptContent.isPGPArmoredAlgorithm(algorithm); OutputStream output = out; if (isArmored) { output = new ArmoredOutputStream(out); } // Default value, do not allow null encryption if (cipher == PGPEncryptedData.NULL) { logger.warn("Null encryption not allowed; defaulting to AES-128"); cipher = PGPEncryptedData.AES_128; } try { // TODO: Can probably hard-code provider to BC and remove one method parameter PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(cipher).setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()).setProvider(provider)); encryptedDataGenerator.addMethod(encryptionMethodGenerator); try (OutputStream encryptedOut = encryptedDataGenerator.open(output, new byte[BUFFER_SIZE])) { PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( PGPCompressedData.ZIP, Deflater.BEST_SPEED); try (OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE])) { PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); try (OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, filename, new Date(), new byte[BUFFER_SIZE])) { final byte[] buffer = new byte[BLOCK_SIZE]; int len; while ((len = in.read(buffer)) > -1) { literalOut.write(buffer, 0, len); } } } } } finally { if (isArmored) { output.close(); } } }
From source file:org.kontalk.crypto.Coder.java
License:Open Source License
/** * Creates encrypted and signed message body. * Errors that may occur are saved to the message. * @param message//from www . j a va 2 s .co m * @return the encrypted and signed text. */ public static Optional<byte[]> processOutMessage(OutMessage message) { if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) { LOGGER.warning("message does not want to be encrypted"); return Optional.empty(); } LOGGER.info("encrypting message..."); // get keys KeysResult keys = getKeys(message.getUser()); if (keys.myKey == null || keys.otherKey == null) { message.setSecurityErrors(keys.errors); return Optional.empty(); } // secure the message against the most basic attacks using Message/CPIM String from = keys.myKey.getUserId(); String to = keys.otherKey.userID + "; "; String mime = "text/plain"; // TODO encrypt more possible content String text = message.getContent().getPlainText(); CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text); byte[] plainText; try { plainText = cpim.toByteArray(); } catch (UnsupportedEncodingException ex) { LOGGER.log(Level.WARNING, "UTF-8 not supported", ex); plainText = cpim.toString().getBytes(); } // 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); //for (PGPPublicKey rcpt : mRecipients) encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey)); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(plainText); try { // catch all io and pgp exceptions OutputStream encryptedOut = encGen.open(out, 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 = keys.myKey.getPublicEncryptionKey().getAlgorithm(); PGPSignatureGenerator sigGen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1)); sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey()); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, keys.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 = in.read(buf)) > 0) { literalOut.write(buf, 0, len); try { sigGen.update(buf, 0, len); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't read data for signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } } in.close(); literalGen.close(); // generate the signature, compress, encrypt and write to the "out" stream try { sigGen.generate().encode(compressedOut); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't create signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } compGen.close(); encGen.close(); } catch (IOException | PGPException ex) { LOGGER.log(Level.WARNING, "can't encrypt message", ex); message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR)); return Optional.empty(); } LOGGER.info("encryption successful"); return Optional.of(out.toByteArray()); }