Java 类org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder 实例源码

项目:base    文件:PGPEncryptionUtil.java   
/**
 * ***********************************************
 */
private static PGPPrivateKey getPrivateKey( final PGPSecretKeyRingCollection keys, final long id,
                                            final String secretPwd )
{
    try
    {
        final PGPSecretKey key = keys.getSecretKey( id );
        if ( key != null )
        {
            return key.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider )
                                                                               .build( secretPwd.toCharArray() ) );
        }
    }
    catch ( final Exception e )
    {
        // Don't print the passphrase but do print null if thats what it was
        final String passphraseMessage = ( secretPwd == null ) ? "null" : "supplied";
        LOG.warn( "Unable to extract key " + id + " using " + passphraseMessage + " passphrase: {}",
                e.getMessage() );
    }
    return null;
}
项目:base    文件:PGPEncryptionUtil.java   
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey,
                                                                PGPSecretKey pgpSecretKey, String secretPwd,
                                                                String issuer, String subject, Date dateOfIssue,
                                                                Date dateOfExpiry, BigInteger serial )
        throws PGPException, CertificateException, IOException
{
    JcaPGPKeyConverter c = new JcaPGPKeyConverter();
    PublicKey publicKey = c.getPublicKey( pgpPublicKey );
    PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) );

    X509v3CertificateBuilder certBuilder =
            new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry,
                    new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) );
    byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded();
    CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" );

    return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) );
}
项目:base    文件:PGPEncryptionUtil.java   
/**
 * ***********************************************
 */
public static PGPPrivateKey getPrivateKey( final PGPSecretKey secretKey, final String secretPwd )
{
    Preconditions.checkNotNull( secretKey );
    Preconditions.checkNotNull( secretPwd );

    try
    {
        return secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
    }
    catch ( Exception e )
    {
        LOG.error( "Unable to extract key {}: {}", secretKey.getKeyID(), e.getMessage() );
    }

    return null;
}
项目: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();
}
项目:Camel    文件:PGPDataFormatTest.java   
private void createSignature(OutputStream out) throws Exception {
    PGPSecretKey pgpSec = readSecretKey();
    PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build(
            "sdude".toCharArray()));
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(),
            HashAlgorithmTags.SHA1).setProvider(getProvider()));

    sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    BCPGOutputStream bOut = new BCPGOutputStream(out);

    InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8"));

    int ch;
    while ((ch = fIn.read()) >= 0) {
        sGen.update((byte) ch);
    }

    fIn.close();

    sGen.generate().encode(bOut);

}
项目:desktopclient-java    文件:PGPUtils.java   
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);
    }
}
项目:izettle-toolbox    文件:PGP.java   
private static PGPPrivateKey findSecretKey(
        final PGPSecretKeyRingCollection keys,
        final long id,
        final String passphrase) {
    try {
        final PGPSecretKey key = keys.getSecretKey(id);
        if (key != null) {
            return key.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder()
                .setProvider(PROVIDER)
                    .build(passphrase.toCharArray()));
        }
    } catch (Exception e) {
        final String passphraseMessage = (passphrase == null) ? "null" : passphrase.length() + " character";
        throw new RuntimeException("Unable to extract key " + id + " using " + passphraseMessage + " passphrase", e);
    }
    return null;
}
项目: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;
}
项目:pgp-encryption-using-java    文件:PGPDecrypt.java   
private static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyId, char[] pass)
        throws PGPException, NoSuchProviderException{
    PGPSecretKey pgpSecretKey = pgpSec.getSecretKey(keyId);

    if (pgpSecretKey == null) return null;

    return pgpSecretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
项目:pgp-encryption-using-java    文件:PGPEncryptionKeys.java   
/**
 * A simple routine that extracts the private key from the secret key previously set
 * @param passPhrase password used to access the private key
 * @return a private key
 * @throws PGPException
 */
private PGPPrivateKey readPrivateKey(String passPhrase) throws PGPException{
    PGPPrivateKey privateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase.toCharArray()));

    if (privateKey != null)
        return privateKey;
    throw new IllegalArgumentException("No private key found in secret key");
}
项目: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    文件:PGPKeyHelper.java   
public static PGPPrivateKey readPrivateKey( InputStream is, String password ) throws PGPException, IOException
{
    PGPSecretKey secretKey = readSecretKey( is );

    return secretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider( "BC" ).build( password.toCharArray() ) );
}
项目:nexus-repository-apt    文件:AptSigningFacet.java   
public byte[] signInline(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.CANONICAL_TEXT_DOCUMENT, privKey);

  @SuppressWarnings("unchecked")
  Iterator<String> userIds = signKey.getUserIDs();
  if (userIds.hasNext()) {
    PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
    sigSubpacketGenerator.setSignerUserID(false, userIds.next());
    sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
  }

  String[] lines = input.split("\r?\n");
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
    aOut.beginClearText(PGPUtil.SHA256);

    boolean firstLine = true;
    for (String line : lines) {
      String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
      sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
      aOut.write((line + "\n").getBytes(Charsets.UTF_8));
      firstLine = false;
    }
    aOut.endClearText();

    BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    sigGenerator.generate().encode(bOut);
  }
  return buffer.toByteArray();
}
项目:Camel    文件:PGPDataFormatUtil.java   
public static PGPPrivateKey findPrivateKeyWithkeyId(long keyid, String passphrase, PGPPassphraseAccessor passphraseAccessor,
        String provider, PGPSecretKeyRingCollection pgpSec) throws PGPException {
    for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext();) {
        Object data = i.next();
        if (data instanceof PGPSecretKeyRing) {
            PGPSecretKeyRing keyring = (PGPSecretKeyRing) data;
            PGPSecretKey secKey = keyring.getSecretKey(keyid);
            if (secKey != null) {
                if (passphrase == null && passphraseAccessor != null) {
                    // get passphrase from accessor // only primary/master key has user IDS
                    @SuppressWarnings("unchecked")
                    Iterator<String> userIDs = keyring.getSecretKey().getUserIDs();
                    while (passphrase == null && userIDs.hasNext()) {
                        passphrase = passphraseAccessor.getPassphrase(userIDs.next());
                    }
                }
                if (passphrase != null) {
                    PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider)
                            .build(passphrase.toCharArray()));
                    if (privateKey != null) {
                        return privateKey;
                    }
                }
            }

        }
    }
    return null;
}
项目:Camel    文件:PGPDataFormatUtil.java   
public static List<PGPSecretKeyAndPrivateKeyAndUserId> findSecretKeysWithPrivateKeyAndUserId(Map<String, String> sigKeyUserId2Password,
        String provider, PGPSecretKeyRingCollection pgpSec) throws PGPException {
    List<PGPSecretKeyAndPrivateKeyAndUserId> result = new ArrayList<PGPSecretKeyAndPrivateKeyAndUserId>(sigKeyUserId2Password.size());
    for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext();) {
        Object data = i.next();
        if (data instanceof PGPSecretKeyRing) {
            PGPSecretKeyRing keyring = (PGPSecretKeyRing) data;
            PGPSecretKey primaryKey = keyring.getSecretKey();
            List<String> useridParts = new ArrayList<String>(sigKeyUserId2Password.keySet());
            String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey.getPublicKey());
            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 all signing keys
            for (Iterator<PGPSecretKey> iterKey = keyring.getSecretKeys(); iterKey.hasNext();) {
                PGPSecretKey secKey = iterKey.next();
                if (isSigningKey(secKey)) {
                    PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider)
                            .build(sigKeyUserId2Password.get(foundKeyUserIdForUserIdPart[1]).toCharArray()));
                    if (privateKey != null) {
                        result.add(new PGPSecretKeyAndPrivateKeyAndUserId(secKey, privateKey, foundKeyUserIdForUserIdPart[0]));
                        LOG.debug("Private key with user ID {} and key ID {} added to the signing keys",
                                foundKeyUserIdForUserIdPart[0], Long.toString(privateKey.getKeyID()));

                    }
                }
            }
        }
    }
    return result;
}
项目:CrococryptFile    文件:PGPUtils.java   
public static final byte[] decrypt(File privring, long keyid, char[] pw, byte[] in){
    if(!privring.exists() || !privring.isFile()) return null;

    try {
        byte[] ret = null;

        FileInputStream fis = new FileInputStream(privring);
        InputStream is = PGPUtil.getDecoderStream(fis);
        PGPSecretKeyRingCollection ring = new PGPSecretKeyRingCollection(is);
        PGPSecretKey seckey = ring.getSecretKey(keyid);
        if(seckey.isMasterKey()) {
            System.err.println("Someone tried to use a non-encryption key. This should never happen.");
            return null;
        }

        PrivateKey key = new JcaPGPKeyConverter().getPrivateKey(
                            seckey.extractPrivateKey(
                                new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pw)
                            )
                        );

        Cipher cipher = Cipher.getInstance(key.getAlgorithm() + "/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        ret = cipher.doFinal(in);

        is.close();
        fis.close();

        return ret;
    } catch (Exception e) {
        System.err.println(e.getLocalizedMessage());
        return null;
    }
}
项目:ant-spk    文件:OpenPGPSignature.java   
public OpenPGPSignature(OpenPGPSecretKey key) throws PGPException {
    PGPDigestCalculatorProvider pgpDigestCalculator = new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    PBESecretKeyDecryptor pbeSecretKeyDecryptor = new JcePBESecretKeyDecryptorBuilder(pgpDigestCalculator).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(key.getPassword());
    JcaPGPContentSignerBuilder pgpContentSigner = new JcaPGPContentSignerBuilder(key.getSecretKey().getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(BouncyCastleProvider.PROVIDER_NAME).setDigestProvider(BouncyCastleProvider.PROVIDER_NAME);

    signature = new PGPSignatureGenerator(pgpContentSigner);

    PGPPrivateKey privateKey = key.getSecretKey().extractPrivateKey(pbeSecretKeyDecryptor);
    signature.init(PGPSignature.BINARY_DOCUMENT, privateKey);
}
项目:incubator-gobblin    文件:GPGFileDecryptor.java   
/**
 * Private util function that finds the private key from keyring collection based on keyId and passPhrase
 * @param pgpSec keyring collection
 * @param keyID keyID for this encryption file
 * @param passPhrase passPhrase for this encryption file
 * @throws PGPException
 */
private PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, String passPhrase)
    throws PGPException {

  PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
  if (pgpSecKey == null) {
    return null;
  }
  return pgpSecKey.extractPrivateKey(
      new JcePBESecretKeyDecryptorBuilder()
          .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));
}
项目:CryptMeme    文件:PGPExampleUtil.java   
/**
 * Search a secret key ring collection for a secret key corresponding to keyID if it
 * exists.
 * 
 * @param pgpSec a secret key ring collection.
 * @param keyID keyID we want.
 * @param pass passphrase to decrypt secret key with.
 * @return the private key.
 * @throws PGPException
 * @throws NoSuchProviderException
 */
static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
    throws PGPException, NoSuchProviderException
{
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null)
    {
        return null;
    }

    return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
项目:CryptMeme    文件:PGPUnicodeTest.java   
public void test_key(BigInteger keyId, String passphrase)
    throws Exception
{

    PGPSecretKeyRingCollection secretKeyRing = loadSecretKeyCollection("secring.gpg");

    PGPSecretKeyRing secretKey = secretKeyRing.getSecretKeyRing(keyId.longValue());
    assertNotNull("Could not locate secret keyring with Id=" + keyId.toString(16), secretKey);

    PGPSecretKey key = secretKey.getSecretKey();
    assertNotNull("Could not locate secret key!", key);

    try
    {
        PGPDigestCalculatorProvider calcProvider = new JcaPGPDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

        PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProvider)
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passphrase.toCharArray());

        PGPPrivateKey privateKey = key.extractPrivateKey(decryptor);

        assertTrue(privateKey.getKeyID() == keyId.longValue());

    }
    catch (PGPException e)
    {
        throw new PGPException("Password incorrect!", e);
    }

    // all fine!
}
项目:irma_future_id    文件:PGPExampleUtil.java   
/**
 * Search a secret key ring collection for a secret key corresponding to keyID if it
 * exists.
 * 
 * @param pgpSec a secret key ring collection.
 * @param keyID keyID we want.
 * @param pass passphrase to decrypt secret key with.
 * @return the private key.
 * @throws PGPException
 * @throws NoSuchProviderException
 */
static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
    throws PGPException, NoSuchProviderException
{
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null)
    {
        return null;
    }

    return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
项目:irma_future_id    文件:PGPUnicodeTest.java   
public void test_key(BigInteger keyId, String passphrase)
    throws Exception
{

    PGPSecretKeyRingCollection secretKeyRing = loadSecretKeyCollection("secring.gpg");

    PGPSecretKeyRing secretKey = secretKeyRing.getSecretKeyRing(keyId.longValue());
    assertNotNull("Could not locate secret keyring with Id=" + keyId.toString(16), secretKey);

    PGPSecretKey key = secretKey.getSecretKey();
    assertNotNull("Could not locate secret key!", key);

    try
    {
        PGPDigestCalculatorProvider calcProvider = new JcaPGPDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

        PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProvider)
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passphrase.toCharArray());

        PGPPrivateKey privateKey = key.extractPrivateKey(decryptor);

        assertTrue(privateKey.getKeyID() == keyId.longValue());

    }
    catch (PGPException e)
    {
        throw new PGPException("Password incorrect!", e);
    }

    // all fine!
}
项目:bc-java    文件:PGPExampleUtil.java   
/**
 * Search a secret key ring collection for a secret key corresponding to keyID if it
 * exists.
 * 
 * @param pgpSec a secret key ring collection.
 * @param keyID keyID we want.
 * @param pass passphrase to decrypt secret key with.
 * @return the private key.
 * @throws PGPException
 * @throws NoSuchProviderException
 */
static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
    throws PGPException, NoSuchProviderException
{
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null)
    {
        return null;
    }

    return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
项目:bc-java    文件:PGPUnicodeTest.java   
public void test_key(BigInteger keyId, String passphrase)
    throws Exception
{

    PGPSecretKeyRingCollection secretKeyRing = loadSecretKeyCollection("secring.gpg");

    PGPSecretKeyRing secretKey = secretKeyRing.getSecretKeyRing(keyId.longValue());
    assertNotNull("Could not locate secret keyring with Id=" + keyId.toString(16), secretKey);

    PGPSecretKey key = secretKey.getSecretKey();
    assertNotNull("Could not locate secret key!", key);

    try
    {
        PGPDigestCalculatorProvider calcProvider = new JcaPGPDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();

        PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProvider)
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passphrase.toCharArray());

        PGPPrivateKey privateKey = key.extractPrivateKey(decryptor);

        assertTrue(privateKey.getKeyID() == keyId.longValue());

    }
    catch (PGPException e)
    {
        throw new PGPException("Password incorrect!", e);
    }

    // all fine!
}
项目:gpgj    文件:UnlockedKeySet.java   
/**
 * Re-encrypts the key set with a new passphrase and returns it in locked
 * form.
 *
 * @param oldPassphrase the old passphrase
 * @param newPassphrase the new passphrase
 * @return {@code this}, re-encrypted with {@code newPassphrase}
 * @throws CryptographicException if {@code oldPassphrase} is incorrect
 */
public KeySet relock(char[] oldPassphrase, char[] newPassphrase, SecureRandom random) throws CryptographicException {
    try {
        final PBESecretKeyDecryptor decryptor =
                new JcePBESecretKeyDecryptorBuilder()
                        .build(oldPassphrase);
        final PBESecretKeyEncryptor encryptor =
                new JcePBESecretKeyEncryptorBuilder(SymmetricAlgorithm.DEFAULT.value())
                        .setSecureRandom(random)
                        .build(newPassphrase);
        final PGPSecretKey masterSecretKey = PGPSecretKey.copyWithNewPassword(
                getUnlockedMasterKey().getSecretKey(),
                decryptor,
                encryptor
        );
        final PGPSecretKey subSecretKey = PGPSecretKey.copyWithNewPassword(
                getUnlockedSubKey().getSecretKey(),
                decryptor,
                encryptor
        );

        final MasterKey newMasterKey = new MasterKey(masterSecretKey);
        final SubKey newSubKey = new SubKey(subSecretKey, newMasterKey);

        return new KeySet(newMasterKey, newSubKey);
    } catch (PGPException e) {
        throw new CryptographicException(e);
    }
}
项目:gpgj    文件:SubKey.java   
@Override
public UnlockedSubKey unlock(char[] passphrase) throws CryptographicException {
    try {
        final PBESecretKeyDecryptor decryptor =
                new JcePBESecretKeyDecryptorBuilder().build(passphrase);
        final PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);
        return new UnlockedSubKey(secretKey, masterKey, privateKey);
    } catch (PGPException e) {
        throw new CryptographicException("Incorrect passphrase");
    }
}
项目:gpgj    文件:MasterKey.java   
@Override
public UnlockedMasterKey unlock(char[] passphrase) throws CryptographicException {
    try {
        final PBESecretKeyDecryptor decryptor =
                new JcePBESecretKeyDecryptorBuilder().build(passphrase);
        final PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);
        return new UnlockedMasterKey(secretKey, privateKey);
    } catch (PGPException e) {
        throw new CryptographicException("Incorrect passphrase", e);
    }
}
项目:saveOrganizer    文件:KeyIO.java   
public static PGPPrivateKey extractPrivateKey(PGPSecretKey secKey, char [] pass) throws PGPException
{
 PBESecretKeyDecryptor secretKeyDecryptor = new JcePBESecretKeyDecryptorBuilder() 
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pass); 
 return secKey.extractPrivateKey(secretKeyDecryptor);
}
项目:react-native-pgp    文件:PGPUtils.java   
static PGPPrivateKey decryptArmoredPrivateKey(PGPSecretKey secretKey, String password) throws IOException, PGPException {
  return  secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(password.toCharArray()));
}
项目:base    文件:PGPEncryptionUtil.java   
public static byte[] signAndEncrypt( final byte[] message, final PGPSecretKey secretKey, final String secretPwd,
                                     final PGPPublicKey publicKey, final boolean armored ) throws PGPException
{
    try
    {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true )
                                                                                   .setSecureRandom(
                                                                                           new SecureRandom() )
                                                                                   .setProvider( provider ) );

        encryptedDataGenerator.addMethod(
                new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setSecureRandom( new SecureRandom() )
                                                                         .setProvider( provider ) );

        final OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out;
        final OutputStream encryptedOut = encryptedDataGenerator.open( theOut, new byte[4096] );

        final PGPCompressedDataGenerator compressedDataGenerator =
                new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );
        final OutputStream compressedOut = compressedDataGenerator.open( encryptedOut, new byte[4096] );
        final PGPPrivateKey privateKey = secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
        final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 )
                        .setProvider( provider ) );
        signatureGenerator.init( PGPSignature.BINARY_DOCUMENT, privateKey );
        final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
        if ( it.hasNext() )
        {
            final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID( false, ( String ) it.next() );
            signatureGenerator.setHashedSubpackets( spGen.generate() );
        }
        signatureGenerator.generateOnePassVersion( false ).encode( compressedOut );
        final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        final OutputStream literalOut = literalDataGenerator
                .open( compressedOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] );
        final InputStream in = new ByteArrayInputStream( message );
        final byte[] buf = new byte[4096];
        for ( int len; ( len = in.read( buf ) ) > 0; )
        {
            literalOut.write( buf, 0, len );
            signatureGenerator.update( buf, 0, len );
        }
        in.close();
        literalDataGenerator.close();
        signatureGenerator.generate().encode( compressedOut );
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        theOut.close();
        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in signAndEncrypt", e );
    }
}
项目:base    文件:PGPEncryptionUtil.java   
public static byte[] sign( byte[] message, PGPSecretKey secretKey, String secretPwd, boolean armor )
        throws PGPException
{
    try
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream theOut = armor ? new ArmoredOutputStream( out ) : out;

        PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 )
                        .setProvider( provider ) );

        sGen.init( PGPSignature.BINARY_DOCUMENT, pgpPrivKey );

        Iterator it = secretKey.getPublicKey().getUserIDs();
        if ( it.hasNext() )
        {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            spGen.setSignerUserID( false, ( String ) it.next() );
            sGen.setHashedSubpackets( spGen.generate() );
        }

        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator( PGPCompressedData.ZLIB );

        BCPGOutputStream bOut = new BCPGOutputStream( cGen.open( theOut ) );

        sGen.generateOnePassVersion( false ).encode( bOut );

        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        OutputStream lOut =
                lGen.open( bOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] );         //
        InputStream fIn = new ByteArrayInputStream( message );
        int ch;

        while ( ( ch = fIn.read() ) >= 0 )
        {
            lOut.write( ch );
            sGen.update( ( byte ) ch );
        }

        lGen.close();

        sGen.generate().encode( bOut );

        cGen.close();

        theOut.close();

        return out.toByteArray();
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in sign", e );
    }
}
项目:bcpg-simple    文件:BcPGPSignEncryptTransform.java   
public void run(final char[] passphrase, final InputStream inputStream, final OutputStream outputStream) throws IOException, CryptoException {
  try {
    final OutputStream armor = new ArmoredOutputStream(outputStream);

    final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(
        SymmetricKeyAlgorithmTags.AES_128).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(new BouncyCastleProvider()));
    encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setSecureRandom(new SecureRandom()).setProvider(
        new BouncyCastleProvider()));

    final OutputStream encryptedOut = encryptedDataGenerator.open(armor, new byte[4096]);

    final PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
    final OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[4096]);

    final PGPPrivateKey privateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(new BouncyCastleProvider())
        .build(passphrase));

    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey()
        .getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(new BouncyCastleProvider()));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
    final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
    if (it.hasNext()) {
      final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
      spGen.setSignerUserID(false, (String) it.next());
      signatureGenerator.setHashedSubpackets(spGen.generate());
    }
    signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

    final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    final OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
    final byte[] buf = new byte[4096];
    for (int len = 0; (len = inputStream.read(buf)) > 0;) {
      literalOut.write(buf, 0, len);
      signatureGenerator.update(buf, 0, len);
    }
    literalDataGenerator.close();
    signatureGenerator.generate().encode(compressedOut);
    compressedDataGenerator.close();
    encryptedDataGenerator.close();
    armor.close();
  }
  catch (final Exception e) {
    throw new CryptoException(e);
  }

}
项目:CryptMeme    文件:PGPKeyRingTest.java   
public void generateTest()
    throws Exception
{
    char[]              passPhrase = "hello".toCharArray();
    KeyPairGenerator    dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");

    dsaKpg.initialize(512);

    //
    // this takes a while as the key generator has to generate some DSA params
    // before it generates the key.
    //
    KeyPair                    dsaKp = dsaKpg.generateKeyPair();

    KeyPairGenerator    elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
    BigInteger             g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
    BigInteger             p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

    ElGamalParameterSpec         elParams = new ElGamalParameterSpec(p, g);

    elgKpg.initialize(elParams);

    //
    // this is quicker because we are using pregenerated parameters.
    //
    KeyPair                    elgKp = elgKpg.generateKeyPair();
    PGPKeyPair        dsaKeyPair = new PGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
    PGPKeyPair        elgKeyPair = new PGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());

    PGPKeyRingGenerator    keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair,
            "test", PGPEncryptedData.AES_256, passPhrase, null, null, new SecureRandom(), "BC");

    keyRingGen.addSubKey(elgKeyPair);

    PGPSecretKeyRing       keyRing = keyRingGen.generateSecretKeyRing();

    keyRing.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase));

    PGPPublicKeyRing        pubRing = keyRingGen.generatePublicKeyRing();

    PGPPublicKey            vKey = null;
    PGPPublicKey            sKey = null;

    Iterator                    it = pubRing.getPublicKeys();
    while (it.hasNext())
    {
        PGPPublicKey    pk = (PGPPublicKey)it.next();
        if (pk.isMasterKey())
        {
            vKey = pk;
        }
        else
        {
            sKey = pk;
        }
    }

    Iterator    sIt = sKey.getSignatures();
    while (sIt.hasNext())
    {
        PGPSignature    sig = (PGPSignature)sIt.next();

        if (sig.getKeyID() == vKey.getKeyID()
            && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING)
        {
            sig.initVerify(vKey, "BC");

            if (!sig.verifyCertification(vKey, sKey))
            {
                fail("failed to verify sub-key signature.");
            }
        }
    }
}
项目:desktopclient-java    文件:PersonalKey.java   
/** Creates a {@link PersonalKey} from private keyring data. */
@SuppressWarnings("unchecked")
public static PersonalKey load(byte[] privateKeyData,
        char[] passphrase,
        byte[] bridgeCertData)
        throws KonException, IOException, PGPException, CertificateException, NoSuchProviderException {
    PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, PGPUtils.FP_CALC);

    PGPSecretKey authKey = null;
    PGPSecretKey signKey = null;
    PGPSecretKey encrKey = null;

    // assign from key ring
    Iterator<PGPSecretKey> skeys = secRing.getSecretKeys();
    while (skeys.hasNext()) {
        PGPSecretKey key = skeys.next();
        if (key.isMasterKey()) {
            // master key: authentication / legacy: signing
            authKey = key;
        } else if (PGPUtils.isSigningKey(key.getPublicKey())) {
            // sub keys: encryption and signing / legacy: only encryption
            signKey = key;
        } else if (key.getPublicKey().isEncryptionKey()) {
            encrKey = key;
        }
    }
    // legacy: auth key is actually signing key
    if (signKey == null && authKey != null && authKey.isSigningKey()) {
        LOGGER.info("legacy key");
        signKey = authKey;
    }

    if (authKey == null || signKey == null || encrKey == null) {
        LOGGER.warning("something could not be found, "
                +"sign="+signKey+ ", auth="+authKey+", encr="+encrKey);
        throw new KonException(KonException.Error.LOAD_KEY,
                new PGPException("could not find all keys in key data"));
    }

    // decrypt private keys
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder()
            .setProvider(PGPUtils.PROVIDER)
            .build(passphrase);
    PGPKeyPair authKeyPair = PGPUtils.decrypt(authKey, decryptor);
    PGPKeyPair signKeyPair = PGPUtils.decrypt(signKey, decryptor);
    PGPKeyPair encryptKeyPair = PGPUtils.decrypt(encrKey, decryptor);

    // user ID
    Iterator<?> uidIt = authKey.getUserIDs();
    if (!uidIt.hasNext())
        throw new KonException(KonException.Error.LOAD_KEY,
                new PGPException("no UID in key"));
    String uid = (String) uidIt.next();

    // X.509 bridge certificate
    X509Certificate bridgeCert;
    if (bridgeCertData != null) {
        bridgeCert = PGPUtils.loadX509Cert(bridgeCertData);
    } else {
        // public key ring
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        authKeyPair.getPublicKey().encode(out);
        signKeyPair.getPublicKey().encode(out);
        encryptKeyPair.getPublicKey().encode(out);
        byte[] publicKeyRingData = out.toByteArray();
        PGPPublicKeyRing pubKeyRing = new BcPGPPublicKeyRing(publicKeyRingData);

        // re-create cert
        bridgeCert = createX509Certificate(authKeyPair, pubKeyRing);
    }

    return new PersonalKey(authKeyPair, signKeyPair, encryptKeyPair, bridgeCert, uid);
}
项目:irma_future_id    文件:PGPKeyRingTest.java   
public void generateTest()
    throws Exception
{
    char[]              passPhrase = "hello".toCharArray();
    KeyPairGenerator    dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");

    dsaKpg.initialize(512);

    //
    // this takes a while as the key generator has to generate some DSA params
    // before it generates the key.
    //
    KeyPair                    dsaKp = dsaKpg.generateKeyPair();

    KeyPairGenerator    elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
    BigInteger             g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
    BigInteger             p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

    ElGamalParameterSpec         elParams = new ElGamalParameterSpec(p, g);

    elgKpg.initialize(elParams);

    //
    // this is quicker because we are using pregenerated parameters.
    //
    KeyPair                    elgKp = elgKpg.generateKeyPair();
    PGPKeyPair        dsaKeyPair = new PGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
    PGPKeyPair        elgKeyPair = new PGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());

    PGPKeyRingGenerator    keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair,
            "test", PGPEncryptedData.AES_256, passPhrase, null, null, new SecureRandom(), "BC");

    keyRingGen.addSubKey(elgKeyPair);

    PGPSecretKeyRing       keyRing = keyRingGen.generateSecretKeyRing();

    keyRing.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase));

    PGPPublicKeyRing        pubRing = keyRingGen.generatePublicKeyRing();

    PGPPublicKey            vKey = null;
    PGPPublicKey            sKey = null;

    Iterator                    it = pubRing.getPublicKeys();
    while (it.hasNext())
    {
        PGPPublicKey    pk = (PGPPublicKey)it.next();
        if (pk.isMasterKey())
        {
            vKey = pk;
        }
        else
        {
            sKey = pk;
        }
    }

    Iterator    sIt = sKey.getSignatures();
    while (sIt.hasNext())
    {
        PGPSignature    sig = (PGPSignature)sIt.next();

        if (sig.getKeyID() == vKey.getKeyID()
            && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING)
        {
            sig.initVerify(vKey, "BC");

            if (!sig.verifyCertification(vKey, sKey))
            {
                fail("failed to verify sub-key signature.");
            }
        }
    }
}
项目:bc-java    文件:PGPKeyRingTest.java   
public void generateTest()
    throws Exception
{
    char[]              passPhrase = "hello".toCharArray();
    KeyPairGenerator    dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");

    dsaKpg.initialize(512);

    //
    // this takes a while as the key generator has to generate some DSA params
    // before it generates the key.
    //
    KeyPair                    dsaKp = dsaKpg.generateKeyPair();

    KeyPairGenerator    elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
    BigInteger             g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
    BigInteger             p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

    ElGamalParameterSpec         elParams = new ElGamalParameterSpec(p, g);

    elgKpg.initialize(elParams);

    //
    // this is quicker because we are using pregenerated parameters.
    //
    KeyPair                    elgKp = elgKpg.generateKeyPair();
    PGPKeyPair        dsaKeyPair = new PGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
    PGPKeyPair        elgKeyPair = new PGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());

    PGPKeyRingGenerator    keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair,
            "test", PGPEncryptedData.AES_256, passPhrase, null, null, new SecureRandom(), "BC");

    keyRingGen.addSubKey(elgKeyPair);

    PGPSecretKeyRing       keyRing = keyRingGen.generateSecretKeyRing();

    keyRing.getSecretKey().extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passPhrase));

    PGPPublicKeyRing        pubRing = keyRingGen.generatePublicKeyRing();

    PGPPublicKey            vKey = null;
    PGPPublicKey            sKey = null;

    Iterator                    it = pubRing.getPublicKeys();
    while (it.hasNext())
    {
        PGPPublicKey    pk = (PGPPublicKey)it.next();
        if (pk.isMasterKey())
        {
            vKey = pk;
        }
        else
        {
            sKey = pk;
        }
    }

    Iterator    sIt = sKey.getSignatures();
    while (sIt.hasNext())
    {
        PGPSignature    sig = (PGPSignature)sIt.next();

        if (sig.getKeyID() == vKey.getKeyID()
            && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING)
        {
            sig.initVerify(vKey, "BC");

            if (!sig.verifyCertification(vKey, sKey))
            {
                fail("failed to verify sub-key signature.");
            }
        }
    }
}
项目:saveOrganizer    文件:PGPUtils.java   
/**
 * Search a secret key ring collection for a secret key corresponding to
 * keyID if it exists.
 * 
 * @param pgpSec
 *            a secret key ring collection.
 * @param keyID
 *            keyID we want.
 * @param pass
 *            passphrase to decrypt secret key with.
 * @return the private key.
 * @throws PGPException
 * @throws NoSuchProviderException
 */
static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
        throws PGPException, NoSuchProviderException
{
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null)
    {
        return null;
    }

    return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
项目:CryptMeme    文件:PGPSecretKey.java   
/**
 * Extract a PGPPrivate key from the SecretKey's encrypted contents.
 *
 * @param passPhrase
 * @param provider
 * @return PGPPrivateKey
 * @throws PGPException
 * @deprecated use method that takes a PBESecretKeyDecryptor
 */
public  PGPPrivateKey extractPrivateKey(
    char[]   passPhrase,
    Provider provider)
    throws PGPException
{
    return extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider(provider).build()).setProvider(provider).build(passPhrase));
}
项目:CryptMeme    文件:PGPSecretKey.java   
/**
 * Return a copy of the passed in secret key, encrypted using a new
 * password and the passed in algorithm.
 *
 * @param key the PGPSecretKey to be copied.
 * @param oldPassPhrase the current password for key.
 * @param newPassPhrase the new password for the key.
 * @param newEncAlgorithm the algorithm to be used for the encryption.
 * @param rand source of randomness.
 * @param provider the provider to use
 * @deprecated use method taking PBESecretKeyDecryptor and PBESecretKeyEncryptor
 */
public static PGPSecretKey copyWithNewPassword(
    PGPSecretKey    key,
    char[]          oldPassPhrase,
    char[]          newPassPhrase,
    int             newEncAlgorithm,
    SecureRandom    rand,
    Provider        provider)
    throws PGPException
{
    return copyWithNewPassword(key, new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider(provider).build()).setProvider(provider).build(oldPassPhrase), new JcePBESecretKeyEncryptorBuilder(newEncAlgorithm).setProvider(provider).setSecureRandom(rand).build(newPassPhrase));
}
项目:irma_future_id    文件:PGPSecretKey.java   
/**
 * Extract a PGPPrivate key from the SecretKey's encrypted contents.
 *
 * @param passPhrase
 * @param provider
 * @return PGPPrivateKey
 * @throws PGPException
 * @deprecated use method that takes a PBESecretKeyDecryptor
 */
public  PGPPrivateKey extractPrivateKey(
    char[]   passPhrase,
    Provider provider)
    throws PGPException
{
    return extractPrivateKey(new JcePBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider(provider).build()).setProvider(provider).build(passPhrase));
}