org.bouncycastle.openpgp.PGPSecretKeyRing Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPSecretKeyRing. 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: KeyFilesOperationsPgpImpl.java    From pgptool with GNU General Public License v3.0 7 votes vote down vote up
@SuppressWarnings("rawtypes")
private static void readKeyFromStream(KeyDataPgp data, InputStream stream) throws IOException {
	PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(stream), fingerprintCalculator);
	for (Iterator iter = factory.iterator(); iter.hasNext();) {
		Object section = iter.next();
		log.debug("Section found: " + section);

		if (section instanceof PGPSecretKeyRing) {
			data.setSecretKeyRing((PGPSecretKeyRing) section);
		} else if (section instanceof PGPPublicKeyRing) {
			data.setPublicKeyRing((PGPPublicKeyRing) section);
		} else {
			log.error("Unknown section enountered in a key file: " + section);
		}
	}
}
 
Example #2
Source File: PGPEncryptionUtilTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifySignature() throws Exception
{
    PGPPublicKey encryptingKey =
            PGPEncryptionUtil.findPublicKeyByFingerprint( findFile( PUBLIC_KEYRING ), PUBLIC_KEY_FINGERPRINT );

    PGPSecretKeyRing secretKeys = PGPKeyUtil.readSecretKeyRing( findFile( SECRET_KEYRING ) );


    byte[] signedAndEncryptedMessage = PGPEncryptionUtil
            .signAndEncrypt( MESSAGE.getBytes(), secretKeys.getSecretKey(), SECRET_PWD, encryptingKey, true );

    ContentAndSignatures contentAndSignatures =
            PGPEncryptionUtil.decryptAndReturnSignatures( signedAndEncryptedMessage, secretKeys, SECRET_PWD );

    assertTrue( PGPEncryptionUtil.verifySignature( contentAndSignatures, secretKeys.getPublicKey() ) );
}
 
Example #3
Source File: KeyDataPgp.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
	ois.defaultReadObject();

	try {
		if (ois.readBoolean()) {
			secretKeyRing = new PGPSecretKeyRing(initInputStream(ois),
					KeyFilesOperationsPgpImpl.fingerprintCalculator);
		}
		if (ois.readBoolean()) {
			publicKeyRing = new PGPPublicKeyRing(initInputStream(ois),
					KeyFilesOperationsPgpImpl.fingerprintCalculator);
		}
	} catch (PGPException e) {
		throw new IOException("Failed to read key", e);
	}
}
 
Example #4
Source File: PGPKeyUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static PGPSecretKey readSecretKey( PGPSecretKeyRing keyRing ) throws PGPException
{
    try
    {
        Iterator keyIter = keyRing.getSecretKeys();

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

            if ( key.isSigningKey() )
            {
                return key;
            }
        }
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage() );
    }

    return null;
}
 
Example #5
Source File: Ring.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Loads all keys from the specified input stream,
 * and adds them to this ring's existing list of keys.
 */
public List<Key> load(InputStream stream) throws IOException, PGPException {
    List<Key> keys = new ArrayList<Key>();

    Iterator<?> packets = parse(stream);
    while (packets.hasNext()) {
        Object packet = packets.next();

        if (packet instanceof PGPSecretKeyRing)
            keys.add(newKey((PGPSecretKeyRing) packet));
        else if (packet instanceof PGPPublicKeyRing)
            keys.add(newKey((PGPPublicKeyRing) packet));
        else if (packet instanceof PublicKeyRingBlob)
            keys.add(newKey(
                ((PublicKeyRingBlob) packet).getPGPPublicKeyRing()));
    }

    this.keys.addAll(keys);
    return keys;
}
 
Example #6
Source File: OpenPgpStoreTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void t06_key_keyReloadTest() throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, IOException, MissingUserIdOnKeyException {
    PGPKeyRing keys = openPgpStoreInstance1.generateKeyRing(alice);
    PGPSecretKeyRing secretKeys = keys.getSecretKeys();
    OpenPgpV4Fingerprint fingerprint = new OpenPgpV4Fingerprint(secretKeys);
    PGPPublicKeyRing publicKeys = keys.getPublicKeys();

    openPgpStoreInstance1.importSecretKey(alice, secretKeys);
    openPgpStoreInstance1.importPublicKey(alice, publicKeys);

    assertNotNull(openPgpStoreInstance2.getSecretKeysOf(alice));
    assertNotNull(openPgpStoreInstance2.getPublicKeysOf(alice));

    // Clean up
    openPgpStoreInstance1.deletePublicKeyRing(alice, fingerprint);
    openPgpStoreInstance1.deleteSecretKeyRing(alice, fingerprint);
    openPgpStoreInstance2.deletePublicKeyRing(alice, fingerprint);
    openPgpStoreInstance2.deleteSecretKeyRing(alice, fingerprint);
}
 
Example #7
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 #8
Source File: SecretKeyBackupHelperTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndDecryptSecretKeyElementTest()
        throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
        IOException, MissingUserIdOnKeyException, MissingOpenPgpKeyException, InvalidBackupCodeException {

    // Prepare store and provider and so on...
    FileBasedOpenPgpStore store = new FileBasedOpenPgpStore(basePath);
    PainlessOpenPgpProvider provider = new PainlessOpenPgpProvider(store);

    // Generate and import key
    PGPKeyRing keyRing = PGPainless.generateKeyRing().simpleEcKeyRing("xmpp:[email protected]");
    BareJid jid = JidCreate.bareFrom("[email protected]");
    provider.getStore().importSecretKey(jid, keyRing.getSecretKeys());

    // Create encrypted backup
    String backupCode = SecretKeyBackupHelper.generateBackupPassword();
    SecretkeyElement element = SecretKeyBackupHelper.createSecretkeyElement(provider, jid, Collections.singleton(new OpenPgpV4Fingerprint(keyRing.getSecretKeys())), backupCode);

    // Decrypt backup and compare
    PGPSecretKeyRing secretKeyRing = SecretKeyBackupHelper.restoreSecretKeyBackup(element, backupCode);
    assertTrue(Arrays.equals(keyRing.getSecretKeys().getEncoded(), secretKeyRing.getEncoded()));
}
 
Example #9
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 #10
Source File: SecretKeyBackupHelper.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link SecretkeyElement} which contains the secret keys listed in {@code fingerprints} and is encrypted
 * symmetrically using the {@code backupCode}.
 *
 * @param provider {@link OpenPgpProvider} for symmetric encryption.
 * @param owner owner of the secret keys (usually our jid).
 * @param fingerprints set of {@link OpenPgpV4Fingerprint}s of the keys which are going to be backed up.
 * @param backupCode passphrase for symmetric encryption.
 * @return {@link SecretkeyElement}
 *
 * @throws PGPException PGP is brittle
 * @throws IOException IO is dangerous
 * @throws MissingOpenPgpKeyException in case one of the keys whose fingerprint is in {@code fingerprints} is
 * not accessible.
 */
public static SecretkeyElement createSecretkeyElement(OpenPgpProvider provider,
                                                BareJid owner,
                                                Set<OpenPgpV4Fingerprint> fingerprints,
                                                String backupCode)
        throws PGPException, IOException, MissingOpenPgpKeyException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    for (OpenPgpV4Fingerprint fingerprint : fingerprints) {

            PGPSecretKeyRing key = provider.getStore().getSecretKeyRing(owner, fingerprint);
            if (key == null) {
                throw new MissingOpenPgpKeyException(owner, fingerprint);
            }

            byte[] bytes = key.getEncoded();
            buffer.write(bytes);
    }
    return createSecretkeyElement(buffer.toByteArray(), backupCode);
}
 
Example #11
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public PGPPublicKeyRing signKey( PGPSecretKeyRing sourceSecRing, PGPPublicKeyRing targetPubRing, int trustLevel )
{
    try
    {
        String sigId = PGPKeyUtil.encodeNumericKeyId( targetPubRing.getPublicKey().getKeyID() );

        targetPubRing = encryptionTool.signPublicKey( targetPubRing, sigId, sourceSecRing.getSecretKey(), "" );
    }
    catch ( Exception ignored )
    {
        //ignore
    }

    return targetPubRing;
}
 
Example #12
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 #13
Source File: EnvironmentManagerImplTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateEnvironmentKeyPair() throws Exception
{
    KeyPair keyPair = mock( KeyPair.class );
    doReturn( keyPair ).when( keyManager ).generateKeyPair( TestHelper.ENV_ID, false );

    PGPSecretKeyRing secRing = mock( PGPSecretKeyRing.class );
    PGPPublicKeyRing pubRing = mock( PGPPublicKeyRing.class );
    doReturn( secRing ).when( pgpKeyUtil ).getSecretKeyRing( any( byte[].class ) );
    doReturn( pubRing ).when( pgpKeyUtil ).getPublicKeyRing( any( byte[].class ) );

    environmentManager.createEnvironmentKeyPair( TestHelper.ENVIRONMENT_ID );

    verify( keyManager ).saveSecretKeyRing( TestHelper.ENV_ID, SecurityKeyType.ENVIRONMENT_KEY.getId(), secRing );
    verify( keyManager ).savePublicKeyRing( TestHelper.ENV_ID, SecurityKeyType.ENVIRONMENT_KEY.getId(), pubRing );
}
 
Example #14
Source File: EnvironmentManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
PGPSecretKeyRing createEnvironmentKeyPair( EnvironmentId envId ) throws EnvironmentCreationException
{
    KeyManager keyManager = securityManager.getKeyManager();
    String pairId = envId.getId();
    try
    {
        KeyPair keyPair = keyManager.generateKeyPair( pairId, false );

        //******Create PEK *****************************************************************
        PGPSecretKeyRing secRing = pgpKeyUtil.getSecretKeyRing( keyPair.getSecKeyring() );
        PGPPublicKeyRing pubRing = pgpKeyUtil.getPublicKeyRing( keyPair.getPubKeyring() );

        //***************Save Keys *********************************************************
        keyManager.saveSecretKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), secRing );
        keyManager.savePublicKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), pubRing );


        return secRing;
    }
    catch ( PGPException ex )
    {
        throw new EnvironmentCreationException( ex );
    }
}
 
Example #15
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public PGPSecretKeyRing getSecretKeyRingByFingerprint( String fingerprint )
{
    try
    {
        SecretKeyStore secData = securityDataService.getSecretKeyData( fingerprint );

        if ( secData != null )
        {
            return PGPKeyUtil.readSecretKeyRing( secData.getData() );
        }
        else
        {
            return null;
        }
    }
    catch ( PGPException e )
    {
        return null;
    }
}
 
Example #16
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public static PGPSecretKeyRing copySecretKeyRingWithNewPassword(byte[] privateKeyData,
        char[] oldPassphrase, char[] newPassphrase) throws PGPException, IOException, KonException {

    // load the secret key ring
    PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, FP_CALC);

    PGPDigestCalculatorProvider calcProv = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProv)
        .setProvider(PGPUtils.PROVIDER)
        .build(oldPassphrase);

    PGPDigestCalculator calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA256);
    PBESecretKeyEncryptor encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calc)
        .setProvider(PROVIDER).build(newPassphrase);

    try {
        return PGPSecretKeyRing.copyWithNewPassword(secRing, decryptor, encryptor);
    } catch (PGPException ex) {
        // treat this special, cause most like the decryption password was wrong
        throw new KonException(KonException.Error.CHANGE_PASS_COPY, ex);
    }
}
 
Example #17
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void saveSecretKeyRing( String identityId, int type, PGPSecretKeyRing secretKeyRing )
{
    try
    {
        PGPPublicKey publicKey = secretKeyRing.getPublicKey();

        if ( publicKey != null )
        {
            // Store secretKey
            String fingerprint = PGPKeyUtil.getFingerprint( publicKey.getFingerprint() );
            String pwd = keyData.getSecretKeyringPwd();

            //*******************
            securityDataService.saveSecretKeyData( fingerprint, secretKeyRing.getEncoded(), pwd, type );
            securityDataService.saveKeyData( identityId, fingerprint, "", type );
            //*******************
        }
    }
    catch ( Exception ex )
    {
        LOG.error( " ******** Error storing Public key:" + ex.toString(), ex );
    }
}
 
Example #18
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public String signPublicKey( String sourceIdentityId, String keyText, int trustLevel )
{
    String keyStr = "";

    try
    {
        PGPPublicKeyRing targetPubRing = PGPKeyUtil.readPublicKeyRing( keyText );
        PGPSecretKeyRing sourceSecRing = getSecretKeyRing( sourceIdentityId );

        targetPubRing = signKey( sourceSecRing, targetPubRing, trustLevel );
        keyStr = encryptionTool.armorByteArrayToString( targetPubRing.getEncoded() );
    }
    catch ( Exception ex )
    {
        LOG.error( "**** Error !!! Error signing key, IdentityId: " + sourceIdentityId, ex );
    }
    return keyStr;
}
 
Example #19
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 #20
Source File: EnvironmentManagerImplTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateEmptyEnvironment() throws Exception
{
    PGPSecretKeyRing secretKeyRing = mock( PGPSecretKeyRing.class );
    doReturn( secretKeyRing ).when( environmentManager ).createEnvironmentKeyPair( any( EnvironmentId.class ) );

    environmentManager.createEmptyEnvironment( topology );

    verify( environmentManager ).save( any( LocalEnvironment.class ) );
}
 
Example #21
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 #22
Source File: Ring.java    From jpgpj with MIT License 5 votes vote down vote up
protected Key newKey(PGPSecretKeyRing ring) throws PGPException {
    ArrayList<Subkey> subkeys = new ArrayList<Subkey>();

    Iterator<PGPSecretKey> i = ring.iterator();
    while (i.hasNext())
        subkeys.add(newSubkey(i.next()));

    return newKey(subkeys);
}
 
Example #23
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public PGPSecretKey getSecretKey( String identityId )
{
    if ( StringUtils.isBlank( identityId ) )
    {
        identityId = keyData.getManHostId();
    }

    try
    {
        PGPSecretKeyRing secretKeyRing = getSecretKeyRing( identityId );

        if ( secretKeyRing != null )
        {
            return PGPKeyUtil.readSecretKey( secretKeyRing );
        }
        else
        {
            return null;
        }
    }
    catch ( Exception ex )
    {
        LOG.error( " ***** Error getting Secret key:" + ex.toString(), ex );
        return null;
    }
}
 
Example #24
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRing setKeyTrust( String sourceFingerprint, String targetFingerprint, int trustLevel )
{
    PGPSecretKeyRing sourceSecRing = getSecretKeyRingByFingerprint( sourceFingerprint );
    PGPPublicKeyRing targetPubRing = getPublicKeyRingByFingerprint( targetFingerprint );

    return setKeyTrust( sourceSecRing, targetPubRing, trustLevel );
}
 
Example #25
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 #26
Source File: PgpHelper.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public static Stream<PGPSecretKey> streamSecretKeys ( final InputStream input ) throws IOException, PGPException
{
    final Stream<PGPSecretKeyRing> s = streamSecretKeyring ( input );
    return s.flatMap ( k -> {
        final Iterator<?> i = k.getSecretKeys ();

        final Stream<?> ks = StreamSupport.stream ( Spliterators.spliteratorUnknownSize ( i, Spliterator.ORDERED ), false );

        return ks.map ( o -> (PGPSecretKey)o );
    } );
}
 
Example #27
Source File: PeerEnvironmentKeyTask.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public PeerEnvironmentKeyTask( final LocalPeer localPeer, final PGPSecretKeyRing envSecKeyRing,
                               final PGPPublicKeyRing localPeerSignedPEK, final Environment environment,
                               final Peer peer, final KeyManager keyManager )
{
    this.localPeer = localPeer;
    this.envSecKeyRing = envSecKeyRing;
    this.localPeerSignedPEK = localPeerSignedPEK;
    this.environment = environment;
    this.peer = peer;
    this.keyManager = keyManager;
}
 
Example #28
Source File: PgpHelper.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public static PGPSecretKey loadSecretKey ( final InputStream input, final String keyId ) throws IOException, PGPException
{
    final long keyIdNum = Long.parseUnsignedLong ( keyId, 16 );

    final BcPGPSecretKeyRingCollection keyrings = new BcPGPSecretKeyRingCollection ( PGPUtil.getDecoderStream ( input ) );

    final Iterator<?> keyRingIter = keyrings.getKeyRings ();
    while ( keyRingIter.hasNext () )
    {
        final PGPSecretKeyRing secretKeyRing = (PGPSecretKeyRing)keyRingIter.next ();

        final Iterator<?> secretKeyIterator = secretKeyRing.getSecretKeys ();
        while ( secretKeyIterator.hasNext () )
        {
            final PGPSecretKey key = (PGPSecretKey)secretKeyIterator.next ();

            if ( !key.isSigningKey () )
            {
                continue;
            }

            final long shortId = key.getKeyID () & 0xFFFFFFFFL;

            if ( key.getKeyID () != keyIdNum && shortId != keyIdNum )
            {
                continue;
            }

            return key;
        }
    }

    return null;
}
 
Example #29
Source File: RelationMessageManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public Relation decryptAndVerifyMessage( final String signedMessage, final String secretKeyId )
        throws UnsupportedEncodingException, RelationVerificationException
{
    try
    {
        KeyManager keyManager = securityManager.getKeyManager();
        EncryptionTool encryptionTool = securityManager.getEncryptionTool();

        PGPSecretKeyRing secretKeyRing = keyManager.getSecretKeyRing( secretKeyId );

        byte[] extractedText = encryptionTool.extractClearSignContent( signedMessage.getBytes() );
        byte[] decrypted = encryptionTool.decrypt( extractedText, secretKeyRing, "" );

        String decryptedMessage = new String( decrypted, StandardCharsets.UTF_8 );
        RelationImpl relation = JsonUtil.fromJson( decryptedMessage, RelationImpl.class );

        PGPPublicKeyRing publicKey = keyManager.getPublicKeyRing( relation.getKeyId() );
        if ( publicKey == null || !encryptionTool.verifyClearSign( signedMessage.getBytes(), publicKey ) )
        {
            throw new RelationVerificationException( "Relation message verification failed." );
        }

        return relation;
    }
    catch ( Exception ex )
    {
        throw new RelationVerificationException( "Relation verification failed.", ex );
    }
}
 
Example #30
Source File: EncryptionToolImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] decrypt( final byte[] message, PGPSecretKeyRing keyRing, String pwd ) throws PGPException
{
    if ( StringUtils.isBlank( pwd ) )
    {
        pwd = keyManager.getSecurityKeyData().getSecretKeyringPwd();
    }

    return PGPEncryptionUtil.decrypt( message, keyRing, pwd );
}