Java Code Examples for org.bouncycastle.openpgp.PGPSignatureGenerator#init()

The following examples show how to use org.bouncycastle.openpgp.PGPSignatureGenerator#init() . 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: 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 2
Source File: Encryptor.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Builds a PGPSignatureGenerator for the specified key and content.
 */
protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta)
        throws PGPException {
    Subkey subkey = key.getSigning();

    log.info("using signing key {}", subkey);

    PGPContentSignerBuilder builder = buildSignerBuilder(
        subkey.getPublicKey().getAlgorithm(),
        signingAlgorithm.ordinal()
    );

    PGPSignatureGenerator generator = new PGPSignatureGenerator(builder);
    generator.init(meta.getSignatureType(), subkey.getPrivateKey());

    String uid = key.getSigningUid();
    if (!Util.isEmpty(uid)) {
        log.debug("using signing uid {}", uid);

        PGPSignatureSubpacketGenerator signer =
            new PGPSignatureSubpacketGenerator();
        signer.setSignerUserID(false, uid);
        generator.setHashedSubpackets(signer.generate());
    }

    return generator;
}
 
Example 3
Source File: PGPSign.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static PGPSignatureGenerator getSignatureGenerator( PGPPrivateKey privateKey, BCPGOutputStream bcOut )
        throws PGPException, IOException
{
    PGPSignatureGenerator signGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder( privateKey.getPublicKeyPacket().getAlgorithm(), PGPUtil.SHA1 )
                    .setProvider( "BC" ) );

    signGen.init( PGPSignature.BINARY_DOCUMENT, privateKey );

    signGen.generateOnePassVersion( false ).encode( bcOut );

    return signGen;
}
 
Example 4
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 5
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Signs a public key
 *
 * @param publicKeyRing a public key ring containing the single public key to sign
 * @param id the id we are certifying against the public key
 * @param secretKey the signing key
 * @param secretKeyPassword the signing key password
 *
 * @return a public key ring with the signed public key
 */
public static PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
                                              String secretKeyPassword ) throws PGPException
{
    try
    {
        PGPPublicKey oldKey = publicKeyRing.getPublicKey();

        PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider )
                                                     .build( secretKeyPassword.toCharArray() ) );

        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 ) );

        signatureGenerator.init( PGPSignature.DEFAULT_CERTIFICATION, pgpPrivKey );

        PGPSignature signature = signatureGenerator.generateCertification( id, oldKey );

        PGPPublicKey newKey = PGPPublicKey.addCertification( oldKey, signature );

        PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( publicKeyRing, oldKey );

        return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey );
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error signing public key", e );
    }
}
 
Example 6
Source File: RydePgpSigningOutputStream.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Create a signer that wraps {@code os} and generates a detached signature using
 * {@code signingKey}. After closing, you should call {@link #getSignature()} to get the detached
 * signature.
 *
 * @param os is the upstream {@link OutputStream} which is not closed by this object
 * @throws RuntimeException to rethrow {@link PGPException}
 */
public RydePgpSigningOutputStream(
    @WillNotClose OutputStream os,
    PGPKeyPair signingKey) {
  super("RydePgpSigningOutputStream", os, false);
  try {
    signer = new PGPSignatureGenerator(
        new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
    signer.init(BINARY_DOCUMENT, signingKey.getPrivateKey());
  } catch (PGPException e) {
    throw new RuntimeException(e);
  }
  addUserInfoToSignature(signingKey.getPublicKey(), signer);
}
 
Example 7
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignVerify_Detached() throws Exception {
  // Load the keys.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Sign the data and write signature data to "signatureFile".
  // Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated.
  PGPSignatureGenerator signer = new PGPSignatureGenerator(
      new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
  signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
  addUserInfoToSignature(publicKey, signer);
  signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  signer.generate().encode(output);
  byte[] signatureFileData = output.toByteArray();
  logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData));

  // Load algorithm information and signature data from "signatureFileData".
  PGPSignature sig;
  try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
    assertThat(sigList.size()).isEqualTo(1);
    sig = sigList.get(0);
  }

  // Use "onePass" and "sig" to verify "publicKey" signed the text.
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  assertThat(sig.verify()).isTrue();

  // Verify that they DIDN'T sign the text "hello monster".
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update("hello monster".getBytes(UTF_8));
  assertThat(sig.verify()).isFalse();
}
 
Example 8
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 9
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 10
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 11
Source File: RsaHeaderSignatureProcessor.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void feedHeader ( final ByteBuffer header )
{
    try
    {
        final BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.hashAlgorithm );
        final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( contentSignerBuilder );

        signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );

        if ( header.hasArray () )
        {
            signatureGenerator.update ( header.array (), header.position (), header.remaining () );
        }
        else
        {
            final byte[] buffer = new byte[header.remaining ()];
            header.get ( buffer );
            signatureGenerator.update ( buffer );
        }

        this.value = signatureGenerator.generate ().getEncoded ();
        logger.info ( "RSA HEADER: {}", this.value );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( e );
    }
}
 
Example 12
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 13
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 14
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 15
Source File: Encryptor.java    From desktopclient-java with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 16
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 3 votes vote down vote up
@Test
public void testSignVerify_OnePass() throws Exception {
  // Load the keys.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Sign the data and write signature data to "signatureFile".
  PGPSignatureGenerator signer = new PGPSignatureGenerator(
      new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
  signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
  addUserInfoToSignature(publicKey, signer);
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  signer.generateOnePassVersion(false).encode(output);
  signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  signer.generate().encode(output);
  byte[] signatureFileData = output.toByteArray();
  logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData));

  // Load algorithm information and signature data from "signatureFileData".
  PGPSignature sig;
  PGPOnePassSignature onePass;
  try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPOnePassSignatureList onePassList = (PGPOnePassSignatureList) pgpFact.nextObject();
    PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
    assertThat(onePassList.size()).isEqualTo(1);
    assertThat(sigList.size()).isEqualTo(1);
    onePass = onePassList.get(0);
    sig = sigList.get(0);
  }

  // Use "onePass" and "sig" to verify "publicKey" signed the text.
  onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  onePass.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  assertThat(onePass.verify(sig)).isTrue();

  // Verify that they DIDN'T sign the text "hello monster".
  onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  onePass.update("hello monster".getBytes(UTF_8));
  assertThat(onePass.verify(sig)).isFalse();
}