List of usage examples for org.bouncycastle.openpgp PGPEncryptedDataGenerator PGPEncryptedDataGenerator
public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder)
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 ww w .ja va 2s .c om 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.bekwam.resignator.util.CryptUtils.java
License:Apache License
private byte[] encrypt(byte[] clearData, char[] passPhrase) throws IOException, PGPException, NoSuchProviderException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); //// w ww . j a va 2 s. c o m // armor makes the encrypted output more readable (includes header, footer, printable chars) // OutputStream out = bOut; out = new ArmoredOutputStream(out); // // The standard jre installation limits keysize to 128. Use the unlimited jars to go higher. // PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_128) .setSecureRandom(new SecureRandom()).setProvider("BC")); encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase).setProvider("BC")); OutputStream encOut = encGen.open(out, clearData.length); encOut.write(clearData); encOut.close(); out.close(); return bOut.toByteArray(); }
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 {//from w w w .j av a 2 s . com 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:com.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
public void signEncryptMessage(InputStream in, OutputStream out, String jid) throws IOException, PGPException, SignatureException { out = new ArmoredOutputStream(out); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SYMM_ALG) .setWithIntegrityPacket(true).setSecureRandom(rand).setProvider(PROVIDER)); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(keys.get(jid)).setProvider(PROVIDER)); OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]); OutputStream compressedData = new PGPCompressedDataGenerator(COMP_ALG).open(encryptedOut); PGPSignatureGenerator sGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(kp.getPrivateKey().getPublicKeyPacket().getAlgorithm(), HASH_ALG) .setProvider(PROVIDER)); sGen.init(PGPSignature.BINARY_DOCUMENT, kp.getPrivateKey()); sGen.generateOnePassVersion(false).encode(compressedData); OutputStream finalOut = new PGPLiteralDataGenerator().open(compressedData, PGPLiteralData.BINARY, "", new Date(), new byte[BUFFER_SIZE]); byte[] buf = new byte[BUFFER_SIZE]; int len;/* w w w.j a v a 2 s .c o m*/ while ((len = in.read(buf)) > 0) { finalOut.write(buf, 0, len); sGen.update(buf, 0, len); } in.close(); finalOut.close(); sGen.generate().encode(compressedData); compressedData.close(); encryptedOut.close(); out.close(); }
From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java
License:Open Source License
public String getEncryptedMessage(byte[] data) { Security.addProvider(new BouncyCastleProvider()); try {/* w w w . ja v a 2s . com*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = new ArmoredOutputStream(baos); byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()).setProvider("BC")); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC")); OutputStream cOut = encGen.open(out, compressedData.length); cOut.write(compressedData); cOut.close(); out.close(); baos.flush(); return new String(baos.toByteArray()); } catch (PGPException | IOException e) { e.printStackTrace(); } return null; }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Encrypt plaintext message using public key from publickeyFile. * * @param message/*from w w w. j a va2 s . c om*/ * the message * * @return the string */ private String encrypt(InputStream publicKeyInputStream, String message) throws PGPException, IOException, NoSuchProviderException { // find the PGP key in the file PGPPublicKey publicKey = findPublicGPGKey(publicKeyInputStream); if (publicKey == null) { System.err.println("Did not find public GPG key"); return null; } // Encode the string into bytes using utf-8 byte[] utf8Bytes = message.getBytes(OS.UTF_8); ByteArrayOutputStream compressedOutput = new ByteArrayOutputStream(); // compress bytes with zip PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); // the reason why we compress here is GPG not being able to decrypt our message input but if we do not compress. // I guess pkzip compression also encodes only to GPG-friendly characters. PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP); try { OutputStream literalDataOutput = literalDataGenerator.open(compressedOutput, PGPLiteralData.BINARY, "_CONSOLE", utf8Bytes.length, new Date()); // update bytes in the stream literalDataOutput.write(utf8Bytes); } catch (IOException e) { // catch but close the streams in finally throw e; } finally { compressedDataGenerator.close(); IO.close(compressedOutput); } SecureRandom random = new SecureRandom(); // now we have zip-compressed bytes byte[] compressedBytes = compressedOutput.toByteArray(); BcPGPDataEncryptorBuilder bcPGPDataEncryptorBuilder = new BcPGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true).setSecureRandom(random); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(bcPGPDataEncryptorBuilder); // use public key to encrypt data BcPublicKeyKeyEncryptionMethodGenerator encKeyGen = new BcPublicKeyKeyEncryptionMethodGenerator(publicKey) .setSecureRandom(random); encryptedDataGenerator.addMethod(encKeyGen); // literalDataOutput --> compressedOutput --> ArmoredOutputStream --> ByteArrayOutputStream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ArmoredOutputStream armoredOut = new ArmoredOutputStream(byteArrayOutputStream); OutputStream encryptedOutput = null; try { encryptedOutput = encryptedDataGenerator.open(armoredOut, compressedBytes.length); encryptedOutput.write(compressedBytes); } catch (IOException e) { throw e; } catch (PGPException e) { throw e; } finally { IO.close(encryptedOutput); IO.close(armoredOut); } String encrypted = new String(byteArrayOutputStream.toByteArray()); System.err.println("Message: " + message); System.err.println("Encrypted: " + encrypted); return encrypted; }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@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)); }//from w w w . ja v a2s. co m encryptedData = output.toByteArray(); } logger.info("Encrypted data: " + 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); } } }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@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("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[bufferSize])) { output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); }/*from w w w . j a va 2 s . com*/ 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))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }
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)); }//from w w w. 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 Encryptor} (Writing Step 1/3) * * <p>This is the first step in creating a ghostryde file. After this method, you'll want to * call {@link #openCompressor(Encryptor)}. * * @param os is the upstream {@link OutputStream} to which the result is written. * @param publicKey is the public encryption key of the recipient. * @throws IOException//from w ww.j a va2s. c om * @throws PGPException */ @CheckReturnValue public Encryptor openEncryptor(@WillNotClose OutputStream os, PGPPublicKey publicKey) throws IOException, PGPException { PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(CIPHER).setWithIntegrityPacket(USE_INTEGRITY_PACKET) .setSecureRandom(getRandom()).setProvider(PROVIDER_NAME)); encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); return new Encryptor(encryptor.open(os, new byte[bufferSize])); }