Java 类org.bouncycastle.openpgp.PGPPublicKeyRing 实例源码

项目:saveOrganizer    文件:KeyIO.java   
public static PGPPublicKey readPublicKey(InputStream in)
   throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);

PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator() );
Iterator rIt = pgpPub.getKeyRings();

while (rIt.hasNext()) {
   PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
   Iterator kIt = kRing.getPublicKeys();

   while (kIt.hasNext()) {
       PGPPublicKey k = (PGPPublicKey) kIt.next();

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

throw new IllegalArgumentException(
       "Can't find encryption key in key ring.");
}
项目:jpgpj    文件:Ring.java   
/**
 * 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 {
    ArrayList<Key> keys = new ArrayList<Key>();

    Iterator packets = parse(unarmor(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));
    }

    this.keys.addAll(keys);
    return keys;
}
项目:gwt-crypto    文件:BcPGPKeyRingTest.java   
private void test11()
    throws Exception
{
    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(subKeyBindingKey, new BcKeyFingerprintCalculator());
    Iterator         it = pubRing.getPublicKeys();

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

        if (key.getValidSeconds() != 0)
        {
            fail("expiration time non-zero");
        }
    }
}
项目:base    文件:PGPKeyUtil.java   
public static PGPPublicKey readPublicKey( PGPPublicKeyRing keyRing ) throws PGPException
{
    try
    {
        Iterator keyIter = keyRing.getPublicKeys();

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

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

    return null;
}
项目:Camel    文件:PGPDataFormatUtil.java   
/**
 * Determines a public key from the keyring collection which has a certain
 * key ID and which has a User ID which contains at least one of the User ID
 * parts.
 * 
 * @param keyId
 *            key ID
 * @param userIdParts
 *            user ID parts, can be empty, than no filter on the User ID is
 *            executed
 * @param publicKeyringCollection
 *            keyring collection
 * @return public key or <code>null</code> if no fitting key is found
 * @throws PGPException
 */
@SuppressWarnings("unchecked")
public static PGPPublicKey getPublicKeyWithKeyIdAndUserID(long keyId, List<String> userIdParts, PGPPublicKeyRingCollection publicKeyringCollection)
    throws PGPException {
    PGPPublicKeyRing publicKeyring = publicKeyringCollection.getPublicKeyRing(keyId);
    if (publicKeyring == null) {
        LOG.debug("No public key found for key ID {}.", Long.toString(keyId));
        return null;
    }
    // publicKey can be a subkey the user IDs must therefore be provided by the primary/master key
    if (isAllowedKey(userIdParts, publicKeyring.getPublicKey().getUserIDs())) {
        return publicKeyring.getPublicKey(keyId);
    } else {
        return null;
    }
}
项目:nomulus    文件:PgpHelper.java   
/**
 * 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 {
    // Safe by specification.
    @SuppressWarnings("unchecked")
    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 with query %s failed: %s", query, e.getMessage()));
  }
}
项目:gvnix1    文件:PgpServiceImpl.java   
public PGPPublicKeyRing getPublicKey(final PgpKeyId keyId) {
    Validate.notNull(keyId, "Key ID required");
    InputStream in = null;
    try {
        final URL lookup = getKeyServerUrlToRetrieveKeyId(keyId);
        in = urlInputStreamService.openConnection(lookup);
        return getPublicKey(in);
    }
    catch (final Exception e) {
        throw new IllegalStateException("Public key ID '" + keyId
                + "' not available from key server", e);
    }
    finally {
        IOUtils.closeQuietly(in);
    }
}
项目:base    文件:PGPKeyHelper.java   
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." );
}
项目:base    文件:RestServiceImpl.java   
@Override
public void updateEnvironmentKey( final PublicKeyContainer publicKeyContainer )
{
    try
    {
        Preconditions.checkNotNull( publicKeyContainer );
        Preconditions.checkArgument( !Strings.isNullOrEmpty( publicKeyContainer.getKey() ) );
        Preconditions.checkArgument( !Strings.isNullOrEmpty( publicKeyContainer.getHostId() ) );
        Preconditions.checkNotNull( publicKeyContainer.getFingerprint() );

        final PGPPublicKeyRing pubKeyRing = PGPKeyUtil.readPublicKeyRing( publicKeyContainer.getKey() );
        localPeer.updatePeerEnvironmentPubKey( new EnvironmentId( publicKeyContainer.getHostId() ), pubKeyRing );
    }
    catch ( Exception e )
    {
        LOGGER.error( e.getMessage(), e );
        throw new WebApplicationException( Response.serverError().entity( e.getMessage() ).build() );
    }
}
项目:base    文件:RestServiceImpl.java   
@Override
public void addInitiatorPeerEnvironmentPubKey( final String keyId, final String pek )
{
    try
    {
        Preconditions.checkArgument( !Strings.isNullOrEmpty( keyId ) );
        Preconditions.checkArgument( !Strings.isNullOrEmpty( pek ) );

        PGPPublicKeyRing pubKeyRing = PGPKeyUtil.readPublicKeyRing( pek );
        localPeer.addPeerEnvironmentPubKey( keyId, pubKeyRing );
    }
    catch ( Exception e )
    {
        LOGGER.error( e.getMessage(), e );
        throw new WebApplicationException( Response.serverError().entity( e.getMessage() ).build() );
    }
}
项目:base    文件:SecurityManagerRestImpl.java   
@Override
public Response getPublicKeyId( final String identityId )
{
    try
    {
        PGPPublicKeyRing pubRing = securityManager.getKeyManager().getPublicKeyRing( identityId );
        PGPPublicKey key = pubRing.getPublicKey();

        if ( key == null )
        {
            logger.info( " ************* Public Key not found with id:" + identityId );
            return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
        }
        else
        {
            return Response.ok( PGPKeyUtil.encodeNumericKeyId( key.getKeyID() ) ).build();
        }
    }
    catch ( Exception ex )
    {
        logger.info( " ************* Error ! Public Key not found with id:" + identityId, ex );
        return Response.status( Response.Status.NOT_FOUND ).entity( "Object Not found" ).build();
    }
}
项目:base    文件:RemotePeerImpl.java   
@Override
public void addPeerEnvironmentPubKey( final String keyId, final PGPPublicKeyRing pek ) throws PeerException
{
    Preconditions.checkNotNull( keyId, "Invalid key ID" );
    Preconditions.checkNotNull( pek, "Public key ring is null" );


    try
    {
        String exportedPubKeyRing = securityManager.getEncryptionTool().armorByteArrayToString( pek.getEncoded() );
        peerWebClient.addPeerEnvironmentPubKey( keyId, exportedPubKeyRing );
    }
    catch ( IOException | PGPException e )
    {
        throw new PeerException( e.getMessage() );
    }
}
项目:gvnix1    文件:PgpServiceImpl.java   
/**
 * Simply stores the key ID in {@link #discoveredKeyIds} for future
 * reference of all Key IDs we've come across. This method uses a
 * {@link PGPPublicKeyRing} to ensure the input is actually a valid key,
 * plus locating any key IDs that have signed the key.
 * <p>
 * Please note {@link #discoveredKeyIds} is not used for any key functions
 * of this class. It is simply for user interface convenience.
 * 
 * @param keyRing the key ID to store (required)
 */
@SuppressWarnings("unchecked")
private void rememberKey(final PGPPublicKeyRing keyRing) {
    final PGPPublicKey key = keyRing.getPublicKey();
    if (key != null) {
        final PgpKeyId keyId = new PgpKeyId(key);
        discoveredKeyIds.add(keyId);
        final Iterator<String> userIdIterator = key.getUserIDs();
        while (userIdIterator.hasNext()) {
            final String userId = userIdIterator.next();
            final Iterator<PGPSignature> signatureIterator = key
                    .getSignaturesForID(userId);
            while (signatureIterator.hasNext()) {
                final PGPSignature signature = signatureIterator.next();
                final PgpKeyId signatureKeyId = new PgpKeyId(signature);
                discoveredKeyIds.add(signatureKeyId);
            }
        }
    }
}
项目:gvnix1    文件:PgpServiceImpl.java   
public PGPPublicKeyRing getPublicKey(final InputStream in) {
    Object obj;
    try {
        final PGPObjectFactory pgpFact = new PGPObjectFactory(
                PGPUtil.getDecoderStream(in));
        obj = pgpFact.nextObject();
    }
    catch (final Exception e) {
        throw new IllegalStateException(e);
    }

    if (obj instanceof PGPPublicKeyRing) {
        final PGPPublicKeyRing keyRing = (PGPPublicKeyRing) obj;
        rememberKey(keyRing);
        return keyRing;
    }

    throw new IllegalStateException("Pblic key not available");
}
项目:base    文件:KeyManagerImpl.java   
@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;
}
项目:base    文件:KeyManagerImpl.java   
@Override
public void savePublicKeyRing( String identityId, int type, String keyringAsASCII )
{
    try
    {
        PGPPublicKeyRing pgpPublicKeyRing = PGPKeyUtil.readPublicKeyRing( keyringAsASCII );

        if ( pgpPublicKeyRing != null )
        {
            savePublicKeyRing( identityId, type, pgpPublicKeyRing );
        }
    }
    catch ( Exception ex )
    {
        LOG.error( " ******** Error storing Public key:" + ex.toString(), ex );
    }
}
项目:base    文件:KeyManagerImpl.java   
@Override
public PGPPublicKey getPublicKey( String identityId )
{
    PGPPublicKeyRing publicKeyRing;

    try
    {
        publicKeyRing = getPublicKeyRing( identityId );

        if ( publicKeyRing != null )
        {
            return PGPKeyUtil.readPublicKey( publicKeyRing );
        }
        else
        {
            LOG.info( "********* Public key not found with identityId:" + identityId );
            return null;
        }
    }
    catch ( PGPException e )
    {
        return null;
    }
}
项目:base    文件:KeyManagerImpl.java   
@Override
public PGPPublicKeyRing getPublicKeyRingByFingerprint( String fingerprint )
{
    try
    {
        byte[] aKeyData = keyServer.getPublicKeyByFingerprint( fingerprint ).getKeyData();

        if ( aKeyData != null )
        {
            return PGPKeyUtil.readPublicKeyRing( aKeyData );
        }
    }
    catch ( Exception e )
    {
        return null;
    }
    return null;
}
项目:base    文件:EncryptionToolImpl.java   
/**
 * Signs a public key
 *
 * @param publicKeyRing a public key ring containing the single public key to sign
 * @param id the id we are certifying against the public key
 * @param secretKey the signing key
 * @param secretKeyPassword the signing key password
 *
 * @return a public key ring with the signed public key
 */
@Override
public PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
                                       String secretKeyPassword )
{
    try
    {
        if ( Strings.isNullOrEmpty( secretKeyPassword ) )
        {
            secretKeyPassword = keyManager.getSecurityKeyData().getSecretKeyringPwd();
        }

        return PGPEncryptionUtil.signPublicKey( publicKeyRing, id, secretKey, secretKeyPassword );
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new ActionFailedException( e );
    }
}
项目:base    文件:EnvironmentManagerImpl.java   
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 );
    }
}
项目:base    文件:PeerEnvironmentKeyTask.java   
@Override
public Peer call() throws Exception
{
    RelationLinkDto relationLinkDto = new RelationLinkDto( environment );
    PublicKeyContainer publicKeyContainer = peer.createPeerEnvironmentKeyPair( relationLinkDto );

    PGPPublicKeyRing pubRing = getPublicKey( publicKeyContainer );

    PGPPublicKeyRing signedPEK = keyManager.setKeyTrust( envSecKeyRing, pubRing, KeyTrustLevel.FULL.getId() );

    peer.updatePeerEnvironmentPubKey( environment.getEnvironmentId(), signedPEK );
    peer.addPeerEnvironmentPubKey( localPeer.getId() + "_" + environment.getEnvironmentId().getId(),
            localPeerSignedPEK );

    localPeer.addPeerEnvironmentPubKey( peer.getId() + "_" + environment.getEnvironmentId().getId(), signedPEK );

    return peer;
}
项目:Camel    文件:PGPDataFormatTest.java   
static PGPPublicKey readPublicKey(String keyringPath) throws Exception {
    InputStream input = new ByteArrayInputStream(getKeyRing(keyringPath));
    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input),
                                                                       new BcKeyFingerprintCalculator());

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();
    while (keyRingIter.hasNext()) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        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.");
}
项目:base    文件:EnvironmentManagerImplTest.java   
@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 );
}
项目:saveOrganizer    文件:PGPUtils.java   
/**
 * A simple routine that opens a key ring file and loads the first available
 * key suitable for encryption.
 * 
 * @param input
 *            data stream containing the public key data
 * @return the first public key found.
 * @throws IOException
 * @throws PGPException
 */
static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException
{
    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input),
            new JcaKeyFingerprintCalculator());

    //
    // we just loop through the collection till we find a key suitable for
    // encryption, in the real
    // world you would probably want to be a bit smarter about this.
    //

    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.");
}
项目:saveOrganizer    文件:KeyGenPane.java   
@Override
protected Void doInBackground() throws Exception
{
    Main.logger.info("Neue Schlüssel werden generiert...");
    PGPKeyRingGenerator pkg = RSAGen.generateKeyRingGenerator(mail, pass, this);
    PGPPublicKeyRing pkr = pkg.generatePublicKeyRing();
    PGPSecretKeyRing skr = pkg.generateSecretKeyRing();
    Main.psk = skr.getSecretKey();
    Iterator<PGPPublicKey> rIt = pkr.getPublicKeys();

    // Sucht den Verschlüsselungsschlüssel
    while (Main.ppk == null && rIt.hasNext())
    {
        PGPPublicKey temp_key = rIt.next();
        if (temp_key.isEncryptionKey())
        {
            Main.ppk = temp_key;
            break;
        }
    }

    PBESecretKeyDecryptor secretKeyDecryptor = new JcePBESecretKeyDecryptorBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pass);
    Main.pprk = Main.psk.extractPrivateKey(secretKeyDecryptor);
    setProgress(90);
    // Speichern der Schlüssel
    PGPSecretKeyRing pskr = pkg.generateSecretKeyRing();
    ArmoredOutputStream secout = new ArmoredOutputStream(
            new BufferedOutputStream(new FileOutputStream(Main.secKey)));
    // Geheimer Schlüssel
    pskr.encode(secout);
    secout.close();

    ArmoredOutputStream pubout = new ArmoredOutputStream(
            new BufferedOutputStream(new FileOutputStream(Main.pubKey)));
    pkr.encode(pubout);
    pubout.close();
    setProgress(100);
    return null;
}
项目:webmethods-integrationserver-pgpencryption    文件:PGPKeyReader.java   
public static String getKeyInfo(PGPPublicKeyRingCollection coll) {

    StringBuffer info = new StringBuffer();

    // Iterate through key rings
    Iterator<?> rings = coll.getKeyRings();
    while (rings.hasNext()) {
        PGPPublicKeyRing ring = (PGPPublicKeyRing)rings.next();
        Iterator<?> keys = ring.getPublicKeys();
        while (keys.hasNext()) {
            info.append(getKeyInfo((PGPPublicKey)keys.next())).append("\n");
        }
    }
    return info.toString();
}
项目:react-native-pgp    文件:Module.java   
@ReactMethod
public void generateKeyPair(final String userId, final int numBits, final String passphrase, Promise promise) {
  Log.d("ReactNativePGP", "generateKeyPair");
  try {
    WritableMap resultMap = Arguments.createMap();
    PGPKeyRingGenerator keyGenerator = PGPUtils.generateKeyRingGenerator(userId, numBits, passphrase.toCharArray());

    // public key
    PGPPublicKeyRing publicKeyRing              = keyGenerator.generatePublicKeyRing();
    ByteArrayOutputStream publicKeyOutputStream = new ByteArrayOutputStream();
    ArmoredOutputStream armoredPubOutputStream  = new ArmoredOutputStream(publicKeyOutputStream);

    publicKeyRing.encode(armoredPubOutputStream);
    armoredPubOutputStream.close();
    resultMap.putString("publicKey", publicKeyOutputStream.toString("UTF-8"));

    // private key
    PGPSecretKeyRing secretKeyRing               = keyGenerator.generateSecretKeyRing();
    ByteArrayOutputStream privateKeyOutputStream = new ByteArrayOutputStream();
    ArmoredOutputStream armoredPrivOutputStream  = new ArmoredOutputStream(privateKeyOutputStream);

    secretKeyRing.encode(armoredPrivOutputStream);
    armoredPrivOutputStream.close();
    resultMap.putString("privateKey", privateKeyOutputStream.toString("UTF-8"));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secretKeyRing.getPublicKey().getFingerprint()));

    promise.resolve(resultMap);
  } catch(Exception e) {
    promise.reject(new Exception(e.getMessage()));
  }
}
项目:jfwknop    文件:GpgUtils.java   
static public void addPublicKeyToKeyring(String gpgHomeDirectory, String keyringFile) throws FileNotFoundException, IOException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    FileInputStream in = new FileInputStream(gpgHomeDirectory + "/pubring.gpg");
    PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator());

    PGPPublicKeyRing pgpKeyring = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator());
    pubRings = PGPPublicKeyRingCollection.addPublicKeyRing(pubRings, pgpKeyring);

    try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/pubring.gpg"))) {
        pubRings.encode(out);
    }
}
项目:jpgpj    文件:Ring.java   
protected Key newKey(PGPPublicKeyRing ring) throws PGPException {
    ArrayList<Subkey> subkeys = new ArrayList<Subkey>();

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

    return newKey(subkeys);
}
项目:gvnix1    文件:PgpServiceImpl.java   
private PGPPublicKeyRing trust(final PGPPublicKeyRing keyRing) {
    rememberKey(keyRing);

    // Get the keys we currently trust
    final List<PGPPublicKeyRing> trusted = getTrustedKeys();

    // Do not store if the first key is revoked
    Validate.validState(
            !keyRing.getPublicKey().isRevoked(),
            "The public key ID '%s' has been revoked and cannot be trusted",
            new PgpKeyId(keyRing.getPublicKey()));

    // trust it and write back to disk
    trusted.add(keyRing);
    OutputStream fos = null;
    try {
        final PGPPublicKeyRingCollection newCollection = new PGPPublicKeyRingCollection(
                trusted);
        fos = new FileOutputStream(ROO_PGP_FILE);
        newCollection.encode(fos);
    }
    catch (final Exception e) {
        throw new IllegalStateException(e);
    }
    finally {
        IOUtils.closeQuietly(fos);
    }
    return keyRing;
}
项目:gwt-crypto    文件:BcPGPKeyRingTest.java   
public void test6()
    throws Exception
{
    PGPPublicKeyRingCollection  pubRings = new PGPPublicKeyRingCollection(pub6, new BcKeyFingerprintCalculator());
    Iterator                    rIt = pubRings.getKeyRings();

    while (rIt.hasNext())
    {
        PGPPublicKeyRing    pgpPub = (PGPPublicKeyRing)rIt.next();
        Iterator            it = pgpPub.getPublicKeys();
        while (it.hasNext())
        {
            PGPPublicKey    k = (PGPPublicKey)it.next();

            if (k.getKeyID() == 0x5ce086b5b5a18ff4L)
            {
                int             count = 0;
                Iterator        sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION);
                while (sIt.hasNext())
                {
                    PGPSignature sig = (PGPSignature)sIt.next();
                    count++;
                }

                if (count != 1)
                {
                    fail("wrong number of revocations in test6.");
                }
            }
        }
    }

    byte[]    encRing = pubRings.getEncoded();
}
项目:gwt-crypto    文件:BcPGPKeyRingTest.java   
private void testPublicKeyRingWithX509()
    throws Exception
{
    checkPublicKeyRingWithX509(pubWithX509);

    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(pubWithX509, new BcKeyFingerprintCalculator());

    checkPublicKeyRingWithX509(pubRing.getEncoded());
}
项目:gwt-crypto    文件:BcPGPKeyRingTest.java   
private void checkPublicKeyRingWithX509(byte[] keyRing)
    throws Exception
{
    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(keyRing, new BcKeyFingerprintCalculator());
    Iterator         it = pubRing.getPublicKeys();

    if (it.hasNext())
    {
        PGPPublicKey key = (PGPPublicKey)it.next();

        Iterator sIt = key.getSignatures();

        if (sIt.hasNext())
        {
            PGPSignature sig = (PGPSignature)sIt.next();
            if (sig.getKeyAlgorithm() != 100)
            {
                fail("experimental signature not found");
            }
            if (!areEqual(sig.getSignature(), Hex.decode("000101")))
            {
                fail("experimental encoding check failed");
            }
        }
        else
        {
            fail("no signature found");
        }
    }
    else
    {
        fail("no key found");
    }
}
项目:base    文件:PGPEncryptionUtil.java   
public static KeyPair generateKeyPair( String userId, String secretPwd, boolean armored ) throws PGPException
{
    try
    {
        KeyPair keyPair = new KeyPair();

        PGPKeyRingGenerator krgen = generateKeyRingGenerator( userId, secretPwd, keyPair );

        // Generate public key ring
        PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
        ByteArrayOutputStream pubOut = new ByteArrayOutputStream();
        pkr.encode( pubOut );
        pubOut.close();

        // Generate private key
        PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
        ByteArrayOutputStream secOut = new ByteArrayOutputStream();
        skr.encode( secOut );
        secOut.close();

        keyPair.setPubKeyring( armored ? armorByteArray( pubOut.toByteArray() ) : pubOut.toByteArray() );
        keyPair.setSecKeyring( armored ? armorByteArray( secOut.toByteArray() ) : secOut.toByteArray() );

        return keyPair;
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in generateKeyPair", e );
    }
}
项目:nomulus    文件:BouncyCastleTest.java   
@Test
public void testEncryptDecrypt_ExplicitStyle() throws Exception {
  int bufferSize = 64 * 1024;

  // Alice loads Bob's "publicKey" into memory.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  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.info("Encrypted data: " + dumpHex(encryptedData));

  // Bob loads his "privateKey" into memory.
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // 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);
    assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID());
    assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID());
    try (InputStream original =
        encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
      assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
          .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    }
  }
}
项目:base    文件:PGPEncryptionUtil.java   
/**
 * Signs a public key
 *
 * @param publicKeyRing a public key ring containing the single public key to sign
 * @param id the id we are certifying against the public key
 * @param secretKey the signing key
 * @param secretKeyPassword the signing key password
 *
 * @return a public key ring with the signed public key
 */
public static PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
                                              String secretKeyPassword ) throws PGPException
{
    try
    {
        PGPPublicKey oldKey = publicKeyRing.getPublicKey();

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

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

        signatureGenerator.init( PGPSignature.DEFAULT_CERTIFICATION, pgpPrivKey );

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

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

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

        return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey );
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error signing public key", e );
    }
}
项目:base    文件:PGPEncryptionUtil.java   
public static PGPPublicKeyRing removeSignature( PGPPublicKeyRing keyToRemoveFrom,
                                                PGPPublicKey keySignatureToRemove ) throws PGPException
{
    try
    {
        PGPPublicKey oldKey = keyToRemoveFrom.getPublicKey();

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

        Iterator<PGPSignature> signIterator = oldKey.getSignatures();
        while ( signIterator.hasNext() )
        {
            PGPSignature signature = signIterator.next();
            signature.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ),
                    keySignatureToRemove );

            String sigId = PGPKeyUtil.encodeNumericKeyId( oldKey.getKeyID() );

            if ( signature.verifyCertification( sigId, oldKey ) )
            {
                PGPPublicKey updatedKey = PGPPublicKey.removeCertification( oldKey, signature );
                keyToRemoveFrom = PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, updatedKey );
            }
        }

        return keyToRemoveFrom;
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error removing signature", e );
    }
}
项目:Camel    文件:PGPDataFormatUtil.java   
public static List<PGPPublicKey> findPublicKeys(List<String> useridParts, boolean forEncryption, PGPPublicKeyRingCollection pgpPublicKeyringCollection) {
    List<PGPPublicKey> result = new ArrayList<PGPPublicKey>(useridParts.size());
    for (Iterator<PGPPublicKeyRing> keyRingIter = pgpPublicKeyringCollection.getKeyRings(); keyRingIter.hasNext();) {
        PGPPublicKeyRing keyRing = keyRingIter.next();
        PGPPublicKey primaryKey = keyRing.getPublicKey();
        String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey);
        if (foundKeyUserIdForUserIdPart == null) {
            LOG.debug("No User ID found in primary key with key ID {} containing one of the parts {}", primaryKey.getKeyID(),
                    useridParts);
            continue;
        }
        LOG.debug("User ID {} found in primary key with key ID {} containing one of the parts {}", new Object[] {
            foundKeyUserIdForUserIdPart[0], primaryKey.getKeyID(), useridParts });
        // add adequate keys to the result
        for (Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); keyIter.hasNext();) {
            PGPPublicKey key = keyIter.next();
            if (forEncryption) {
                if (isEncryptionKey(key)) {
                    LOG.debug("Public encryption key with key user ID {} and key ID {} added to the encryption keys",
                            foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
                    result.add(key);
                }
            } else if (!forEncryption && isSignatureKey(key)) {
                // not used!
                result.add(key);
                LOG.debug("Public key with key user ID {} and key ID {} added to the signing keys", foundKeyUserIdForUserIdPart[0],
                        Long.toString(key.getKeyID()));
            }
        }

    }

    return result;
}
项目:base    文件:PGPEncryptionUtilTest.java   
@Test
public void testVerifyKey() throws Exception
{

    PGPPublicKeyRing pgpPublicKey = PGPKeyUtil.readPublicKeyRing( findFile( PUBLIC_KEYRING ) );
    PGPSecretKey pgpSecretKey = PGPEncryptionUtil.findSecretKeyById( findFile( SECRET_KEYRING ), SECRET_KEY_ID );

    PGPPublicKeyRing signedPubKey =
            PGPEncryptionUtil.signPublicKey( pgpPublicKey, USER_ID, pgpSecretKey, SECRET_PWD );

    assertTrue( PGPEncryptionUtil
            .verifyPublicKey( signedPubKey.getPublicKey(), USER_ID, pgpSecretKey.getPublicKey() ) );
}
项目:base    文件:PGPEncryptionUtilTest.java   
@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 );
}