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 ); } }
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException, UnsupportedEncodingException { PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath))); OutputStream encOut = encGen.open(bos, new byte[512]); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]); try { litOut.write("Test Message Without Compression".getBytes("UTF-8")); litOut.flush(); } finally { IOHelper.close(litOut); IOHelper.close(encOut, bos); } }
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; }
/** * 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 * @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])); }
@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()); }
public static byte[] encrypt( final byte[] secret, final PGPPublicKey... keys) throws CryptographyException { final ByteArrayOutputStream out; try (ByteArrayInputStream in = new ByteArrayInputStream(secret); ByteArrayOutputStream bOut = new ByteArrayOutputStream()) { final PGPLiteralDataGenerator literal = new PGPLiteralDataGenerator(); final PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.UNCOMPRESSED); 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(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()) .setProvider(PROVIDER)); for (final PGPPublicKey key : keys) { generator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key).setProvider(PROVIDER)); } out = new ByteArrayOutputStream(); final ArmoredOutputStream armor = new ArmoredOutputStream(out); final OutputStream cOut = generator.open(armor, bytes.length); cOut.write(bytes); cOut.close(); armor.close(); } catch (IOException | PGPException e) { throw new CryptographyException("Failed to encrypt.", e); } return out.toByteArray(); }
public void EncryptAndSign(OutputStream outputStream, String unencryptedFilename, boolean withArmor, boolean withIntegrityCheck) throws IOException, NoSuchProviderException { File unencryptedFile = new File(unencryptedFilename); if (outputStream == null) throw new IllegalArgumentException("outputStream is null"); if (unencryptedFilename == null || unencryptedFilename.isEmpty()) throw new IllegalArgumentException("Unencrypted filename is missing"); if (!unencryptedFile.exists()) throw new IllegalArgumentException("Unencrypted file is missing"); if (withArmor) { outputStream = new ArmoredOutputStream(outputStream); } try { //SIGNATURE GENERATION OBJECTS PGPSignatureGenerator pgpSignatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(encryptionKeys.getPublicKey().getAlgorithm(), sigHashAlgorithmTag).setProvider("BC")); pgpSignatureGenerator.init(PGPSignature.BINARY_DOCUMENT, encryptionKeys.getPrivateKey()); Iterator it = encryptionKeys.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator(); signatureSubpacketGenerator.setSignerUserID(false, (String)it.next()); pgpSignatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate()); } //ENCRYPTED GENERATOR OBJECTS PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(symmetricAlgorithm).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC")); encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKeys.getPublicKey()).setProvider("BC")); OutputStream encryptedOut = encryptedDataGenerator.open(outputStream, new byte[1 << 16]); //COMPRESSED GENERATOR OBJECTS PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( compressionAlgorithm); OutputStream compressedOut = compressedDataGenerator.open(encryptedOut); BCPGOutputStream bcpgOutputStream = new BCPGOutputStream(compressedOut); pgpSignatureGenerator.generateOnePassVersion(false).encode(bcpgOutputStream); //LITERAL DATA GENERATOR OBJECTS PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); OutputStream literalOut = literalDataGenerator.open(bcpgOutputStream, PGPLiteralData.BINARY, unencryptedFile); FileInputStream in = new FileInputStream(unencryptedFile); int ch; while ((ch = in.read()) > 0) { literalOut.write(ch); pgpSignatureGenerator.update((byte)ch); } pgpSignatureGenerator.generate().encode(bcpgOutputStream); literalOut.close(); bcpgOutputStream.close(); in.close(); compressedDataGenerator.close(); encryptedOut.close(); compressedOut.close(); if (withArmor) { outputStream.close(); } } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } }
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 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); } }
/** * Base constructor. * * @param encAlgorithm the symmetric algorithm to use. * @param rand source of randomness * @param provider the provider name to use for encryption algorithms. * @deprecated use constructor that takes a PGPDataEncryptor */ public PGPEncryptedDataGenerator( int encAlgorithm, SecureRandom rand, String provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setSecureRandom(rand).setProvider(provider)); }
/** * Base constructor. * * @param encAlgorithm the symmetric algorithm to use. * @param rand source of randomness * @param provider the provider to use for encryption algorithms. * @deprecated use constructor that takes a PGPDataEncryptorBuilder */ public PGPEncryptedDataGenerator( int encAlgorithm, SecureRandom rand, Provider provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setSecureRandom(rand).setProvider(provider)); }
/** * Creates a cipher stream which will have an integrity packet * associated with it. * * @param encAlgorithm * @param withIntegrityPacket * @param rand * @param provider * @deprecated use constructor that takes a PGPDataEncryptorBuilder */ public PGPEncryptedDataGenerator( int encAlgorithm, boolean withIntegrityPacket, SecureRandom rand, String provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setWithIntegrityPacket(withIntegrityPacket).setSecureRandom(rand).setProvider(provider)); }
/** * Creates a cipher stream which will have an integrity packet * associated with it. * * @param encAlgorithm * @param withIntegrityPacket * @param rand * @param provider * @deprecated use constructor that takes a PGPDataEncryptorBuilder */ public PGPEncryptedDataGenerator( int encAlgorithm, boolean withIntegrityPacket, SecureRandom rand, Provider provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setWithIntegrityPacket(withIntegrityPacket).setSecureRandom(rand).setProvider(provider)); }
/** * Base constructor. * * @param encAlgorithm the symmetric algorithm to use. * @param rand source of randomness * @param oldFormat PGP 2.6.x compatibility required. * @param provider the provider to use for encryption algorithms. * @deprecated use constructor that takes a PGPDataEncryptorBuilder */ public PGPEncryptedDataGenerator( int encAlgorithm, SecureRandom rand, boolean oldFormat, String provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setSecureRandom(rand).setProvider(provider), oldFormat); }
/** * Base constructor. * * @param encAlgorithm the symmetric algorithm to use. * @param rand source of randomness * @param oldFormat PGP 2.6.x compatibility required. * @param provider the provider to use for encryption algorithms. * @deprecated use constructor that takes a PGPDataEncryptorBuilder */ public PGPEncryptedDataGenerator( int encAlgorithm, SecureRandom rand, boolean oldFormat, Provider provider) { this(new JcePGPDataEncryptorBuilder(encAlgorithm).setSecureRandom(rand).setProvider(provider), oldFormat); }