org.bouncycastle.bcpg.ArmoredOutputStream Java Examples

The following examples show how to use org.bouncycastle.bcpg.ArmoredOutputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 7 votes vote down vote up
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 );
    }
}
 
Example #2
Source File: KeyFilesOperationsPgpImpl.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exportPrivateKey(Key key, String targetFilePathname) {
	Preconditions.checkArgument(key != null && key.getKeyData() != null && key.getKeyInfo() != null,
			"Key must be providedand fully described");
	KeyDataPgp keyDataPgp = KeyDataPgp.get(key);
	Preconditions.checkArgument(keyDataPgp.getSecretKeyRing() != null, "KeyPair key wasn't provided");
	Preconditions.checkArgument(StringUtils.hasText(targetFilePathname), "targetFilePathname must be provided");
	Stack<OutputStream> os = new Stack<>();
	try {
		os.push(new FileOutputStream(targetFilePathname));
		if ("asc".equalsIgnoreCase(FilenameUtils.getExtension(targetFilePathname))) {
			os.push(new ArmoredOutputStream(os.peek()));
		}
		keyDataPgp.getSecretKeyRing().encode(os.peek());
		if (keyDataPgp.getPublicKeyRing() != null) {
			keyDataPgp.getPublicKeyRing().encode(os.peek());
		}
	} catch (Throwable t) {
		throw new RuntimeException(
				"Failed to export private key " + key.getKeyInfo().getUser() + " to " + targetFilePathname, t);
	} finally {
		while (!os.isEmpty()) {
			IoStreamUtils.safeClose(os.pop());
		}
	}
}
 
Example #3
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public byte[] signExternal(final String input) throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try {
    PGPSecretKey signKey = readSecretKey();
    PGPPrivateKey privKey = signKey.extractPrivateKey(
        new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
    PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
        new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
    sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey);

    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
      BCPGOutputStream bOut = new BCPGOutputStream(aOut);
      sigGenerator.update(input.getBytes(Charsets.UTF_8));
      sigGenerator.generate().encode(bOut);
    }
  }
  catch (PGPException ex) {
    throw new RuntimeException(ex);
  }

  return buffer.toByteArray();
}
 
Example #4
Source File: KeySerializer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize a PGPKeyPair
 *
 * <p>Use this to serialize a PGPPrivateKey as well (pairing it with the corresponding
 * PGPPublicKey), as private keys can't be serialized on their own.
 */
public static byte[] serializeKeyPair(PGPKeyPair keyPair) throws IOException, PGPException {
  try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
    // NOTE: We have to close the ArmoredOutputStream before calling the underlying OutputStream's
    // "toByteArray". Failing to do so would result in a truncated serialization as we took the
    // byte array before the ArmoredOutputStream wrote all the data.
    //
    // Even "flushing" the ArmoredOutputStream isn't enough - as there are parts that are only
    // written by the ArmoredOutputStream when it is closed: the "-----END PGP PRIVATE KEY
    // BLOCK-----" (or similar) footer.
    try (ArmoredOutputStream out = new ArmoredOutputStream(byteStream)) {
      new PGPSecretKey(
          keyPair.getPrivateKey(),
          keyPair.getPublicKey(),
          new JcaPGPDigestCalculatorProviderBuilder()
              .setProvider("BC")
              .build()
              .get(HashAlgorithmTags.SHA256),
          true,
          null).encode(out);
    }
    return byteStream.toByteArray();
  }
}
 
Example #5
Source File: KeySerializer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize a PGPPublicKey
 *
 * <p>The reason we're not using {@link PGPPublicKey#getEncoded()} is to use {@link
 * ArmoredOutputStream}.
 */
public static byte[] serializePublicKey(PGPPublicKey publicKey) throws IOException {
  try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
    // NOTE: We have to close the ArmoredOutputStream before calling the underlying OutputStream's
    // "toByteArray". Failing to do so would result in a truncated serialization as we took the
    // byte array before the ArmoredOutputStream wrote all the data.
    //
    // Even "flushing" the ArmoredOutputStream isn't enough - as there are parts that are only
    // written by the ArmoredOutputStream when it is closed: the "-----END PGP PRIVATE KEY
    // BLOCK-----" (or similar) footer.
    try (ArmoredOutputStream out = new ArmoredOutputStream(byteStream)) {
      publicKey.encode(out);
    }
    return byteStream.toByteArray();
  }
}
 
Example #6
Source File: EscrowDepositEncryptor.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Creates a {@code .ryde} and {@code .sig} file, provided an XML deposit file. */
void encrypt(String tld, Path xmlFile, Path outdir)
    throws IOException, XmlException {
  try (InputStream xmlFileInput = Files.newInputStream(xmlFile);
      BufferedInputStream xmlInput = new BufferedInputStream(xmlFileInput, PEEK_BUFFER_SIZE)) {
    DateTime watermark = RdeUtil.peekWatermark(xmlInput);
    String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, 0);
    Path rydePath = outdir.resolve(name + ".ryde");
    Path sigPath = outdir.resolve(name + ".sig");
    Path pubPath = outdir.resolve(tld + ".pub");
    PGPKeyPair signingKey = rdeSigningKey.get();
    try (OutputStream rydeOutput = Files.newOutputStream(rydePath);
        OutputStream sigOutput = Files.newOutputStream(sigPath);
        RydeEncoder rydeEncoder = new RydeEncoder.Builder()
            .setRydeOutput(rydeOutput, rdeReceiverKey.get())
            .setSignatureOutput(sigOutput, signingKey)
            .setFileMetadata(name, Files.size(xmlFile), watermark)
            .build()) {
      ByteStreams.copy(xmlInput, rydeEncoder);
    }
    try (OutputStream pubOutput = Files.newOutputStream(pubPath);
        ArmoredOutputStream ascOutput = new ArmoredOutputStream(pubOutput)) {
      signingKey.getPublicKey().encode(ascOutput);
    }
  }
}
 
Example #7
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String armorByteArrayToString( byte[] data ) throws PGPException
{
    try
    {
        ByteArrayOutputStream encOut = new ByteArrayOutputStream();
        ArmoredOutputStream armorOut = new ArmoredOutputStream( encOut );

        armorOut.write( data );
        armorOut.flush();
        armorOut.close();
        return new String( encOut.toByteArray() );
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error loading keyring", e );
    }
}
 
Example #8
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static byte[] armorByteArray( byte[] data ) throws PGPException
{
    try
    {
        ByteArrayOutputStream encOut = new ByteArrayOutputStream();
        ArmoredOutputStream armorOut = new ArmoredOutputStream( encOut );

        armorOut.write( data );
        armorOut.flush();
        armorOut.close();
        return encOut.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error loading keyring", e );
    }
}
 
Example #9
Source File: KeyFilesOperationsPgpImpl.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
private void savePublicKey(Key key, OutputStream outputStream, boolean saveAsArmored) {
	Preconditions.checkArgument(key != null && key.getKeyData() != null && key.getKeyInfo() != null,
			"Key must be providedand fully described");
	Stack<OutputStream> os = new Stack<>();
	try {
		os.push(outputStream);
		if (saveAsArmored) {
			os.push(new ArmoredOutputStream(os.peek()));
		}
		KeyDataPgp keyDataPgp = KeyDataPgp.get(key);
		if (keyDataPgp.getPublicKeyRing() != null) {
			keyDataPgp.getPublicKeyRing().encode(os.peek());
		} else {
			keyDataPgp.getSecretKeyRing().getPublicKey().encode(os.peek());
		}
	} catch (Throwable t) {
		throw new RuntimeException("Failed to save public key " + key.getKeyInfo().getUser(), t);
	} finally {
		while (!os.isEmpty()) {
			IoStreamUtils.safeClose(os.pop());
		}
	}
}
 
Example #10
Source File: Encryptor.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Wraps with stream that outputs ASCII-armored text - including configuring
 * its armor headers.
 *
 * @param meta The input plaintext {@link FileMetadata} - might be empty
 * (but not {@code null}).
 * @param out The {@link OutputStream} to wrap
 * @return The wrapped output stream - {@code null} if no wrapping.
 * @see #isAsciiArmored()
 * @see #isRemoveDefaultArmoredVersionHeader()
 * @see #setArmoredHeaders(Map) setArmoredHeaders
 * @see #addArmoredHeaders(Map) addArmoredHeaders
 * @see #updateArmoredHeader(String, String) updateArmoredHeader
 * @see #setArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback)
 */
protected OutputStream armor(OutputStream out, FileMetadata meta) {
    if (!isAsciiArmored()) {
        return null;
    }

    ArmoredOutputStream aos = new ArmoredOutputStream(out);
    if (isRemoveDefaultArmoredVersionHeader()) {
        aos.setHeader(ArmoredOutputStream.VERSION_HDR, null);
    }

    // add the global headers - if any
    armoredHeaders.forEach((name, value) -> aos.setHeader(name, value));

    // see if user wants to manipulate the headers
    EncryptedAsciiArmorHeadersCallback callback = getArmorHeadersCallback();
    if (callback != null) {
        EncryptedAsciiArmorHeadersManipulator manipulator =
            EncryptedAsciiArmorHeadersManipulator.wrap(aos);
        callback.prepareAsciiArmoredHeaders(this, meta, manipulator);
    }

    return aos;
}
 
Example #11
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
public Content getPublicKey() throws IOException, PGPException {
  PGPSecretKey signKey = readSecretKey();
  PGPPublicKey publicKey = signKey.getPublicKey();
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try (BCPGOutputStream os = new BCPGOutputStream(new ArmoredOutputStream(buffer))) {
    publicKey.encode(os);
  }
  return new Content(new BytesPayload(buffer.toByteArray(), AptMimeTypes.PUBLICKEY));
}
 
Example #12
Source File: PGPEncryptionUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public PGPEncryptionUtil(PGPPublicKey key, String payloadFilename, OutputStream out) throws PGPException, NoSuchProviderException, IOException {
    BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(payloadEncryptAlg);
    builder.setSecureRandom(new SecureRandom());
    // create an encrypted payload and set the public key on the data
    // generator
    PGPEncryptedDataGenerator encryptGen = new PGPEncryptedDataGenerator(builder, supportPGP2_6);

    encryptGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key));

    // open an output stream connected to the encrypted data generator
    // and have the generator write its data out to the ascii-encoding
    // stream
    byte[] buffer = new byte[BUFFER_SIZE];
    // write data out using "ascii-armor" encoding if enabled - this is the normal PGP text output.
    encryptedOut = encryptGen.open(isArmor ? new ArmoredOutputStream(out) : out, buffer);

    // add a data compressor if compression is enabled else just write the encrypted stream to the literal
    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    if (isCompressData) {
        // compress data. before encryption ... far better compression on unencrypted data.
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        compressedOut = compressor.open(encryptedOut);
        literalOut = literalGen.open(compressedOut, PGPLiteralDataGenerator.UTF8, payloadFilename, new Date(), new byte[BUFFER_SIZE]);
    } else {
        literalOut = literalGen.open(encryptedOut, PGPLiteralDataGenerator.UTF8, payloadFilename, new Date(), new byte[BUFFER_SIZE]);
    }
}
 
Example #13
Source File: SigningStream.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
protected void testInit () throws IOException
{
    if ( this.initialized )
    {
        return;
    }

    this.initialized = true;

    try
    {
        this.signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.digestAlgorithm ) );
        this.signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );

        this.armoredOutput = new ArmoredOutputStream ( this.stream );
        if ( this.version != null )
        {
            this.armoredOutput.setHeader ( "Version", this.version );
        }

        if ( this.inline )
        {
            this.armoredOutput.beginClearText ( this.digestAlgorithm );
        }
    }
    catch ( final PGPException e )
    {
        throw new IOException ( e );
    }
}
 
Example #14
Source File: AbstractSecretKeySigningService.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void printPublicKey ( final OutputStream out ) throws IOException
{
    final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out );
    armoredOutput.setHeader ( "Version", VersionInformation.VERSIONED_PRODUCT );

    final PGPPublicKey pubKey = this.secretKey.getPublicKey ();
    pubKey.encode ( new BCPGOutputStream ( armoredOutput ) );
    armoredOutput.close ();
}
 
Example #15
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] signInline(final String input) throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try {
    PGPSecretKey signKey = readSecretKey();
    PGPPrivateKey privKey = signKey.extractPrivateKey(
        new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
    PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
        new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
    sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey);

    Iterator<String> userIds = signKey.getUserIDs();
    if (userIds.hasNext()) {
      PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
      sigSubpacketGenerator.setSignerUserID(false, userIds.next());
      sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
    }

    String[] lines = input.split("\r?\n");
    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
      aOut.beginClearText(PGPUtil.SHA256);

      boolean firstLine = true;
      for (String line : lines) {
        String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
        sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
        aOut.write((line + "\n").getBytes(Charsets.UTF_8));
        firstLine = false;
      }
      aOut.endClearText();

      BCPGOutputStream bOut = new BCPGOutputStream(aOut);
      sigGenerator.generate().encode(bOut);
    }
  }
  catch (PGPException ex) {
    throw new RuntimeException(ex);
  }
  return buffer.toByteArray();
}
 
Example #16
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public Content getPublicKey() throws IOException {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  PGPSecretKey signKey = readSecretKey();
  PGPPublicKey publicKey = signKey.getPublicKey();
  try (BCPGOutputStream os = new BCPGOutputStream(new ArmoredOutputStream(buffer))) {
    publicKey.encode(os);
  }

  return new Content(new BytesPayload(buffer.toByteArray(), AptMimeTypes.PUBLICKEY));
}
 
Example #17
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] signExternal(String input) throws IOException, PGPException {
  PGPSecretKey signKey = readSecretKey();
  PGPPrivateKey privKey = signKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
  PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
      new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
  sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey);

  ByteArrayOutputStream buffer = new ByteArrayOutputStream();

  try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
    BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    sigGenerator.update(input.getBytes(Charsets.UTF_8));
    sigGenerator.generate().encode(bOut);
  }

  return buffer.toByteArray();
}
 
Example #18
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
public byte[] signInline(String input) throws IOException, PGPException {
  PGPSecretKey signKey = readSecretKey();
  PGPPrivateKey privKey = signKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
  PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
      new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
  sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey);

  @SuppressWarnings("unchecked")
  Iterator<String> userIds = signKey.getUserIDs();
  if (userIds.hasNext()) {
    PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
    sigSubpacketGenerator.setSignerUserID(false, userIds.next());
    sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
  }

  String[] lines = input.split("\r?\n");
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
    aOut.beginClearText(PGPUtil.SHA256);

    boolean firstLine = true;
    for (String line : lines) {
      String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
      sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
      aOut.write((line + "\n").getBytes(Charsets.UTF_8));
      firstLine = false;
    }
    aOut.endClearText();

    BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    sigGenerator.generate().encode(bOut);
  }
  return buffer.toByteArray();
}
 
Example #19
Source File: PGPKeyUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * *********************************************************************************** Exports given public key as
 * ASCII armored text.
 *
 * @param pgpKey key to export
 *
 * @return ASCII armored key text
 */
public static String exportAscii( PGPPublicKey pgpKey ) throws PGPException
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try ( OutputStream os = new ArmoredOutputStream( out ) )
    {
        pgpKey.encode( os );
    }
    catch ( IOException ex )
    {
        throw new PGPException( "Failed to export PGP key", ex );
    }
    return out.toString();
}
 
Example #20
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String encryptText(String sourceText, Collection<Key> recipients) {
	try {
		PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
				buildKeysListForEncryption(recipients));

		SourceInfo encryptionSourceInfo = new SourceInfo("text.asc", sourceText.length(),
				System.currentTimeMillis());
		ByteArrayOutputStream pOut = new ByteArrayOutputStream();
		ByteArrayInputStream pIn = new ByteArrayInputStream(sourceText.getBytes("UTF-8"));
		ArmoredOutputStream armoredOut = new ArmoredOutputStream(pOut);
		doEncryptFile(pIn, encryptionSourceInfo, armoredOut, dataGenerator, null, PGPLiteralData.BINARY);
		pIn.close();
		armoredOut.flush();
		armoredOut.close();
		return pOut.toString();
	} catch (Throwable t) {
		throw new RuntimeException("Encryption failed", t);
	}
}
 
Example #21
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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 );
    }
}
 
Example #22
Source File: PGPSign.java    From peer-os with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example #23
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static byte[] clearSign( byte[] message, PGPSecretKey pgpSecKey, char[] pass, String digestName )
        throws IOException, PGPException, SignatureException
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int digest;

    if ( "SHA256".equals( digestName ) )
    {
        digest = PGPUtil.SHA256;
    }
    else if ( "SHA384".equals( digestName ) )
    {
        digest = PGPUtil.SHA384;
    }
    else if ( "SHA512".equals( digestName ) )
    {
        digest = PGPUtil.SHA512;
    }
    else if ( "MD5".equals( digestName ) )
    {
        digest = PGPUtil.MD5;
    }
    else if ( "RIPEMD160".equals( digestName ) )
    {
        digest = PGPUtil.RIPEMD160;
    }
    else
    {
        digest = PGPUtil.SHA1;
    }

    PGPPrivateKey pgpPrivKey =
            pgpSecKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( "BC" ).build( pass ) );
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder( pgpSecKey.getPublicKey().getAlgorithm(), digest ).setProvider( "BC" ) );
    PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

    sGen.init( PGPSignature.CANONICAL_TEXT_DOCUMENT, pgpPrivKey );

    Iterator it = pgpSecKey.getPublicKey().getUserIDs();
    if ( it.hasNext() )
    {
        spGen.setSignerUserID( false, ( String ) it.next() );
        sGen.setHashedSubpackets( spGen.generate() );
    }

    InputStream fIn = new ByteArrayInputStream( message );
    ArmoredOutputStream aOut = new ArmoredOutputStream( out );

    aOut.beginClearText( digest );

    //
    // note the last \n/\r/\r\n in the file is ignored
    //
    ByteArrayOutputStream lineOut = new ByteArrayOutputStream();
    int lookAhead = readInputLine( lineOut, fIn );

    processLine( aOut, sGen, lineOut.toByteArray() );

    if ( lookAhead != -1 )
    {
        do
        {
            lookAhead = readInputLine( lineOut, lookAhead, fIn );

            sGen.update( ( byte ) '\r' );
            sGen.update( ( byte ) '\n' );

            processLine( aOut, sGen, lineOut.toByteArray() );
        }
        while ( lookAhead != -1 );
    }

    fIn.close();

    aOut.endClearText();

    BCPGOutputStream bOut = new BCPGOutputStream( aOut );

    sGen.generate().encode( bOut );

    aOut.close();

    return out.toByteArray();
}
 
Example #24
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
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 );
    }
}
 
Example #25
Source File: AbstractSecretKeySigningService.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void sign ( final InputStream in, final OutputStream out, final boolean inline ) throws Exception
{
    final int digest = HashAlgorithmTags.SHA1;
    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), digest ) );

    if ( inline )
    {
        signatureGenerator.init ( PGPSignature.CANONICAL_TEXT_DOCUMENT, this.privateKey );
    }
    else
    {
        signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );
    }

    final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out );
    armoredOutput.setHeader ( "Version", VersionInformation.VERSIONED_PRODUCT );

    if ( inline )
    {
        armoredOutput.beginClearText ( digest );

        final LineNumberReader lnr = new LineNumberReader ( new InputStreamReader ( in, StandardCharsets.UTF_8 ) );

        String line;
        while ( ( line = lnr.readLine () ) != null )
        {
            if ( lnr.getLineNumber () > 1 )
            {
                signatureGenerator.update ( NL_DATA );
            }

            final byte[] data = trimTrailing ( line ).getBytes ( StandardCharsets.UTF_8 );

            if ( inline )
            {
                armoredOutput.write ( data );
                armoredOutput.write ( NL_DATA );
            }
            signatureGenerator.update ( data );
        }

        armoredOutput.endClearText ();
    }
    else
    {

        final byte[] buffer = new byte[4096];
        int rc;
        while ( ( rc = in.read ( buffer ) ) >= 0 )
        {
            signatureGenerator.update ( buffer, 0, rc );
        }
    }

    final PGPSignature signature = signatureGenerator.generate ();
    signature.encode ( new BCPGOutputStream ( armoredOutput ) );

    armoredOutput.close ();
}
 
Example #26
Source File: PGPEncrypt.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static byte[] encrypt( byte data[], PGPPublicKey publicKey ) throws IOException, PGPException
{
    byte[] compressedData = compress( data );

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    ArmoredOutputStream aos = new ArmoredOutputStream( bos );

    OutputStream encOut = getEncryptedGenerator( publicKey ).open( aos, compressedData.length );

    encOut.write( compressedData );

    encOut.close();

    aos.close();

    return bos.toByteArray();
}
 
Example #27
Source File: EncryptedAsciiArmorHeadersManipulator.java    From jpgpj with MIT License 2 votes vote down vote up
/**
 * Wraps an {@link ArmoredOutputStream}
 *
 * @param aos The stream to wrap - ignored if {@code null}
 * @return The manipulator wrapping
 */
static EncryptedAsciiArmorHeadersManipulator wrap(ArmoredOutputStream aos) {
    return (aos == null) ? EMPTY : (name, value) -> aos.setHeader(name, value);
}