List of usage examples for org.bouncycastle.openpgp.operator.bc BcPGPDataEncryptorBuilder setWithIntegrityPacket
public BcPGPDataEncryptorBuilder setWithIntegrityPacket(boolean withIntegrityPacket)
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 {//ww w . ja v a 2s . co m 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:com.geoxp.oss.CryptoHelper.java
License:Apache License
public static byte[] encryptPGP(byte[] data, PGPPublicKey key, boolean armored, String name, int compressionAlgorithm, int encAlgorithm) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = armored ? new ArmoredOutputStream(baos) : baos; BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encAlgorithm); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(CryptoHelper.getSecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key)); try {/*ww w . j av a 2 s .c o m*/ OutputStream encout = encryptedDataGenerator.open(out, 1024); PGPCompressedDataGenerator pgpcdg = new PGPCompressedDataGenerator(compressionAlgorithm); OutputStream compout = pgpcdg.open(encout); PGPLiteralDataGenerator pgpldg = new PGPLiteralDataGenerator(false); OutputStream ldout = pgpldg.open(compout, PGPLiteralData.BINARY, name, data.length, PGPLiteralData.NOW); ldout.write(data); ldout.close(); compout.close(); encout.close(); out.close(); baos.close(); return baos.toByteArray(); } catch (PGPException pgpe) { throw new IOException(pgpe); } }
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 w ww. j a v a2 s .c o 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()); }