Example usage for org.bouncycastle.openpgp.operator PBESecretKeyDecryptor makeKeyFromPassPhrase

List of usage examples for org.bouncycastle.openpgp.operator PBESecretKeyDecryptor makeKeyFromPassPhrase

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator PBESecretKeyDecryptor makeKeyFromPassPhrase.

Prototype

public byte[] makeKeyFromPassPhrase(int keyAlgorithm, S2K s2k) throws PGPException 

Source Link

Usage

From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.java

License:Open Source License

/**
 * Returns true on right passphrase//  w w  w  . ja  v  a 2s.co  m
 */
public boolean unlock(final Passphrase passphrase) throws PgpGeneralException {
    // handle keys on OpenPGP cards like they were unlocked
    S2K s2k = mSecretKey.getS2K();
    if (s2k != null && s2k.getType() == S2K.GNU_DUMMY_S2K
            && s2k.getProtectionMode() == S2K.GNU_PROTECTION_MODE_DIVERT_TO_CARD) {
        mPrivateKeyState = PRIVATE_KEY_STATE_DIVERT_TO_CARD;
        return true;
    }

    // try to extract keys using the passphrase
    try {

        int keyEncryptionAlgorithm = mSecretKey.getKeyEncryptionAlgorithm();
        if (keyEncryptionAlgorithm == SymmetricKeyAlgorithmTags.NULL) {
            mPrivateKey = mSecretKey.extractPrivateKey(null);
            mPrivateKeyState = PRIVATE_KEY_STATE_UNLOCKED;
            return true;
        }

        byte[] sessionKey;
        sessionKey = passphrase.getCachedSessionKeyForParameters(keyEncryptionAlgorithm, s2k);
        if (sessionKey == null) {
            PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder()
                    .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(passphrase.getCharArray());
            // this operation is EXPENSIVE, so we cache its result in the passed Passphrase object!
            sessionKey = keyDecryptor.makeKeyFromPassPhrase(keyEncryptionAlgorithm, s2k);
            passphrase.addCachedSessionKeyForParameters(keyEncryptionAlgorithm, s2k, sessionKey);
        }

        PBESecretKeyDecryptor keyDecryptor = new SessionKeySecretKeyDecryptorBuilder()
                .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(sessionKey);
        mPrivateKey = mSecretKey.extractPrivateKey(keyDecryptor);
        mPrivateKeyState = PRIVATE_KEY_STATE_UNLOCKED;
    } catch (PGPException e) {
        return false;
    }
    if (mPrivateKey == null) {
        throw new PgpGeneralException("error extracting key");
    }
    return true;
}