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

项目:base    文件:PGPEncryptionUtil.java   
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 );
}
项目:base    文件:PGPEncryptionUtil.java   
@SuppressWarnings( "unchecked" )
private static Iterator<PGPPublicKeyEncryptedData> getEncryptedObjects( final byte[] message ) throws IOException
{
    try
    {
        final PGPObjectFactory factory =
                new PGPObjectFactory( PGPUtil.getDecoderStream( new ByteArrayInputStream( message ) ),
                        new JcaKeyFingerprintCalculator() );
        final Object first = factory.nextObject();
        final Object list = ( first instanceof PGPEncryptedDataList ) ? first : factory.nextObject();
        return ( ( PGPEncryptedDataList ) list ).getEncryptedDataObjects();
    }
    catch ( IOException e )
    {
        throw new IOException( e );
    }
}
项目: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.");
}
项目:react-native-pgp    文件:PGPUtils.java   
static PGPSecretKey getSecretKey(String privateKeyData) throws IOException, PGPException {
  PGPPrivateKey privKey = null;
  try (InputStream privStream = new ArmoredInputStream(new ByteArrayInputStream(privateKeyData.getBytes("UTF-8")))) {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privStream), 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.");
}
项目:rug-resolver    文件:GpgSignatureVerifier.java   
/**
 * Verify a signature. Only return true if signature matches calculated signature of signedData
 * and if it was signed by the publicKey
 *
 * @param signedData
 * @param signature
 * @return
 */
public boolean verify(InputStream signedData, InputStream signature) {
    try {
        signature = PGPUtil.getDecoderStream(signature);
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(signature);
        PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0);
        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();
    }
    catch (Exception ex) {
        // can we put a logger here please?
        return false;
    }
}
项目: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    文件:PGPKeyHelper.java   
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." );
}
项目:java-binrepo-proxy    文件:PGPKeysCache.java   
public PGPPublicKey getKey(long keyID) throws IOException, PGPException {

        File keyFile = null;
        PGPPublicKey key = null;

        try {
            String path = String.format("%02X/%02X/%016X.asc",
                    (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID);

            keyFile = new File(cachePath, path);
            if (!keyFile.exists()) {
                receiveKey(keyFile, keyID);
            }

            InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile));
            PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator());
            key = pgpRing.getPublicKey(keyID);
        } finally {
            if (key == null) {
                deleteFile(keyFile);
            }
        }
        return key;
    }
项目: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");
}
项目:nexus-repository-apt    文件:AptSigningFacet.java   
public byte[] signExternal(String input) throws IOException, PGPException {
  PGPSecretKey signKey = readSecretKey();
  PGPPrivateKey privKey = signKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
  PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
      new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
  sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey);

  ByteArrayOutputStream buffer = new ByteArrayOutputStream();

  try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
    BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    sigGenerator.update(input.getBytes(Charsets.UTF_8));
    sigGenerator.generate().encode(bOut);
  }

  return buffer.toByteArray();
}
项目:nexus-repository-apt    文件:AptSigningFacet.java   
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.");
}
项目:Camel    文件:PGPDataFormatTest.java   
static PGPSecretKey readSecretKey() throws Exception {
    InputStream input = new ByteArrayInputStream(getSecKeyRing());
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input),
                                                                       new BcKeyFingerprintCalculator());

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

        @SuppressWarnings("rawtypes")
        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.");
}
项目: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.");
}
项目:jerkar    文件:PgpUtils.java   
private static List<PGPSecretKeyRing> extractSecrectKeyRings(InputStream inputStream) {

        InputStream decodedInput;
        try {
            decodedInput = PGPUtil.getDecoderStream(inputStream);
        } catch (final IOException e) {
            throw JkUtilsThrowable.unchecked(e);
        }
        final KeyFingerPrintCalculator fingerPrintCalculator = new JcaKeyFingerprintCalculator();
        final InnerPGPObjectFactory pgpFact = new InnerPGPObjectFactory(decodedInput,
                fingerPrintCalculator);
        PGPSecretKeyRing secKeyRing;
        final List<PGPSecretKeyRing> result = new LinkedList<>();
        while ((secKeyRing = pgpFact.nextSecretKey()) != null) {
            result.add(secKeyRing);
        }
        return result;
    }
项目:geocaching    文件:PublicKeyCreator.java   
public PGPPublicKey createKeyFrom(InputStream in) throws IOException, PGPException {

    InputStream pgpData = PGPUtil.getDecoderStream(in);

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(pgpData), 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.");
}
项目:vertx-http-service-factory    文件:PGPHelper.java   
/**
 * Verify a PGP signature.
 *
 * @param file the file
 * @param signature the signature
 * @param key the public key
 * @return true if the signature is verified
 * @throws Exception anything preventing the verification to happen
 */
public static boolean verifySignature(
    InputStream file,
    InputStream signature,
    PGPPublicKey key)
    throws Exception {
  InputStream sigInputStream = PGPUtil.getDecoderStream(signature);
  PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream, new BcKeyFingerprintCalculator());
  PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject();
  PGPSignature pgpSignature = sigList.get(0);
  pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), key);
  try (InputStream inArtifact = new BufferedInputStream(file)) {

    int t;
    while ((t = inArtifact.read()) >= 0) {
      pgpSignature.update((byte) t);
    }
  }
  return pgpSignature.verify();
}
项目:bouncycastle    文件:PGPCryptoTools.java   
public static final List<String> listCertifications(File publicKeyFile) throws IOException {
        FileInputStream keyInputStream = new FileInputStream(publicKeyFile);
        List<String> keyIds = new ArrayList<String>();

        PGPPublicKeyRing pgpPubRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(keyInputStream), new JcaKeyFingerprintCalculator());
        PGPPublicKey pubKey = pgpPubRing.getPublicKey();

        @SuppressWarnings("unchecked")
        Iterator<PGPSignature> sigIter = pubKey.getSignatures();
        while (sigIter.hasNext()) {
                PGPSignature pgpSig = sigIter.next();
                long keyId = pgpSig.getKeyID();
                keyIds.add(Long.toHexString(keyId).toUpperCase());
        }

        return keyIds;
}
项目:ant-spk    文件:OpenPGPSecretKey.java   
public OpenPGPSecretKey(String keyId, InputStream secretKeyRing, char[] password) throws IOException {
    PGPObjectFactory pgpObjectFactory = new BcPGPObjectFactory(PGPUtil.getDecoderStream(secretKeyRing));

    for (Object it = pgpObjectFactory.nextObject(); it != null; it = pgpObjectFactory.nextObject()) {
        PGPSecretKeyRing pgpSecretKeyRing = (PGPSecretKeyRing) it;
        PGPSecretKey pgpSecretKey = pgpSecretKeyRing.getSecretKey();

        if (keyId == null || keyId.isEmpty() || Long.valueOf(keyId, 16) == (pgpSecretKey.getKeyID() & MASK)) {
            this.secretKey = pgpSecretKey;
            break;
        }
    }

    // sanity check
    if (secretKey == null) {
        throw new IllegalArgumentException("Secret key " + keyId + " not found");
    }

    this.password = password;
}
项目:CryptMeme    文件:PGPECDHTest.java   
public void performTest()
    throws Exception
{
    PGPUtil.setDefaultProvider("BC");

    //
    // Read the public key
    //
    PGPPublicKeyRing        pubKeyRing = new PGPPublicKeyRing(testPubKey, new JcaKeyFingerprintCalculator());

    doBasicKeyRingCheck(pubKeyRing);

    //
    // Read the private key
    //
    PGPSecretKeyRing        secretKeyRing = new PGPSecretKeyRing(testPrivKey, new JcaKeyFingerprintCalculator());

    testDecrypt(secretKeyRing);

    encryptDecryptTest();

    generate();
}
项目:crackgpg    文件:GpgPassphraseChecker.java   
private static PGPSecretKey readSecretKey(InputStream input, String keyId)
        throws IOException, PGPException {
    for (@SuppressWarnings("unchecked")
    Iterator<PGPSecretKeyRing> keyRingIter = new PGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(input)).getKeyRings(); keyRingIter
            .hasNext();) {
        for (@SuppressWarnings("unchecked")
        Iterator<PGPSecretKey> keyIter = keyRingIter.next().getSecretKeys(); keyIter
                .hasNext();) {
            PGPSecretKey key = keyIter.next();
            String id = bytArrayToHex(key.getPublicKey().getFingerprint());
            if ((keyId == null || keyId.equalsIgnoreCase(id.substring(id
                    .length() - 8))) && key.isSigningKey()) {
                return key;
            }
        }
    }
    throw new IllegalArgumentException("No signing key in keyring");
}
项目:pgpverify-maven-plugin    文件:PGPKeysCache.java   
PGPPublicKey getKey(long keyID) throws IOException, PGPException {

        File keyFile = null;
        PGPPublicKey key = null;

        try {
            String path = String.format("%02X/%02X/%016X.asc",
                    (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID);

            keyFile = new File(cachePath, path);
            if (!keyFile.exists()) {
                receiveKey(keyFile, keyID);
            }

            InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile));
            PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator());
            key = pgpRing.getPublicKey(keyID);
        } finally {
            if (key == null) {
                deleteFile(keyFile);
            }
        }
        return key;
    }
项目:cloudstore    文件:PGPVerifier.java   
private PGPSignatureList readSignatureFile(final File signatureFile) throws PGPVerifyException {
    AssertUtil.assertNotNull(signatureFile, "signatureFile");
    if (!signatureFile.isFile() || !signatureFile.canRead())
        throw new PGPVerifyException("The signature-file does not exist or is not readable: " + signatureFile.getAbsolutePath());

    try {
        final InputStream in = new BufferedInputStream(castStream(signatureFile.createInputStream()));
        try {
            final PGPObjectFactory objectFactory = new PGPObjectFactory(
                    PGPUtil.getDecoderStream(in), new BcKeyFingerprintCalculator());
            final PGPSignatureList sl = (PGPSignatureList) objectFactory.nextObject();
            return sl;
        } finally {
            in.close();
        }
    } catch (final Exception e) {
        throw new PGPVerifyException(signatureFile.getAbsolutePath() + ": " + e, e);
    }
}
项目:irma_future_id    文件:PGPECDHTest.java   
public void performTest()
    throws Exception
{
    PGPUtil.setDefaultProvider("BC");

    //
    // Read the public key
    //
    PGPPublicKeyRing        pubKeyRing = new PGPPublicKeyRing(testPubKey, new JcaKeyFingerprintCalculator());

    doBasicKeyRingCheck(pubKeyRing);

    //
    // Read the private key
    //
    PGPSecretKeyRing        secretKeyRing = new PGPSecretKeyRing(testPrivKey, new JcaKeyFingerprintCalculator());

    generate();
}
项目:appframework    文件:AbstractPGPEncryptor.java   
protected static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {

        BcPGPPublicKeyRingCollection pgpPub = new BcPGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(in));
        in.close();

        Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();
        while (rIt.hasNext()) {
            PGPPublicKeyRing kRing = rIt.next();
            Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();

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

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

        throw new IllegalArgumentException("Can't find encryption key in key ring.");
    }
项目:bc-java    文件:PGPECDHTest.java   
public void performTest()
    throws Exception
{
    PGPUtil.setDefaultProvider("BC");

    //
    // Read the public key
    //
    PGPPublicKeyRing        pubKeyRing = new PGPPublicKeyRing(testPubKey, new JcaKeyFingerprintCalculator());

    doBasicKeyRingCheck(pubKeyRing);

    //
    // Read the private key
    //
    PGPSecretKeyRing        secretKeyRing = new PGPSecretKeyRing(testPrivKey, new JcaKeyFingerprintCalculator());

    generate();
}
项目:whois    文件:PgpSignedMessage.java   
public static PgpSignedMessage parse(final String signedContent, final String signature, final Charset charset) {
    try {
        final byte[] content = canonicalise(signedContent.getBytes());
        final ByteArrayInputStream signatureIn = new ByteArrayInputStream(signature.getBytes(charset));
        final InputStream decoderStream = PGPUtil.getDecoderStream(signatureIn);
        if (decoderStream instanceof ArmoredInputStream) {
            final ArmoredInputStream armoredInputStream = (ArmoredInputStream) decoderStream;
            while (true) {
                if (!(armoredInputStream.isClearText() && armoredInputStream.read() != -1)) {
                    break;
                }
            }
        }

        final byte[] signatureBytes = FileCopyUtils.copyToByteArray(signatureIn);
        return new PgpSignedMessage(content, signatureBytes, false);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:Reer    文件:PgpSignatory.java   
public PGPSignatureGenerator createSignatureGenerator() {
    try {
        PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
        generator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
        return generator;
    } catch (PGPException e) {
        throw new UncheckedException(e);
    }
}
项目:saveOrganizer    文件:KeyIO.java   
public static PGPSecretKey readSecretKey(InputStream in)
    throws IOException, PGPException
{
    in = PGPUtil.getDecoderStream(in);
    PGPSecretKeyRingCollection keyRingCollection = new PGPSecretKeyRingCollection(in, new JcaKeyFingerprintCalculator());

    //
    // We just loop through the collection till we find a key suitable for signing.
    // In the real world you would probably want to be a bit smarter about this.
    //
    PGPSecretKey secretKey = null;

    Iterator<PGPSecretKeyRing> rIt = keyRingCollection.getKeyRings();
    while (secretKey == null && rIt.hasNext()) {
        PGPSecretKeyRing keyRing = rIt.next();
        Iterator<PGPSecretKey> kIt = keyRing.getSecretKeys();
        while (secretKey == null && kIt.hasNext()) {
            PGPSecretKey key = kIt.next();
            if (key.isSigningKey()) {
                secretKey = key;
            }
        }
    }

    // Validate secret key
    if (secretKey == null) {
        throw new IllegalArgumentException("Can't find private key in the key ring.");
    }
    if (!secretKey.isSigningKey()) {
        throw new IllegalArgumentException("Private key does not allow signing.");
    }
    if (secretKey.getPublicKey().isRevoked()) {
        throw new IllegalArgumentException("Private key has been revoked.");
    }

    return secretKey;
}
项目:saveOrganizer    文件:PGPUtils.java   
static byte[] compressFile(String fileName, int algorithm) throws IOException
{
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
    comData.close();
    return bOut.toByteArray();
}
项目: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    文件:PGPUtils.java   
/**
 * A simple routine that opens a key ring file and loads the first available
 * key suitable for signature generation.
 * 
 * @param input
 *            stream to read the secret key ring collection from.
 * @return a secret key.
 * @throws IOException
 *             on a problem with using the input stream.
 * @throws PGPException
 *             if there is an issue parsing the input stream.
 */
static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException
{
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(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 = 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.");
}
项目:webmethods-integrationserver-pgpencryption    文件:PGPKeyReader.java   
public static PGPPublicKey readPublicKey(InputStream in, int algorithm)
        throws IOException, PGPException {

    // Get the decoder stream (auto-disarming)
    in = PGPUtil.getDecoderStream(in);

    // Open the key ring
    PGPPublicKeyRingCollection coll = new PGPPublicKeyRingCollection(in);

    // Find key encryption key for algorithm, if given
    return readPublicKey(coll, algorithm);
}
项目:webmethods-integrationserver-pgpencryption    文件:PGPKeyReader.java   
public static PGPSecretKey readSecretKey(InputStream in)
        throws IOException, PGPException, NoSuchProviderException {

    // Get the decoder stream (auto-disarming)
    in = PGPUtil.getDecoderStream(in);

    // Open the key ring
    PGPSecretKeyRingCollection coll = new PGPSecretKeyRingCollection(in);

    // Find key
    return readSecretKey(coll);
}
项目:whistleblower    文件:CryptographyHandler.java   
private PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException
{
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
            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 = 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.");
}
项目:jfwknop    文件:GpgUtils.java   
static public void addPrivateKeyToKeyring(final String gpgHomeDirectory, final String keyringFile) throws FileNotFoundException, IOException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    // Read user secret keyring
    FileInputStream inPriv = new FileInputStream(gpgHomeDirectory + "/secring.gpg");
    PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection(inPriv, new JcaKeyFingerprintCalculator());

    // Read keys (public and private) from armored file
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
        PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator());

    // Iterate over the keys
    Iterator keyRingIter = pgpSec.getKeyRings();
    while (keyRingIter.hasNext()) {
        PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
        privRings = PGPSecretKeyRingCollection.addSecretKeyRing(privRings, keyRing);

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

            if (key.isSigningKey()) {
                System.out.println("Private key imported " + Long.toHexString(key.getKeyID()).toUpperCase());
            }
        }
    }

    try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/secring.gpg"))) {
        privRings.encode(out);
    }
}
项目: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);
    }
}
项目: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    文件:PGPEncryptionUtilTest.java   
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() );
        }
    }
}
项目: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 );
}