org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator. 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: 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 #2
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 #3
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 #4
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 #5
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
private static PGPKeyRingGenerator generateKeyRingGenerator( String id, char[] pass, int s2kcount, int keySize,
                                                             KeyPair keyPair ) throws PGPException
{
    // This object generates individual key-pairs.
    RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();

    // Boilerplate RSA parameters, no need to change anything
    // except for the RSA key-size (2048). You can use whatever
    // key-size makes sense for you -- 4096, etc.
    kpg.init( new RSAKeyGenerationParameters( BigInteger.valueOf( 0x10001 ), new SecureRandom(), keySize, 12 ) );

    // First create the master (signing) key with the generator.
    PGPKeyPair rsakp_sign = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() );
    // Then an encryption subkey.
    PGPKeyPair rsakp_enc = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() );

    keyPair.setPrimaryKeyId( Long.toHexString( rsakp_sign.getKeyID() ) );
    keyPair.setPrimaryKeyFingerprint( BytesToHex( rsakp_sign.getPublicKey().getFingerprint() ) );
    keyPair.setSubKeyId( Long.toHexString( rsakp_enc.getKeyID() ) );
    keyPair.setSubKeyFingerprint( BytesToHex( rsakp_enc.getPublicKey().getFingerprint() ) );

    // Add a self-signature on the id
    PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    // Add signed metadata on the signature.
    // 1) Declare its purpose
    signhashgen.setKeyFlags( false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER );
    // 2) Set preferences for secondary crypto algorithms to use
    //    when sending messages to this key.
    signhashgen.setPreferredSymmetricAlgorithms( false, new int[] {
            SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128,
            SymmetricKeyAlgorithmTags.CAST5, SymmetricKeyAlgorithmTags.TRIPLE_DES
    } );
    signhashgen.setPreferredHashAlgorithms( false, new int[] {
            HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512,
            HashAlgorithmTags.SHA224,
    } );
    signhashgen.setPreferredCompressionAlgorithms( false, new int[] {
            CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2, CompressionAlgorithmTags.ZIP
    } );
    // 3) Request senders add additional checksums to the
    //    message (useful when verifying unsigned messages.)
    signhashgen.setFeature( false, Features.FEATURE_MODIFICATION_DETECTION );

    // Create a signature on the encryption subkey.
    PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
    // Add metadata to declare its purpose
    enchashgen.setKeyFlags( false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE );

    // Objects used to encrypt the secret key.
    PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get( HashAlgorithmTags.SHA1 );

    // bcpg 1.48 exposes this API that includes s2kcount. Earlier
    // versions use a default of 0x60.
    PBESecretKeyEncryptor pske =
            ( new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.CAST5, sha1Calc, s2kcount ) ).build( pass );
    // Finally, create the keyring itself. The constructor
    // takes parameters that allow it to generate the self
    // signature.
    PGPKeyRingGenerator keyRingGen =
            new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc,
                    signhashgen.generate(), null,
                    new BcPGPContentSignerBuilder( rsakp_sign.getPublicKey().getAlgorithm(),
                            HashAlgorithmTags.SHA1 ), pske );

    // Add our encryption subkey, together with its signature.
    keyRingGen.addSubKey( rsakp_enc, enchashgen.generate(), null );
    return keyRingGen;
}
 
Example #6
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 #7
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 #8
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 #9
Source File: RydePgpSigningOutputStream.java    From nomulus with Apache License 2.0 3 votes vote down vote up
/**
 * Add user ID to signature file.
 *
 * <p>This adds information about the identity of the signer to the signature file. It's not
 * required, but I'm guessing it could be a lifesaver if somewhere down the road, people lose
 * track of the public keys and need to figure out how to verify a couple blobs. This would at
 * least tell them which key to download from the MIT keyserver.
 *
 * <p>But the main reason why I'm using this is because I copied it from the code of another
 * googler who was also uncertain about the precise reason why it's needed.
 */
private static void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) {
  Iterator<String> uidIter = publicKey.getUserIDs();
  if (uidIter.hasNext()) {
    PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator();
    spg.setSignerUserID(false, uidIter.next());
    signer.setHashedSubpackets(spg.generate());
  }
}
 
Example #10
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 3 votes vote down vote up
/**
 * Add user ID to signature file.
 *
 * <p>This adds information about the identity of the signer to the signature file. It's not
 * required, but I'm guessing it could be a lifesaver if somewhere down the road, people lose
 * track of the public keys and need to figure out how to verify a couple blobs. This would at
 * least tell them which key to download from the MIT keyserver.
 *
 * <p>But the main reason why I'm using this is because I copied it from the code of another
 * Googler who was also uncertain about the precise reason why it's needed.
 */
private void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) {
  Iterator<String> uidIter = publicKey.getUserIDs();
  if (uidIter.hasNext()) {
    PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator();
    spg.setSignerUserID(false, uidIter.next());
    signer.setHashedSubpackets(spg.generate());
  }
}