Java 类org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor 实例源码

项目:gwt-crypto    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:gwt-crypto    文件:BcPBESecretKeyDecryptorBuilder.java   
public PBESecretKeyDecryptor build(char[] passPhrase)
{
    return new PBESecretKeyDecryptor(passPhrase, calculatorProvider)
    {
        public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
            throws PGPException
        {
            try
            {
                BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv);

                byte[] out = new byte[keyLen];
                int    outLen = c.processBytes(keyData, keyOff, keyLen, out, 0);

                outLen += c.doFinal(out, outLen);

                return out;
            }
            catch (InvalidCipherTextException e)
            {
                throw new PGPException("decryption failed: " + e.getMessage(), e);
            }
        }
    };
}
项目:CryptMeme    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:CryptMeme    文件:BcPBESecretKeyDecryptorBuilder.java   
public PBESecretKeyDecryptor build(char[] passPhrase)
{
    return new PBESecretKeyDecryptor(passPhrase, calculatorProvider)
    {
        public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
            throws PGPException
        {
            try
            {
                BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv);

                byte[] out = new byte[keyLen];
                int    outLen = c.processBytes(keyData, keyOff, keyLen, out, 0);

                outLen += c.doFinal(out, outLen);

                return out;
            }
            catch (InvalidCipherTextException e)
            {
                throw new PGPException("decryption failed: " + e.getMessage(), e);
            }
        }
    };
}
项目: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);
    }
}
项目:irma_future_id    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:irma_future_id    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:irma_future_id    文件:BcPBESecretKeyDecryptorBuilder.java   
public PBESecretKeyDecryptor build(char[] passPhrase)
{
    return new PBESecretKeyDecryptor(passPhrase, calculatorProvider)
    {
        public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
            throws PGPException
        {
            try
            {
                BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv);

                byte[] out = new byte[keyLen];
                int    outLen = c.processBytes(keyData, keyOff, keyLen, out, 0);

                outLen += c.doFinal(out, outLen);

                return out;
            }
            catch (InvalidCipherTextException e)
            {
                throw new PGPException("decryption failed: " + e.getMessage(), e);
            }
        }
    };
}
项目:appframework    文件:PGPDecryptor.java   
private static PGPPrivateKey extractPrivateKey(PGPSecretKey pgpSecKey, char[] passPhrase)
        throws PGPException {
    PGPPrivateKey privateKey = null;
    BcPGPDigestCalculatorProvider calculatorProvider = new BcPGPDigestCalculatorProvider();
    BcPBESecretKeyDecryptorBuilder secretKeyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder(
            calculatorProvider);
    PBESecretKeyDecryptor pBESecretKeyDecryptor = secretKeyDecryptorBuilder.build(passPhrase);

    try {
        privateKey = pgpSecKey.extractPrivateKey(pBESecretKeyDecryptor);
    } catch (PGPException e) {
        throw new PGPException("invalid privateKey passPhrase: " + String.valueOf(passPhrase),
                e);
    }

    return privateKey;
}
项目:bc-java    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:bc-java    文件:PGPSecretKeyRing.java   
/**
 * Return a copy of the passed in secret key ring, with the private keys (where present) associated with the master key and sub keys
 * are encrypted using a new password and the passed in algorithm.
 *
 * @param ring the PGPSecretKeyRing to be copied.
 * @param oldKeyDecryptor the current decryptor based on the current password for key.
 * @param newKeyEncryptor a new encryptor based on a new password for encrypting the secret key material.
 * @return the updated key ring.
 */
public static PGPSecretKeyRing copyWithNewPassword(
    PGPSecretKeyRing       ring,
    PBESecretKeyDecryptor  oldKeyDecryptor,
    PBESecretKeyEncryptor  newKeyEncryptor)
    throws PGPException
{
    List newKeys = new ArrayList(ring.keys.size());

    for (Iterator keys = ring.getSecretKeys(); keys.hasNext();)
    {
        PGPSecretKey key = (PGPSecretKey)keys.next();

        if (key.isPrivateKeyEmpty())
        {
            newKeys.add(key);
        }
        else
        {
            newKeys.add(PGPSecretKey.copyWithNewPassword(key, oldKeyDecryptor, newKeyEncryptor));
        }
    }

    return new PGPSecretKeyRing(newKeys, ring.extraPubKeys);
}
项目:bc-java    文件:BcPBESecretKeyDecryptorBuilder.java   
public PBESecretKeyDecryptor build(char[] passPhrase)
{
    return new PBESecretKeyDecryptor(passPhrase, calculatorProvider)
    {
        public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen)
            throws PGPException
        {
            try
            {
                BufferedBlockCipher c = BcUtil.createSymmetricKeyWrapper(false, BcImplProvider.createBlockCipher(encAlgorithm), key, iv);

                byte[] out = new byte[keyLen];
                int    outLen = c.processBytes(keyData, keyOff, keyLen, out, 0);

                outLen += c.doFinal(out, outLen);

                return out;
            }
            catch (InvalidCipherTextException e)
            {
                throw new PGPException("decryption failed: " + e.getMessage(), e);
            }
        }
    };
}
项目:Reer    文件:PgpSignatory.java   
private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) {
    try {
        PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray());
        return secretKey.extractPrivateKey(decryptor);
    } catch (PGPException e) {
        throw new UncheckedException(e);
    }
}
项目: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;
}
项目:jpgpj    文件:Subkey.java   
/**
 * Builds a secret key decryptor for the specified passphrase.
 */
protected PBESecretKeyDecryptor buildDecryptor(String passphrase) {
    char[] chars = !Util.isEmpty(passphrase) ?
        passphrase.toCharArray() : new char[0];
    return new BcPBESecretKeyDecryptorBuilder(
        new BcPGPDigestCalculatorProvider()).build(chars);
}
项目:java-api    文件:BcPrivateKey.java   
BcPrivateKey(String armoredKeyString, char[] passphrase) throws PGPKeyInitialisationException {
    try {
        PGPSecretKeyRing secKeyRing = new PGPSecretKeyRing(
                new ArmoredInputStream(new ByteArrayInputStream(armoredKeyString.getBytes(StandardCharsets.US_ASCII))),
                new BcKeyFingerprintCalculator());

        PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
                .build(passphrase);

        ImmutableMap.Builder<Long, PGPPrivateKey> builder = ImmutableMap.builder();
        List<PGPPublicKey> pubKeys = new ArrayList<>(2);

        for (Iterator iterator = secKeyRing.getSecretKeys(); iterator.hasNext(); ) {
            PGPSecretKey secretKey = (PGPSecretKey) iterator.next();
            PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);
            builder.put(privateKey.getKeyID(), privateKey);
            pubKeys.add(secretKey.getPublicKey());
        }

        this.secretKey = secKeyRing.getSecretKey();
        this.privateKeys = builder.build();
        this.privateKey = this.secretKey.extractPrivateKey(decryptor);
        if (pubKeys.size() >= 2) {
            this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(1));
        } else {
            this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(0));
        }

    } catch (PGPException | RuntimeException | IOException e) {
        throw new PGPKeyInitialisationException("Error instantiating a private key", e);
    }
    checkNotNull(this.secretKey);
    checkNotNull(this.privateKey);

    this.fingerprint = BcPublicKey.hexFingerprint(secretKey.getPublicKey());
}
项目:mq-mft    文件:CryptDecryptUtil.java   
/**
 * Get private key using the given passphrase
 * @param pgpSecKey The secret key
 * @param pass passphrase to decrypt secret key with
 * @return Private key
 * @throws PGPException
 */
private PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass)
    throws PGPException {
    if (pgpSecKey == null) return null;

    PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass);
    return pgpSecKey.extractPrivateKey(decryptor);
}
项目:simple-pgp    文件:BasePGPCommon.java   
/**
 * read the private key from the given secret key
 *
 * @param pgpSecretKey
 *    the secret key
 * @param password
 *    the password to unlock the private key
 * @return the unlocked private key
 * @throws PGPException
 */
protected PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecretKey, String password) throws PGPException {
  LOGGER.trace("findPrivateKey(PGPSecretKey, String)");
  LOGGER.trace("Secret Key: {}, Password: {}", pgpSecretKey == null ? "not set" : "set", password == null ? "not set" : "********");
  PGPPrivateKey result = null;
  PBESecretKeyDecryptor pbeSecretKeyDecryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray());
  LOGGER.info("Extracting private key");
  result = pgpSecretKey.extractPrivateKey(pbeSecretKeyDecryptor);
  if( result == null && LOGGER.isErrorEnabled() ) {
    LOGGER.error("No private key could be extracted");
  }
  return result;
}
项目:superfly    文件:PGPUtils.java   
private static PGPPrivateKey findSecretKey(
        PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
        throws PGPException, NoSuchProviderException {
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

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

    final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(
            new BcPGPDigestCalculatorProvider()).build(pass);
    return pgpSecKey.extractPrivateKey(decryptor);
}
项目:subshare    文件:GnuPgTest.java   
public static PGPPrivateKey findSecretKey(final InputStream keyIn, final long keyID, final char[] pass) throws IOException, PGPException {
    final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator());
    final PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
    if (pgpSecKey == null) return null;

    final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass);
    return pgpSecKey.extractPrivateKey(decryptor);
}
项目:subshare    文件:GnuPgTest.java   
private static PGPPrivateKey getPgpPrivateKeyOrFail(final long keyId, final char[] passphrase) throws IOException, PGPException {
    final PGPSecretKey secretKey = getPgpSecretKeyOrFail(keyId);

    final PGPDigestCalculatorProvider calculatorProvider = new BcPGPDigestCalculatorProvider();
    final BcPBESecretKeyDecryptorBuilder secretKeyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder(calculatorProvider);
    final PBESecretKeyDecryptor secretKeyDecryptor = secretKeyDecryptorBuilder.build(passphrase);
    final PGPPrivateKey privateKey = secretKey.extractPrivateKey(secretKeyDecryptor);
    return privateKey;
}
项目: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);
}
项目: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!
}
项目:desktopclient-java    文件:PGPUtils.java   
static PGPKeyPair decrypt(PGPSecretKey secretKey, PBESecretKeyDecryptor dec) throws KonException {
    try {
        return new PGPKeyPair(secretKey.getPublicKey(), secretKey.extractPrivateKey(dec));
    } catch (PGPException ex) {
        LOGGER.log(Level.WARNING, "failed", ex);
        throw new KonException(KonException.Error.LOAD_KEY_DECRYPT, ex);
    }
}
项目: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    文件: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);
}
项目:whistleblower    文件:CryptographyHandler.java   
public PGPDecryptionResult decrypt(InputStream in) throws IOException {

        PGPDecryptionResult result = new PGPDecryptionResult();
//        List<String> receivers = new ArrayList<>();

        in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
        PGPObjectFactory pgpF = new PGPObjectFactory(in, new JcaKeyFingerprintCalculator());
        PGPEncryptedDataList enc;

        Object o = pgpF.nextObject();

        if (o instanceof  PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpF.nextObject();
        }

        Iterator it = enc.getEncryptedDataObjects();

        PGPPublicKeyEncryptedData pbe = null;

        while (it.hasNext()) {

            PGPPublicKeyEncryptedData current = (PGPPublicKeyEncryptedData) it.next();

            if(current.getKeyID() == secretKey.getKeyID()) {
                pbe = current;
            }

//            receivers.add(Long.toString(current.getKeyID()));
        }

        if(pbe == null)
            return result;


        try {
            PGPDigestCalculatorProvider digestCalculatorProvider = new JcaPGPDigestCalculatorProviderBuilder().build();

            PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(digestCalculatorProvider)
                    .build(passphrase.toCharArray());

            PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);

            InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(privateKey));


            JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
            Object message = plainFact.nextObject();

            if(message instanceof PGPCompressedData) {
                PGPCompressedData   cData = (PGPCompressedData)plainFact.nextObject();

                InputStream         compressedStream = new BufferedInputStream(cData.getDataStream());
                JcaPGPObjectFactory    pgpFact = new JcaPGPObjectFactory(compressedStream);

                message = pgpFact.nextObject();
            }

            if (message instanceof PGPLiteralData)
            {
                PGPLiteralData ld = (PGPLiteralData)message;

                InputStream unc = ld.getInputStream();

                ObjectMapper mapper = new ObjectMapper();
                result.submission = mapper.readValue(unc, Submission.class);
                unc.close();
                Log.i(result.submission.reply_to);
                Log.i(Integer.toString(result.submission.receivers.size()));

                result.decryptedSuccessfully = !pbe.isIntegrityProtected() ||  pbe.verify();
                return result;
            }
        } catch (PGPException e) {
            e.printStackTrace();
        }
        return result;
    }
项目:gwt-crypto    文件:PGPSecretKey.java   
private static byte[] getDValue(InputStream inputStream, PBEProtectionRemoverFactory keyProtectionRemoverFactory, String curveName)
    throws IOException, PGPException
{
    String type;
    SXprUtils.skipOpenParenthesis(inputStream);

    String protection;
    S2K s2k;
    byte[] iv;
    byte[] secKeyData;

    type = SXprUtils.readString(inputStream, inputStream.read());
    if (type.equals("protected"))
    {
        protection = SXprUtils.readString(inputStream, inputStream.read());

        SXprUtils.skipOpenParenthesis(inputStream);

        s2k = SXprUtils.parseS2K(inputStream);

        iv = SXprUtils.readBytes(inputStream, inputStream.read());

        SXprUtils.skipCloseParenthesis(inputStream);

        secKeyData = SXprUtils.readBytes(inputStream, inputStream.read());
    }
    else
    {
        throw new PGPException("protected block not found");
    }

    PBESecretKeyDecryptor keyDecryptor = keyProtectionRemoverFactory.createDecryptor(protection);

    // TODO: recognise other algorithms
    byte[] key = keyDecryptor.makeKeyFromPassPhrase(SymmetricKeyAlgorithmTags.AES_128, s2k);

    byte[] data = keyDecryptor.recoverKeyData(SymmetricKeyAlgorithmTags.AES_128, key, iv, secKeyData, 0, secKeyData.length);

    //
    // parse the secret key S-expr
    //
    InputStream keyIn = new ByteArrayInputStream(data);

    SXprUtils.skipOpenParenthesis(keyIn);
    SXprUtils.skipOpenParenthesis(keyIn);
    SXprUtils.skipOpenParenthesis(keyIn);
    String name = SXprUtils.readString(keyIn, keyIn.read());
    return SXprUtils.readBytes(keyIn, keyIn.read());
}
项目:nomulus    文件:KeySerializer.java   
private static PBESecretKeyDecryptor createSecretKeyDecryptor() {
  // There shouldn't be a passphrase on the key
  return new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
      .build(new char[0]);
}
项目: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);
}
项目:whistleblower    文件:CryptographyHandler.java   
public boolean loadKeys() throws IOException, PGPException {
    secretKey = readSecretKey(new ArmoredInputStream(new FileInputStream("secret.pgp")));


    PGPDigestCalculatorProvider digestCalculatorProvider = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(digestCalculatorProvider)
            .build(passphrase.toCharArray());

    PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);

    return secretKey != null;
}