org.bouncycastle.openpgp.PGPSecretKeyRingCollection Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPSecretKeyRingCollection. 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 6 votes vote down vote up
private static PGPLiteralData asLiteral( final byte[] message, final InputStream secretKeyRing,
                                         final String secretPwd ) throws IOException, PGPException
{
    PGPPrivateKey key = null;
    PGPPublicKeyEncryptedData encrypted = null;
    final PGPSecretKeyRingCollection keys =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRing ),
                    new JcaKeyFingerprintCalculator() );
    for ( final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects( message );
          ( key == null ) && i.hasNext(); )
    {
        encrypted = i.next();
        key = getPrivateKey( keys, encrypted.getKeyID(), secretPwd );
    }
    if ( key == null )
    {
        throw new IllegalArgumentException( "secret key for message not found." );
    }
    final InputStream stream = encrypted
            .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( provider ).build( key ) );
    return asLiteral( stream );
}
 
Example #2
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * ***********************************************
 */
private static PGPPrivateKey getPrivateKey( final PGPSecretKeyRingCollection keys, final long id,
                                            final String secretPwd )
{
    try
    {
        final PGPSecretKey key = keys.getSecretKey( id );
        if ( key != null )
        {
            return key.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider )
                                                                               .build( secretPwd.toCharArray() ) );
        }
    }
    catch ( final Exception e )
    {
        // Don't print the passphrase but do print null if thats what it was
        final String passphraseMessage = ( secretPwd == null ) ? "null" : "supplied";
        LOG.warn( "Unable to extract key " + id + " using " + passphraseMessage + " passphrase: {}",
                e.getMessage() );
    }
    return null;
}
 
Example #3
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 #4
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void importSecretKey(BareJid owner, PGPSecretKeyRing secretKeys)
        throws IOException, PGPException, MissingUserIdOnKeyException {

    // TODO: Avoid 'new' use instance method.
    if (!new BareJidUserId.SecRingSelectionStrategy().accept(owner, secretKeys)) {
        throw new MissingUserIdOnKeyException(owner, new OpenPgpV4Fingerprint(secretKeys));
    }

    PGPSecretKeyRing importKeys = BCUtil.removeUnassociatedKeysFromKeyRing(secretKeys, secretKeys.getPublicKey());

    PGPSecretKeyRingCollection secretKeyRings = getSecretKeysOf(owner);
    try {
        if (secretKeyRings != null) {
            secretKeyRings = PGPSecretKeyRingCollection.addSecretKeyRing(secretKeyRings, importKeys);
        } else {
            secretKeyRings = BCUtil.keyRingsToKeyRingCollection(importKeys);
        }
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.INFO, "Skipping secret key ring " + Long.toHexString(importKeys.getPublicKey().getKeyID()) +
                " as it is already in the key ring of " + owner.toString());
    }
    this.secretKeyRingCollections.put(owner, secretKeyRings);
    writeSecretKeysOf(owner, secretKeyRings);
}
 
Example #5
Source File: AptSigningFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 6 votes vote down vote up
private PGPSecretKey readSecretKey() throws IOException, PGPException {
  PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
      PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes())),
      new JcaKeyFingerprintCalculator());

  Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings();
  while (keyRings.hasNext()) {
    PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRings.next();

    Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
    while (keys.hasNext()) {
      PGPSecretKey key = (PGPSecretKey) keys.next();

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

  throw new IllegalStateException("Can't find signing key in key ring.");
}
 
Example #6
Source File: AptSigningFacet.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private PGPSecretKey readSecretKey() throws IOException {
  try {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
        PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes(Charsets.UTF_8))),
        new JcaKeyFingerprintCalculator());

    Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings();
    while (keyRings.hasNext()) {
      PGPSecretKeyRing keyRing = keyRings.next();

      Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
      while (keys.hasNext()) {
        PGPSecretKey key = keys.next();

        if (key.isSigningKey()) {
          return key;
        }
      }
    }
  }
  catch (PGPException ex) {
    throw new RuntimeException(ex);
  }

  throw new IllegalStateException("Can't find signing key in key ring.");
}
 
Example #7
Source File: FileBasedOpenPgpKeyStore.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void writeSecretKeysOf(BareJid owner, PGPSecretKeyRingCollection secretKeys) throws IOException {
    File file = getSecretKeyRingPath(owner);

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

    OutputStream outputStream = null;
    try {
        outputStream = FileUtils.prepareFileOutputStream(file);
        secretKeys.encode(outputStream);
    } finally {
        CloseableUtil.maybeClose(outputStream, LOGGER);
    }
}
 
Example #8
Source File: OpenPgpSelf.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Return the {@link PGPSecretKeyRing} which we will use to sign our messages.
 * @return signing key
 * @throws IOException IO is dangerous
 * @throws PGPException PGP is brittle
 */
public PGPSecretKeyRing getSigningKeyRing() throws IOException, PGPException {
    PGPSecretKeyRingCollection secretKeyRings = getSecretKeys();
    if (secretKeyRings == null) {
        return null;
    }

    PGPSecretKeyRing signingKeyRing = null;
    for (PGPSecretKeyRing ring : secretKeyRings) {
        if (signingKeyRing == null) {
            signingKeyRing = ring;
            continue;
        }

        if (ring.getPublicKey().getCreationTime().after(signingKeyRing.getPublicKey().getCreationTime())) {
            signingKeyRing = ring;
        }
    }

    return signingKeyRing;
}
 
Example #9
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Upload the encrypted secret key to a private PEP node.
 *
 * @see <a href="https://xmpp.org/extensions/xep-0373.html#synchro-pep">XEP-0373 ยง5</a>
 *
 * @param displayCodeCallback callback, which will receive the backup password used to encrypt the secret key.
 * @param selectKeyCallback callback, which will receive the users choice of which keys will be backed up.
 * @throws InterruptedException if the thread is interrupted.
 * @throws PubSubException.NotALeafNodeException if the private node is not a {@link LeafNode}.
 * @throws XMPPException.XMPPErrorException in case of an XMPP protocol error.
 * @throws SmackException.NotConnectedException if we are not connected.
 * @throws SmackException.NoResponseException if the server doesn't respond.
 * @throws SmackException.NotLoggedInException if we are not logged in.
 * @throws IOException IO is dangerous.
 * @throws SmackException.FeatureNotSupportedException if the server doesn't support the PubSub whitelist access model.
 * @throws PGPException PGP is brittle
 * @throws MissingOpenPgpKeyException in case we have no OpenPGP key pair to back up.
 */
public void backupSecretKeyToServer(DisplayBackupCodeCallback displayCodeCallback,
                                    SecretKeyBackupSelectionCallback selectKeyCallback)
        throws InterruptedException, PubSubException.NotALeafNodeException,
        XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException,
        SmackException.NotLoggedInException, IOException,
        SmackException.FeatureNotSupportedException, PGPException, MissingOpenPgpKeyException {
    throwIfNoProviderSet();
    throwIfNotAuthenticated();

    BareJid ownJid = connection().getUser().asBareJid();

    String backupCode = SecretKeyBackupHelper.generateBackupPassword();

    PGPSecretKeyRingCollection secretKeyRings = provider.getStore().getSecretKeysOf(ownJid);

    Set<OpenPgpV4Fingerprint> availableKeyPairs = new HashSet<>();
    for (PGPSecretKeyRing ring : secretKeyRings) {
        availableKeyPairs.add(new OpenPgpV4Fingerprint(ring));
    }

    Set<OpenPgpV4Fingerprint> selectedKeyPairs = selectKeyCallback.selectKeysToBackup(availableKeyPairs);

    SecretkeyElement secretKey = SecretKeyBackupHelper.createSecretkeyElement(provider, ownJid, selectedKeyPairs, backupCode);

    OpenPgpPubSubUtil.depositSecretKey(connection(), secretKey);
    displayCodeCallback.displayBackupCode(backupCode);
}
 
Example #10
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteSecretKeyRing(BareJid owner, OpenPgpV4Fingerprint fingerprint) throws IOException, PGPException {
    PGPSecretKeyRingCollection secretKeyRings = getSecretKeysOf(owner);
    if (secretKeyRings.contains(fingerprint.getKeyId())) {
        secretKeyRings = PGPSecretKeyRingCollection.removeSecretKeyRing(secretKeyRings, secretKeyRings.getSecretKeyRing(fingerprint.getKeyId()));
        if (!secretKeyRings.iterator().hasNext()) {
            secretKeyRings = null;
        }
        this.secretKeyRingCollections.put(owner, secretKeyRings);
        writeSecretKeysOf(owner, secretKeyRings);
    }
}
 
Example #11
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public PGPSecretKeyRing getSecretKeyRing(BareJid owner, OpenPgpV4Fingerprint fingerprint) throws IOException, PGPException {
    PGPSecretKeyRingCollection secretKeyRings = getSecretKeysOf(owner);

    if (secretKeyRings != null) {
        return secretKeyRings.getSecretKeyRing(fingerprint.getKeyId());
    }

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

    PGPSecretKeyRingCollection collection = PGPainless.readKeyRing().secretKeyRingCollection(inputStream);
    inputStream.close();
    return collection;
}
 
Example #14
Source File: PGPKeyHelper.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static PGPSecretKey readSecretKey( InputStream is ) throws IOException, PGPException
{
    PGPSecretKeyRingCollection pgpSec =
            new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() );
    Iterator keyRingIter = pgpSec.getKeyRings();

    while ( keyRingIter.hasNext() )
    {
        PGPSecretKeyRing keyRing = ( PGPSecretKeyRing ) keyRingIter.next();
        Iterator keyIter = keyRing.getSecretKeys();

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

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

    throw new IllegalArgumentException( "Can't find signing key in key ring." );
}
 
Example #15
Source File: GPGFileDecryptor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Private util function that finds the private key from keyring collection based on keyId and passPhrase
 * @param pgpSec keyring collection
 * @param keyID keyID for this encryption file
 * @param passPhrase passPhrase for this encryption file
 * @throws PGPException
 */
private PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, String passPhrase)
    throws PGPException {

  PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
  if (pgpSecKey == null) {
    return null;
  }
  return pgpSecKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder()
          .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));
}
 
Example #16
Source File: OpenPGPSignatureGenerator.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
private PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException {
    in = PGPUtil.getDecoderStream(in);
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(in,
            new BcKeyFingerprintCalculator());

    PGPSecretKey key = null;
    Iterator<PGPSecretKeyRing> it = pgpSec.getKeyRings();
    while (key == null && it.hasNext()) {
        PGPSecretKeyRing kRing = it.next();

        Iterator<PGPSecretKey> it2 = kRing.getSecretKeys();
        while (key == null && it2.hasNext()) {
            PGPSecretKey k = it2.next();
            if (keyId == null && k.isSigningKey()) {
                key = k;
            }
            if (keyId != null && Long.valueOf(keyId, 16) == (k.getKeyID() & MASK)) {
                key = k;
            }
        }
    }

    if (key == null) {
        throw new IllegalArgumentException("Can't find encryption key"
                + (keyId != null ? " '" + keyId + "' " : " ") + "in key ring.");
    }

    return key;
}
 
Example #17
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 #18
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 #19
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 #20
Source File: AbstractOpenPgpStore.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public PGPSecretKeyRingCollection getSecretKeysOf(BareJid owner) throws IOException, PGPException {
    return keyStore.getSecretKeysOf(owner);
}
 
Example #21
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 #22
Source File: OpenPgpSelf.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Return a {@link PGPSecretKeyRingCollection} which contains all of our {@link PGPSecretKeyRing}s.
 * @return collection of our secret keys
 * @throws IOException IO is dangerous
 * @throws PGPException PGP is brittle
 */
public PGPSecretKeyRingCollection getSecretKeys() throws IOException, PGPException {
    return store.getSecretKeysOf(jid);
}
 
Example #23
Source File: OpenPgpKeyStore.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Return the {@link PGPSecretKeyRingCollection} containing all secret keys of {@code owner} which are locally
 * available.
 * This method might return null.
 *
 * @param owner {@link BareJid} of the user we want to get keys from.
 * @return {@link PGPSecretKeyRingCollection} of the user.
 *
 * @throws IOException IO is dangerous
 * @throws PGPException PGP is brittle
 */
PGPSecretKeyRingCollection getSecretKeysOf(BareJid owner) throws IOException, PGPException;
 
Example #24
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Read a {@link PGPSecretKeyRingCollection} from local storage.
 * This method returns null, if no keys were found.
 *
 * @param owner owner of the keys
 * @return secret keys
 *
 * @throws IOException IO is dangerous
 * @throws PGPException PGP is brittle
 */
protected abstract PGPSecretKeyRingCollection readSecretKeysOf(BareJid owner) throws IOException, PGPException;
 
Example #25
Source File: AbstractOpenPgpKeyStore.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Write the {@link PGPSecretKeyRingCollection} of a user to local storage.
 *
 * @param owner owner of the keys
 * @param secretKeys secret keys
 *
 * @throws IOException IO is dangerous
 */
protected abstract void writeSecretKeysOf(BareJid owner, PGPSecretKeyRingCollection secretKeys) throws IOException;