Java Code Examples for org.bitcoinj.core.ECKey#isEncrypted()

The following examples show how to use org.bitcoinj.core.ECKey#isEncrypted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" + input.getOutpoint().toString());
    if (sigKey.isEncrypted())
        checkNotNull(aesKey);
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example 2
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" +
            input.getOutpoint().toString());
    if (sigKey.isEncrypted()) {
        checkNotNull(aesKey);
    }
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example 3
Source File: KeyChainGroup.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key.
 */
public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) {
    // TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.
    checkState(keyCrypter != null, "Not encrypted");
    LinkedList<ECKey> encryptedKeys = Lists.newLinkedList();
    for (ECKey key : keys) {
        if (key.isEncrypted())
            throw new IllegalArgumentException("Cannot provide already encrypted keys");
        encryptedKeys.add(key.encrypt(keyCrypter, aesKey));
    }
    return importKeys(encryptedKeys);
}
 
Example 4
Source File: DecryptingKeyBag.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private ECKey maybeDecrypt(ECKey key) {
    if (key == null)
        return null;
    else if (key.isEncrypted()) {
        if (aesKey == null)
            throw new ECKey.KeyIsEncryptedException();
        return key.decrypt(aesKey);
    } else {
        return key;
    }
}
 
Example 5
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void checkKeyEncryptionStateMatches(ECKey key) {
    if (keyCrypter == null && key.isEncrypted())
        throw new KeyCrypterException("Key is encrypted but chain is not");
    else if (keyCrypter != null && !key.isEncrypted())
        throw new KeyCrypterException("Key is not encrypted but chain is");
    else if (keyCrypter != null && key.getKeyCrypter() != null && !key.getKeyCrypter().equals(keyCrypter))
        throw new KeyCrypterException("Key encrypted under different parameters to chain");
}
 
Example 6
Source File: BasicKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the AES key can decrypt the first encrypted key in the wallet.
 *
 * @return true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise.
 */
@Override
public boolean checkAESKey(KeyParameter aesKey) {
    lock.lock();
    try {
        // If no keys then cannot decrypt.
        if (hashToKeys.isEmpty())
            return false;
        checkState(keyCrypter != null, "Key chain is not encrypted");

        // Find the first encrypted key in the wallet.
        ECKey first = null;
        for (ECKey key : hashToKeys.values()) {
            if (key.isEncrypted()) {
                first = key;
                break;
            }
        }
        checkState(first != null, "No encrypted keys in the wallet");

        try {
            ECKey rebornKey = first.decrypt(aesKey);
            return Arrays.equals(first.getPubKey(), rebornKey.getPubKey());
        } catch (KeyCrypterException e) {
            // The AES key supplied is incorrect.
            return false;
        }
    } finally {
        lock.unlock();
    }
}
 
Example 7
Source File: DecryptingKeyBag.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private ECKey maybeDecrypt(ECKey key) {
    if (key == null)
        return null;
    else if (key.isEncrypted()) {
        if (aesKey == null)
            throw new ECKey.KeyIsEncryptedException();
        return key.decrypt(aesKey);
    } else {
        return key;
    }
}
 
Example 8
Source File: BasicKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void checkKeyEncryptionStateMatches(ECKey key) {
    if (keyCrypter == null && key.isEncrypted())
        throw new KeyCrypterException("Key is encrypted but chain is not");
    else if (keyCrypter != null && !key.isEncrypted())
        throw new KeyCrypterException("Key is not encrypted but chain is");
    else if (keyCrypter != null && key.getKeyCrypter() != null && !key.getKeyCrypter().equals(keyCrypter))
        throw new KeyCrypterException("Key encrypted under different parameters to chain");
}
 
Example 9
Source File: BasicKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the AES key can decrypt the first encrypted key in the wallet.
 *
 * @return true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise.
 */
@Override
public boolean checkAESKey(KeyParameter aesKey) {
    lock.lock();
    try {
        // If no keys then cannot decrypt.
        if (hashToKeys.isEmpty()) return false;
        checkState(keyCrypter != null, "Key chain is not encrypted");

        // Find the first encrypted key in the wallet.
        ECKey first = null;
        for (ECKey key : hashToKeys.values()) {
            if (key.isEncrypted()) {
                first = key;
                break;
            }
        }
        checkState(first != null, "No encrypted keys in the wallet");

        try {
            ECKey rebornKey = first.decrypt(aesKey);
            return Arrays.equals(first.getPubKey(), rebornKey.getPubKey());
        } catch (KeyCrypterException e) {
            // The AES key supplied is incorrect.
            return false;
        }
    } finally {
        lock.unlock();
    }
}
 
Example 10
Source File: DecryptingKeyBag.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private ECKey maybeDecrypt(ECKey key) {
    if (key == null)
        return null;
    else if (key.isEncrypted()) {
        if (aesKey == null)
            throw new ECKey.KeyIsEncryptedException();
        return key.decrypt(aesKey);
    } else {
        return key;
    }
}
 
Example 11
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void checkKeyEncryptionStateMatches(ECKey key) {
    if (keyCrypter == null && key.isEncrypted())
        throw new KeyCrypterException("Key is encrypted but chain is not");
    else if (keyCrypter != null && !key.isEncrypted())
        throw new KeyCrypterException("Key is not encrypted but chain is");
    else if (keyCrypter != null && key.getKeyCrypter() != null && !key.getKeyCrypter().equals(keyCrypter))
        throw new KeyCrypterException("Key encrypted under different parameters to chain");
}
 
Example 12
Source File: BasicKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the AES key can decrypt the first encrypted key in the wallet.
 *
 * @return true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise.
 */
@Override
public boolean checkAESKey(KeyParameter aesKey) {
    lock.lock();
    try {
        // If no keys then cannot decrypt.
        if (hashToKeys.isEmpty()) return false;
        checkState(keyCrypter != null, "Key chain is not encrypted");

        // Find the first encrypted key in the wallet.
        ECKey first = null;
        for (ECKey key : hashToKeys.values()) {
            if (key.isEncrypted()) {
                first = key;
                break;
            }
        }
        checkState(first != null, "No encrypted keys in the wallet");

        try {
            ECKey rebornKey = first.decrypt(aesKey);
            return Arrays.equals(first.getPubKey(), rebornKey.getPubKey());
        } catch (KeyCrypterException e) {
            // The AES key supplied is incorrect.
            return false;
        }
    } finally {
        lock.unlock();
    }
}
 
Example 13
Source File: KeyChainGroup.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * If the key chain contains only random keys and no deterministic key chains, this method will create a chain
 * based on the oldest non-rotating private key (i.e. the seed is derived from the old wallet).
 *
 * @param keyRotationTimeSecs If non-zero, UNIX time for which keys created before this are assumed to be
 *                            compromised or weak, those keys will not be used for deterministic upgrade.
 * @param aesKey              If non-null, the encryption key the keychain is encrypted under. If the keychain is encrypted
 *                            and this is not supplied, an exception is thrown letting you know you should ask the user for
 *                            their password, turn it into a key, and then try again.
 * @return the DeterministicKeyChain that was created by the upgrade.
 * @throws java.lang.IllegalStateException      if there is already a deterministic key chain present or if there are
 *                                              no random keys (i.e. this is not an upgrade scenario), or if aesKey is
 *                                              provided but the wallet is not encrypted.
 * @throws java.lang.IllegalArgumentException   if the rotation time specified excludes all keys.
 * @throws DeterministicUpgradeRequiresPassword if the key chain group is encrypted
 *                                              and you should provide the users encryption key.
 */
public DeterministicKeyChain upgradeToDeterministic(long keyRotationTimeSecs, @Nullable KeyParameter aesKey) throws DeterministicUpgradeRequiresPassword, AllRandomKeysRotating {
    checkState(basic.numKeys() > 0);
    checkArgument(keyRotationTimeSecs >= 0);
    // Subtract one because the key rotation time might have been set to the creation time of the first known good
    // key, in which case, that's the one we want to find.
    ECKey keyToUse = basic.findOldestKeyAfter(keyRotationTimeSecs - 1);
    if (keyToUse == null)
        throw new AllRandomKeysRotating();

    if (keyToUse.isEncrypted()) {
        if (aesKey == null) {
            // We can't auto upgrade because we don't know the users password at this point. We throw an
            // exception so the calling code knows to abort the load and ask the user for their password, they can
            // then try loading the wallet again passing in the AES key.
            //
            // There are a few different approaches we could have used here, but they all suck. The most obvious
            // is to try and be as lazy as possible, running in the old random-wallet mode until the user enters
            // their password for some other reason and doing the upgrade then. But this could result in strange
            // and unexpected UI flows for the user, as well as complicating the job of wallet developers who then
            // have to support both "old" and "new" UI modes simultaneously, switching them on the fly. Given that
            // this is a one-off transition, it seems more reasonable to just ask the user for their password
            // on startup, and then the wallet app can have all the widgets for accessing seed words etc active
            // all the time.
            throw new DeterministicUpgradeRequiresPassword();
        }
        keyToUse = keyToUse.decrypt(aesKey);
    } else if (aesKey != null) {
        throw new IllegalStateException("AES Key was provided but wallet is not encrypted.");
    }

    if (chains.isEmpty()) {
        log.info("Auto-upgrading pre-HD wallet to HD!");
    } else {
        log.info("Wallet with existing HD chain is being re-upgraded due to change in key rotation time.");
    }
    log.info("Instantiating new HD chain using oldest non-rotating private key (address: {})", LegacyAddress.fromKey(params, keyToUse));
    byte[] entropy = checkNotNull(keyToUse.getSecretBytes());
    // Private keys should be at least 128 bits long.
    checkState(entropy.length >= DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);
    // We reduce the entropy here to 128 bits because people like to write their seeds down on paper, and 128
    // bits should be sufficient forever unless the laws of the universe change or ECC is broken; in either case
    // we all have bigger problems.
    entropy = Arrays.copyOfRange(entropy, 0, DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);    // final argument is exclusive range.
    checkState(entropy.length == DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);
    String passphrase = ""; // FIXME allow non-empty passphrase
    DeterministicKeyChain chain = new DeterministicKeyChain(entropy, passphrase, keyToUse.getCreationTimeSeconds());
    if (aesKey != null) {
        chain = chain.toEncrypted(checkNotNull(basic.getKeyCrypter()), aesKey);
    }
    chains.add(chain);
    return chain;
}