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 ); } }
/** * Wraps with stream that outputs compressed data packet. */ protected OutputStream compress(OutputStream out, FileMetadata meta) throws IOException, PGPException { if (log.isLoggable(Level.FINEST)) log.finest("using compression algorithm " + compressionAlgorithm + " -" + compressionLevel); if (compressionAlgorithm == CompressionAlgorithm.Uncompressed || compressionLevel < 1 || compressionLevel > 9) return null; int algo = compressionAlgorithm.ordinal(); int level = compressionLevel; byte[] buf = getCompressionBuffer(meta); return new PGPCompressedDataGenerator(algo, level).open(out, buf); }
@Test public void testCompressDecompress() throws Exception { // Compress the data and write out a compressed data OpenPGP message. byte[] data; try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(ZIP); try (OutputStream output2 = kompressor.open(output)) { output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); } data = output.toByteArray(); } logger.info("Compressed data: " + dumpHex(data)); // Decompress the data. try (ByteArrayInputStream input = new ByteArrayInputStream(data)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPCompressedData object = (PGPCompressedData) pgpFact.nextObject(); InputStream original = object.getDataStream(); // Closing this would close input. assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); assertThat(pgpFact.nextObject()).isNull(); } }
private static byte[] compress(byte[] clearData, String fileName, int algorithm) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm); OutputStream cos = comData.open(bOut); // open it with the final destination PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); // we want to generate compressed data. This might be a user option later, // in which case we would pass in bOut. OutputStream pOut = lData.open(cos, // the compressed output stream PGPLiteralData.BINARY, fileName, // "filename" to store clearData.length, // length of clear data new Date() // current time ); pOut.write(clearData); pOut.close(); comData.close(); return bOut.toByteArray(); }
static byte[] compressFile(String fileName, int algorithm) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm); PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName)); comData.close(); return bOut.toByteArray(); }
/** * Encrypt the given file * @param unencryptedFileName - Name of the unecrypted file * @param encryptedFileName - Name of the encrypted file, will have .enc as extension * @throws IOException * @throws NoSuchProviderException * @throws PGPException * @throws CryptDecryptException */ public void encryptFile(final String unencryptedFileName, final String encryptedFileName) throws IOException, NoSuchProviderException, PGPException, CryptDecryptException { if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Entry"); // Initialise PGP provider and read public key if(!initialized) initialise(false); FileOutputStream encrytedFile = new FileOutputStream(encryptedFileName); // Compress the input plain text file in ZIP format. ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(unencryptedFileName) ); comData.close(); // Encrypt the file using Triple-DES algorithm BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES); dataEncryptor.setWithIntegrityPacket(false); dataEncryptor.setSecureRandom(new SecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); byte[] bytes = bOut.toByteArray(); OutputStream cOut = encryptedDataGenerator.open(encrytedFile, bytes.length); cOut.write(bytes); cOut.close(); encrytedFile.close(); if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Exit"); }
private static OutputStream createDelegate(int bufferSize, OutputStream os) { try { return new PGPCompressedDataGenerator(ZIP).open(os, new byte[bufferSize]); } catch (IOException | PGPException e) { throw new RuntimeException(e); } }
@Test public void testExceptionDecryptorIncorrectInputFormatSymmetricEncryptedData() throws Exception { byte[] payload = "Not Correct Format".getBytes("UTF-8"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator("pw".toCharArray())); OutputStream encOut = encGen.open(bos, new byte[1024]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP); OutputStream comOut = new BufferedOutputStream(comData.open(encOut)); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[1024]); litOut.write(payload); litOut.flush(); litOut.close(); comOut.close(); encOut.close(); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkeyUnmarshal", bos.toByteArray()); assertMockEndpointsSatisfied(); checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format."); }
public String encryptString(PGPPublicKey key, String clearText) throws IOException, PGPException { byte[] clearData = clearText.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream encOut = new ByteArrayOutputStream(); OutputStream out = new ArmoredOutputStream(encOut); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator( PGPCompressedDataGenerator.ZIP); OutputStream cos = comData.open(bOut); PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); OutputStream pOut = lData.open(cos, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, clearData.length, new Date()); pOut.write(clearData); lData.close(); comData.close(); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()).setProvider(BouncyCastleProvider.PROVIDER_NAME)); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); byte[] bytes = bOut.toByteArray(); OutputStream cOut = encGen.open(out, bytes.length); cOut.write(bytes); cOut.close(); out.close(); return new String(encOut.toByteArray()); }
private void testCompression( int type) throws IOException, PGPException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator cPacket = new PGPCompressedDataGenerator(type); OutputStream out = cPacket.open(new UncloseableOutputStream(bOut)); out.write("hello world!".getBytes()); out.close(); PGPObjectFactory pgpFact = new PGPObjectFactory(bOut.toByteArray()); PGPCompressedData c1 = (PGPCompressedData)pgpFact.nextObject(); InputStream pIn = c1.getDataStream(); bOut.reset(); int ch; while ((ch = pIn.read()) >= 0) { bOut.write(ch); } if (!areEqual(bOut.toByteArray(), "hello world!".getBytes())) { fail("compression test failed"); } }
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 ); } }
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 ); } }
public static byte[] sign( byte data[], PGPPrivateKey privateKey ) throws IOException, PGPException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ArmoredOutputStream aos = new ArmoredOutputStream( bos ); PGPCompressedDataGenerator compressGen = new PGPCompressedDataGenerator( PGPCompressedData.ZLIB ); BCPGOutputStream bcOut = new BCPGOutputStream( compressGen.open( aos ) ); PGPSignatureGenerator signGen = getSignatureGenerator( privateKey, bcOut ); produceSign( data, bcOut, signGen ); compressGen.close(); aos.close(); return bos.toByteArray(); }
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(); }
public static byte[] signFile(byte[] content, String fileName, InputStream keyIn, char[] pass, Provider securityProvider, TimeProvider timeProvider) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); ArmoredOutputStream armoredOut = new ArmoredOutputStream(byteArrayOut); PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); try { PGPSecretKey pgpSecretKey = BouncyCastlePGPExampleUtil.readSecretKey(keyIn); PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(pass, securityProvider); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(pgpSecretKey .getPublicKey().getAlgorithm(), PGPUtil.SHA1, securityProvider); signatureGenerator.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey); Iterator<?> it = pgpSecretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { //get first user ID PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, (String) it.next()); signatureGenerator.setHashedSubpackets(spGen.generate()); } else { throw new PGPException("No user ID found in the public key of the certificate."); } BCPGOutputStream bOut = new BCPGOutputStream(compressedDataGenerator.open(armoredOut)); signatureGenerator.generateOnePassVersion(false).encode(bOut); OutputStream literalOut = literalDataGenerator.open(bOut, PGPLiteralData.BINARY, fileName, timeProvider.nowDate(), content); literalOut.write(content); signatureGenerator.update(content); signatureGenerator.generate().encode(bOut); } finally { literalDataGenerator.close(); compressedDataGenerator.close(); armoredOut.close(); } return byteArrayOut.toByteArray(); }
private PGPCompressedDataGenerator createCompressedDataGenerator() { return new PGPCompressedDataGenerator(getCompressionAlgorithm().getCompressionAlgorithmTag()); }
public void run(final char[] passphrase, final InputStream inputStream, final OutputStream outputStream) throws IOException, CryptoException { try { final OutputStream armor = new ArmoredOutputStream(outputStream); final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_128).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(new BouncyCastleProvider())); encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setSecureRandom(new SecureRandom()).setProvider( new BouncyCastleProvider())); final OutputStream encryptedOut = encryptedDataGenerator.open(armor, 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(new BouncyCastleProvider()) .build(passphrase)); final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey() .getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(new BouncyCastleProvider())); 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, "", new Date(), new byte[4096]); final byte[] buf = new byte[4096]; for (int len = 0; (len = inputStream.read(buf)) > 0;) { literalOut.write(buf, 0, len); signatureGenerator.update(buf, 0, len); } literalDataGenerator.close(); signatureGenerator.generate().encode(compressedOut); compressedDataGenerator.close(); encryptedDataGenerator.close(); armor.close(); } catch (final Exception e) { throw new CryptoException(e); } }
/** * 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(); }
/** * 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 * @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])); }