org.bouncycastle.openpgp.PGPPublicKeyRingCollection Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPPublicKeyRingCollection. 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: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void importPublicKey(BareJid owner, PGPPublicKeyRing publicKeys) throws IOException, PGPException, MissingUserIdOnKeyException {

    if (!new BareJidUserId.PubRingSelectionStrategy().accept(owner, publicKeys)) {
        throw new MissingUserIdOnKeyException(owner, new OpenPgpV4Fingerprint(publicKeys));
    }

    PGPPublicKeyRing importKeys = BCUtil.removeUnassociatedKeysFromKeyRing(publicKeys, publicKeys.getPublicKey());

    PGPPublicKeyRingCollection publicKeyRings = getPublicKeysOf(owner);
    try {
        if (publicKeyRings != null) {
            publicKeyRings = PGPPublicKeyRingCollection.addPublicKeyRing(publicKeyRings, importKeys);
        } else {
            publicKeyRings = BCUtil.keyRingsToKeyRingCollection(importKeys);
        }
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.INFO, "Skipping public key ring " + Long.toHexString(importKeys.getPublicKey().getKeyID()) +
                " as it is already in the key ring of " + owner.toString());
    }
    this.publicKeyRingCollections.put(owner, publicKeyRings);
    writePublicKeysOf(owner, publicKeyRings);
}
 
Example #2
Source File: FileBasedOpenPgpKeyStore.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void writePublicKeysOf(BareJid owner, PGPPublicKeyRingCollection publicKeys) throws IOException {
    File file = getPublicKeyRingPath(owner);

    if (publicKeys == null) {
        FileUtils.maybeDeleteFileOrThrow(file);
        return;
    }

    OutputStream outputStream = null;
    try {
        outputStream = FileUtils.prepareFileOutputStream(file);
        publicKeys.encode(outputStream);
    } finally {
        CloseableUtil.maybeClose(outputStream, LOGGER);
    }
}
 
Example #3
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Search for public key on keyring based on a substring (like an email address).
 *
 * @throws VerifyException if the key couldn't be found.
 * @see #lookupKeyPair
 */
public static PGPPublicKey lookupPublicKey(
    PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) {
  try {
    Iterator<PGPPublicKeyRing> results =
        keyring.getKeyRings(checkNotNull(query, "query"), true, true);
    verify(results.hasNext(), "No public key found matching substring: %s", query);
    while (results.hasNext()) {
      Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want);
      if (result.isPresent()) {
        return result.get();
      }
    }
    throw new VerifyException(String.format(
        "No public key (%s) found matching substring: %s", want, query));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Public key lookup failed for query: %s", query), e);
  }
}
 
Example #4
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #lookupPublicKey} but also retrieves the associated private key.
 *
 * @throws VerifyException if either keys couldn't be found.
 * @see #lookupPublicKey
 */
public static PGPKeyPair lookupKeyPair(
    PGPPublicKeyRingCollection publics,
    PGPSecretKeyRingCollection privates,
    String query,
    KeyRequirement want) {
  PGPPublicKey publicKey = lookupPublicKey(publics, query, want);
  PGPPrivateKey privateKey;
  try {
    PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()),
        "Keyring missing private key associated with public key id: %x (query '%s')",
        publicKey.getKeyID(), query);
    // We do not support putting a password on the private key so we're just going to
    // put char[0] here.
    privateKey = secret.extractPrivateKey(
        new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(new char[0]));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Could not load PGP private key for: %s", query), e);
  }
  return new PGPKeyPair(publicKey, privateKey);
}
 
Example #5
Source File: OpenPgpContact.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Return a {@link Set} of {@link OpenPgpV4Fingerprint}s of all keys in {@code publicKeys}, which are marked with the
 * {@link OpenPgpTrustStore.Trust} of {@code trust}.
 *
 * @param publicKeys {@link PGPPublicKeyRingCollection} of keys which are iterated.
 * @param trust {@link OpenPgpTrustStore.Trust} state.
 * @return {@link Set} of fingerprints
 *
 * @throws IOException IO error
 */
public Set<OpenPgpV4Fingerprint> getFingerprintsOfKeysWithState(PGPPublicKeyRingCollection publicKeys,
                                                                OpenPgpTrustStore.Trust trust)
        throws IOException {
    PGPPublicKeyRingCollection keys = getPublicKeysOfTrustState(publicKeys, trust);
    Set<OpenPgpV4Fingerprint> fingerprints = new HashSet<>();

    if (keys == null) {
        return fingerprints;
    }

    for (PGPPublicKeyRing ring : keys) {
        fingerprints.add(new OpenPgpV4Fingerprint(ring));
    }

    return fingerprints;
}
 
Example #6
Source File: AptITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public boolean verifyReleaseFilePgpSignature(final InputStream signedData,
                                             final InputStream signature,
                                             final InputStream publicKey)
    throws Exception
{
  PGPObjectFactory pgpFact =
      new PGPObjectFactory(PGPUtil.getDecoderStream(signature), new JcaKeyFingerprintCalculator());
  PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0);

  PGPPublicKeyRingCollection pgpPubRingCollection =
      new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKey),
          new JcaKeyFingerprintCalculator());

  PGPPublicKey key = pgpPubRingCollection.getPublicKey(sig.getKeyID());
  sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key);
  byte[] buff = new byte[1024];
  int read = 0;
  while ((read = signedData.read(buff)) != -1) {
    sig.update(buff, 0, read);
  }
  signedData.close();
  return sig.verify();
}
 
Example #7
Source File: PGPKeyHelper.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static PGPPublicKey readPublicKey( InputStream is ) throws IOException, PGPException
{
    PGPPublicKeyRingCollection pgpPub =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() );

    Iterator keyRingIter = pgpPub.getKeyRings();

    while ( keyRingIter.hasNext() )
    {
        PGPPublicKeyRing keyRing = ( PGPPublicKeyRing ) keyRingIter.next();
        Iterator keyIter = keyRing.getPublicKeys();

        while ( keyIter.hasNext() )
        {
            PGPPublicKey key = ( PGPPublicKey ) keyIter.next();

            if ( key.isEncryptionKey() )
            {
                return key;
            }
        }
    }

    throw new IllegalArgumentException( "Can't find encryption key in key ring." );
}
 
Example #8
Source File: OpenPGPKeyBasedEncryptor.java    From nifi with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated

    // Read in from the public keyring file
    try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {

        // Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
        PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());

        // Iterate over all public keyrings
        Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
        PGPPublicKeyRing keyRing;
        while (iter.hasNext()) {
            keyRing = iter.next();

            // Iterate over each public key in this keyring
            Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
            while (keyIter.hasNext()) {
                PGPPublicKey publicKey = keyIter.next();

                // Iterate over each userId attached to the public key
                Iterator userIdIterator = publicKey.getUserIDs();
                while (userIdIterator.hasNext()) {
                    String id = (String) userIdIterator.next();
                    if (userId.equalsIgnoreCase(id)) {
                        return publicKey;
                    }
                }
            }
        }
    }

    // If this point is reached, no public key could be extracted with the given userId
    throw new PGPException("Could not find a public key with the given userId");
}
 
Example #9
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void deletePublicKeyRing(BareJid owner, OpenPgpV4Fingerprint fingerprint) throws IOException, PGPException {
    PGPPublicKeyRingCollection publicKeyRings = getPublicKeysOf(owner);
    if (publicKeyRings.contains(fingerprint.getKeyId())) {
        publicKeyRings = PGPPublicKeyRingCollection.removePublicKeyRing(publicKeyRings, publicKeyRings.getPublicKeyRing(fingerprint.getKeyId()));
        if (!publicKeyRings.iterator().hasNext()) {
            publicKeyRings = null;
        }
        this.publicKeyRingCollections.put(owner, publicKeyRings);
        writePublicKeysOf(owner, publicKeyRings);
    }
}
 
Example #10
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRing getPublicKeyRing(BareJid owner, OpenPgpV4Fingerprint fingerprint) throws IOException, PGPException {
    PGPPublicKeyRingCollection publicKeyRings = getPublicKeysOf(owner);

    if (publicKeyRings != null) {
        return publicKeyRings.getPublicKeyRing(fingerprint.getKeyId());
    }

    return null;
}
 
Example #11
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRingCollection getPublicKeysOf(BareJid owner) throws IOException, PGPException {
    PGPPublicKeyRingCollection keys = publicKeyRingCollections.get(owner);
    if (keys == null) {
        keys = readPublicKeysOf(owner);
        if (keys != null) {
            publicKeyRingCollections.put(owner, keys);
        }
    }
    return keys;
}
 
Example #12
Source File: FileBasedOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRingCollection readPublicKeysOf(BareJid owner)
        throws IOException, PGPException {
    File file = getPublicKeyRingPath(owner);
    if (!file.exists()) {
        return null;
    }
    FileInputStream inputStream = FileUtils.prepareFileInputStream(file);

    PGPPublicKeyRingCollection collection = PGPainless.readKeyRing().publicKeyRingCollection(inputStream);
    inputStream.close();
    return collection;
}
 
Example #13
Source File: PainlessOpenPgpProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public OpenPgpElementAndMetadata encrypt(CryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients)
        throws IOException, PGPException {
    InputStream plainText = element.toInputStream();
    ByteArrayOutputStream cipherText = new ByteArrayOutputStream();

    ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>();
    for (OpenPgpContact contact : recipients) {
        PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys();
        if (keys != null) {
            recipientKeys.add(keys);
        } else {
            LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString());
        }
    }

    EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText)
            .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {}))
            .andToSelf(self.getTrustedAnnouncedKeys())
            .usingSecureAlgorithms()
            .doNotSign()
            .noArmor();

    Streams.pipeAll(plainText, cipherStream);
    plainText.close();
    cipherStream.flush();
    cipherStream.close();
    cipherText.close();

    String base64 = Base64.encodeToString(cipherText.toByteArray());
    OpenPgpElement openPgpElement = new OpenPgpElement(base64);

    return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult());
}
 
Example #14
Source File: PainlessOpenPgpProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public OpenPgpElementAndMetadata signAndEncrypt(SigncryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients)
        throws IOException, PGPException {
    InputStream plainText = element.toInputStream();
    ByteArrayOutputStream cipherText = new ByteArrayOutputStream();

    ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>();
    for (OpenPgpContact contact : recipients) {
        PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys();
        if (keys != null) {
            recipientKeys.add(keys);
        } else {
            LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString());
        }
    }

    EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText)
            .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {}))
            .andToSelf(self.getTrustedAnnouncedKeys())
            .usingSecureAlgorithms()
            .signWith(getStore().getKeyRingProtector(), self.getSigningKeyRing())
            .noArmor();

    Streams.pipeAll(plainText, cipherStream);
    plainText.close();
    cipherStream.flush();
    cipherStream.close();
    cipherText.close();

    String base64 = Base64.encodeToString(cipherText.toByteArray());
    OpenPgpElement openPgpElement = new OpenPgpElement(base64);

    return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult());
}
 
Example #15
Source File: OpenPGPKeyBasedEncryptor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated

    // Read in from the public keyring file
    try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {

        // Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
        PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());

        // Iterate over all public keyrings
        Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
        PGPPublicKeyRing keyRing;
        while (iter.hasNext()) {
            keyRing = iter.next();

            // Iterate over each public key in this keyring
            Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
            while (keyIter.hasNext()) {
                PGPPublicKey publicKey = keyIter.next();

                // Iterate over each userId attached to the public key
                Iterator userIdIterator = publicKey.getUserIDs();
                while (userIdIterator.hasNext()) {
                    String id = (String) userIdIterator.next();
                    if (userId.equalsIgnoreCase(id)) {
                        return publicKey;
                    }
                }
            }
        }
    }

    // If this point is reached, no public key could be extracted with the given userId
    throw new PGPException("Could not find a public key with the given userId");
}
 
Example #16
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private void signKeyAndPrintIds( KeyPair first, KeyPair second, String password ) throws IOException, PGPException
{
    InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() );
    InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() );
    InputStream secondSecretStream = new ByteArrayInputStream( second.getSecKeyring() );

    PGPPublicKeyRingCollection keyrings =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ),
                    new JcaKeyFingerprintCalculator() );

    PGPPublicKeyRing firstPublicKeyRing = null;
    if ( keyrings.getKeyRings().hasNext() )
    {
        firstPublicKeyRing = keyrings.getKeyRings().next();


        PGPSecretKey secondSecretKey =
                PGPEncryptionUtil.findSecretKeyById( secondSecretStream, second.getPrimaryKeyId() );
        PGPPublicKey secondPublicKey =
                PGPEncryptionUtil.findPublicKeyById( secondPublicStream, second.getPrimaryKeyId() );

        if ( secondSecretKey != null )
        {
            String keyId = Long.toHexString( secondSecretKey.getKeyID() );

            PGPPublicKeyRing firstSignedPublicKeyRing =
                    PGPEncryptionUtil.signPublicKey( firstPublicKeyRing, keyId, secondSecretKey, password );

            printPublicKeySignatures( firstSignedPublicKeyRing.getPublicKey(), secondPublicKey );

            first.setPubKeyring( firstSignedPublicKeyRing.getEncoded() );
        }
    }
}
 
Example #17
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeySigning() throws PGPException, IOException
{
    KeyPair first = PGPEncryptionUtil.generateKeyPair( "[email protected]", "first", false );
    KeyPair second = PGPEncryptionUtil.generateKeyPair( "[email protected]", "second", false );
    signKeyAndPrintIds( first, second, "second" );

    InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() );
    InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() );

    PGPPublicKeyRingCollection firstPublicKeyRingCollection =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ),
                    new JcaKeyFingerprintCalculator() );

    PGPPublicKeyRingCollection secondPublicKeyRingCollection =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
                    new JcaKeyFingerprintCalculator() );

    if ( firstPublicKeyRingCollection.getKeyRings().hasNext() )
    {
        PGPPublicKeyRing firstPublicKeyRing = null;
        PGPPublicKeyRing secondPublicKeyRing = null;
        firstPublicKeyRing = firstPublicKeyRingCollection.getKeyRings().next();
        secondPublicKeyRing = secondPublicKeyRingCollection.getKeyRings().next();
        assertEquals( true,
                printPublicKeySignatures( firstPublicKeyRing.getPublicKey(), secondPublicKeyRing.getPublicKey() ) );
    }
}
 
Example #18
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyClearSign() throws Exception
{
    InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY );
    PGPPublicKeyRingCollection secondPublicKeyRingCollection =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
                    new JcaKeyFingerprintCalculator() );

    PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection
            .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() );

    String signedMessage = IOUtils.toString( findFile( "signedMessage.txt" ) );

    logger.info( "\n" + signedMessage );

    boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring );
    if ( result )
    {
        logger.info( "signature verified." );
    }
    else
    {
        logger.info( "signature verification failed." );
    }

    assertEquals( true, result );
}
 
Example #19
Source File: GPGFileEncryptor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}.
 * @param outputStream {@link OutputStream} that will receive the encrypted content
 * @param keyIn keyring inputstream. This InputStream is owned by the caller.
 * @param keyId key identifier
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return an {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher)
    throws IOException {
  try {
    if (Security.getProvider(PROVIDER_NAME) == null) {
      Security.addProvider(new BouncyCastleProvider());
    }

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
        new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
            .setSecureRandom(new SecureRandom())
            .setProvider(PROVIDER_NAME));

    PGPPublicKey publicKey;
    PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
        new BcKeyFingerprintCalculator());
    publicKey = keyRings.getPublicKey(keyId);

    if (publicKey == null) {
      throw new IllegalArgumentException("public key for encryption not found");
    }

    cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME));

    OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    OutputStream _literalOut =
        literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]);

    return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
  } catch (PGPException e) {
    throw new IOException(e);
  }
}
 
Example #20
Source File: DummyKeyringModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Always returns a {@link InMemoryKeyring} instance. */
@Provides
@Named("DummyKeyring")
static InMemoryKeyring provideDummyKeyring() {
  PGPKeyPair dummyKey;
  try (InputStream publicInput = PGP_PUBLIC_KEYRING.openStream();
      InputStream privateInput = PGP_PRIVATE_KEYRING.openStream()) {
    PGPPublicKeyRingCollection publicKeys =
        new BcPGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicInput));
    PGPSecretKeyRingCollection privateKeys =
        new BcPGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateInput));
    dummyKey = lookupKeyPair(publicKeys, privateKeys, EMAIL_ADDRESS, ENCRYPT_SIGN);
  } catch (PGPException | IOException e) {
    throw new VerifyException("Failed to load PGP keys from jar", e);
  }
  // Use the same dummy PGP keypair for all required PGP keys -- a real production system would
  // have different values for these keys.  Pass dummy values for all Strings.
  return new InMemoryKeyring(
      dummyKey,
      dummyKey,
      dummyKey.getPublicKey(),
      dummyKey,
      dummyKey.getPublicKey(),
      "not a real key",
      "not a real key",
      "not a real password",
      "not a real API key",
      "not a real login",
      "not a real password",
      "not a real login",
      "not a real credential",
      "not a real password",
      "not a real password");
}
 
Example #21
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageSigning() throws Exception
{
    InputStream secondSecretStream = findFile( PLUGIN_PRIVATE_KEY );
    InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY );

    PGPSecretKeyRingCollection secretKeyRingCollection =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secondSecretStream ),
                    new JcaKeyFingerprintCalculator() );

    PGPSecretKeyRing secretKeyRing = secretKeyRingCollection
            .getSecretKeyRing( secretKeyRingCollection.iterator().next().getSecretKey().getKeyID() );

    PGPSecretKey secondSecretKey = secretKeyRing.getSecretKey();

    PGPPublicKeyRingCollection secondPublicKeyRingCollection =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
                    new JcaKeyFingerprintCalculator() );


    PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection
            .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() );


    byte[] encryptedMessage =
            PGPEncryptionUtil.encrypt( "Test message.\n".getBytes(), pgpKeyring.getPublicKey(), true );

    byte[] signedMessageArmor =
            PGPEncryptionUtil.clearSign( encryptedMessage, secondSecretKey, "123".toCharArray(), "" );

    String signedMessage = new String( signedMessageArmor, StandardCharsets.UTF_8 );

    logger.info( "\n" + signedMessage );
    logger.info( "\n======================" );

    boolean result = PGPEncryptionUtil.verifyClearSign( signedMessageArmor, pgpKeyring );
    if ( result )
    {
        logger.info( "signature verified." );
    }
    else
    {
        logger.info( "signature verification failed." );
    }

    byte[] extracted = PGPEncryptionUtil.extractContentFromClearSign( signedMessage.getBytes() );
    byte[] decrypted = PGPEncryptionUtil.decrypt( extracted, secretKeyRing, "123" );
    logger.info( "Decrypted message \n" + new String( decrypted, StandardCharsets.UTF_8 ) );

    assertEquals( true, result );
}
 
Example #22
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 4 votes vote down vote up
@Test
public void testClearSign() throws Exception
{
    InputStream secondSecretStream = findFile( PLUGIN_PRIVATE_KEY );
    InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY );

    PGPSecretKeyRingCollection secretKeyRingCollection =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secondSecretStream ),
                    new JcaKeyFingerprintCalculator() );

    PGPSecretKeyRing secretKeyRing = secretKeyRingCollection
            .getSecretKeyRing( secretKeyRingCollection.iterator().next().getPublicKey().getKeyID() );

    PGPSecretKey secondSecretKey = secretKeyRing.getSecretKey();

    PGPPublicKeyRingCollection secondPublicKeyRingCollection =
            new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ),
                    new JcaKeyFingerprintCalculator() );


    PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection
            .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() );

    byte[] signedMessageArmor = PGPEncryptionUtil
            .clearSign( IOUtils.toString( findFile( "message.txt" ) ).getBytes(), secondSecretKey,
                    "123".toCharArray(), "" );

    String signedMessage = new String( signedMessageArmor, StandardCharsets.UTF_8 );

    logger.info( "\n" + signedMessage );

    boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring );
    if ( result )
    {
        logger.info( "signature verified." );
    }
    else
    {
        logger.info( "signature verification failed." );
    }

    assertEquals( true, result );
}
 
Example #23
Source File: AbstractOpenPgpStore.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public PGPPublicKeyRingCollection getPublicKeysOf(BareJid owner) throws IOException, PGPException {
    return keyStore.getPublicKeysOf(owner);
}
 
Example #24
Source File: AptITSupport.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public boolean verifyInReleaseFilePgpSignature(final InputStream fileContent, final InputStream publicKeyString)
    throws Exception
{

  PGPPublicKeyRingCollection pgpRings =
      new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyString),
          new JcaKeyFingerprintCalculator());
  ArmoredInputStream aIn = new ArmoredInputStream(fileContent);
  ByteArrayOutputStream releaseContent = new ByteArrayOutputStream();
  ByteArrayOutputStream lineOut = new ByteArrayOutputStream();

  int fromPositon = -1;
  if (aIn.isClearText()) {
    do {
      fromPositon = readStreamLine(lineOut, fromPositon, aIn);
      releaseContent.write(lineOut.toByteArray());
    }
    while (fromPositon != -1 && aIn.isClearText());
  }

  PGPObjectFactory pgpFact = new PGPObjectFactory(aIn, new JcaKeyFingerprintCalculator());
  PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
  PGPSignature sig = p3.get(0);

  PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
  sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
  InputStream sigIn = new ByteArrayInputStream(releaseContent.toByteArray());

  fromPositon = -1;
  do {
    int length;
    if (fromPositon != -1) {
      sig.update((byte) '\r');
      sig.update((byte) '\n');
    }
    fromPositon = readStreamLine(lineOut, fromPositon, sigIn);
    length = lineOut.toString(StandardCharsets.UTF_8.name()).replaceAll("\\s*$", "").length();
    if (length > 0) {
      sig.update(lineOut.toByteArray(), 0, length);
    }
  }
  while (fromPositon != -1);

  return sig.verify();
}
 
Example #25
Source File: PGPKeyId.java    From pgpverify-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
        throws PGPException {
    return pgpRingCollection.getPublicKeyRing(fingerprint);
}
 
Example #26
Source File: PGPKeyId.java    From pgpverify-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public PGPPublicKeyRing getKeyRingFromRingCollection(PGPPublicKeyRingCollection pgpRingCollection)
        throws PGPException {
    return pgpRingCollection.getPublicKeyRing(keyId);
}
 
Example #27
Source File: OpenPgpContact.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Return a {@link PGPPublicKeyRingCollection} which contains all public keys of the contact, which are announced,
 * as well as marked as {@link OpenPgpStore.Trust#trusted}.
 *
 * @return announced, trusted keys.
 *
 * @throws IOException IO error
 * @throws PGPException PGP error
 */
public PGPPublicKeyRingCollection getTrustedAnnouncedKeys()
        throws IOException, PGPException {
    PGPPublicKeyRingCollection announced = getAnnouncedPublicKeys();
    PGPPublicKeyRingCollection trusted = getPublicKeysOfTrustState(announced, OpenPgpTrustStore.Trust.trusted);
    return trusted;
}
 
Example #28
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 3 votes vote down vote up
@Test
public void testEncryptDecrypt_KeyRingStyle() throws Exception {
  int bufferSize = 64 * 1024;

  // Alice loads Bob's "publicKey" into memory from her public key ring.
  PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
      PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
  PGPPublicKeyRing publicKeyRing =
      publicKeyRings.getKeyRings("[email protected]", true, true).next();
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();

  // Alice encrypts the secret message for Bob using his "publicKey".
  PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
      new BcPGPDataEncryptorBuilder(AES_128));
  encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
  byte[] encryptedData;
  try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
    try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
      output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
    }
    encryptedData = output.toByteArray();
  }
  logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData));

  // Bob loads his chain of private keys into memory.
  PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
      PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

  // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
  try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
    assertThat(encDataList.size()).isEqualTo(1);
    PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
    // Bob loads the private key to which the message is addressed.
    PGPPrivateKey privateKey =
        extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
    try (InputStream original =
        encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
      assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
          .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    }
  }
}
 
Example #29
Source File: TestHelper.java    From peer-os with Apache License 2.0 3 votes vote down vote up
public static PGPPublicKeyRing PGP_PUB_KEY() throws PGPException, IOException
{

    PGPPublicKeyRingCollection pgpPublicKeyRings = new PGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream( new ByteArrayInputStream( PGP_PUBLIC_KEY.getBytes() ) ),
            new JcaKeyFingerprintCalculator() );


    return pgpPublicKeyRings.getPublicKeyRing( pgpPublicKeyRings.iterator().next().getPublicKey().getKeyID() );
}
 
Example #30
Source File: OpenPgpSelf.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Return a {@link PGPPublicKeyRingCollection} containing only the public keys belonging to our signing key ring.
 * TODO: Add support for public keys of other devices of the owner.
 *
 * @return public keys
 *
 * @throws IOException IO is dangerous.
 * @throws PGPException PGP is brittle.
 */
@Override
public PGPPublicKeyRingCollection getAnnouncedPublicKeys() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = getSigningKeyRing();
    PGPPublicKeyRing publicKeys = getAnyPublicKeys().getPublicKeyRing(secretKeys.getPublicKey().getKeyID());
    publicKeys = BCUtil.removeUnassociatedKeysFromKeyRing(publicKeys, secretKeys.getPublicKey());
    return new PGPPublicKeyRingCollection(Collections.singleton(publicKeys));
}