org.bitcoinj.crypto.KeyCrypterScrypt Java Examples

The following examples show how to use org.bitcoinj.crypto.KeyCrypterScrypt. 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: BasicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = KeyCrypterException.class)
public void cannotMixParams() throws Exception {
    chain = chain.toEncrypted("foobar");
    KeyCrypterScrypt scrypter = new KeyCrypterScrypt(2);    // Some bogus params.
    ECKey key1 = new ECKey().encrypt(scrypter, scrypter.deriveKey("other stuff"));
    chain.importKeys(key1);
}
 
Example #2
Source File: WalletPasswordController.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
@FXML void confirmClicked(ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.bitcoin.wallet().getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected void onFinish(KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.bitcoin.wallet().checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #3
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    if (this.aesKey != null) {
        log.warn("encryptWallet called but we have a aesKey already set. " +
                "We decryptWallet with the old key before we apply the new key.");
        decryptWallet(this.aesKey);
    }

    wallet.encrypt(keyCrypterScrypt, key);
    aesKey = key;
}
 
Example #4
Source File: WalletPasswordController.java    From devcoretalk with GNU General Public License v2.0 5 votes vote down vote up
@FXML void confirmClicked(ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.bitcoin.wallet().getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected void onFinish(KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.bitcoin.wallet().checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #5
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder().setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt()));
    ScryptParameters scryptParameters = scryptParametersBuilder.build();
    keyCrypter = new KeyCrypterScrypt(scryptParameters);

    BriefLogFormatter.init();
}
 
Example #6
Source File: BasicKeyChainTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = KeyCrypterException.class)
public void cannotMixParams() throws Exception {
    chain = chain.toEncrypted("foobar");
    KeyCrypterScrypt scrypter = new KeyCrypterScrypt(2);    // Some bogus params.
    ECKey key1 = new ECKey().encrypt(scrypter, scrypter.deriveKey("other stuff"));
    chain.importKeys(key1);
}
 
Example #7
Source File: WalletsManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void encryptWallets(KeyCrypterScrypt keyCrypterScrypt, KeyParameter aesKey) {
    try {
        btcWalletService.encryptWallet(keyCrypterScrypt, aesKey);
        bsqWalletService.encryptWallet(keyCrypterScrypt, aesKey);

        // we save the key for the trade wallet as we don't require passwords here
        tradeWalletService.setAesKey(aesKey);
    } catch (Throwable t) {
        log.error(t.toString());
        throw t;
    }
}
 
Example #8
Source File: WalletPasswordController.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@FXML void confirmClicked(ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.bitcoin.wallet().getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected final void onFinish(KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.bitcoin.wallet().checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #9
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    super.encryptWallet(keyCrypterScrypt, key);
    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key));
    });
    addressEntryList.persist();
}
 
Example #10
Source File: WalletPasswordController.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
@FXML
void confirmClicked (ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.wallet.getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected void onFinish (KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.wallet.checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #11
Source File: ECKeyTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder().setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt()));
    ScryptParameters scryptParameters = scryptParametersBuilder.build();
    keyCrypter = new KeyCrypterScrypt(scryptParameters);

    BriefLogFormatter.init();
}
 
Example #12
Source File: BasicKeyChainTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = KeyCrypterException.class)
public void cannotMixParams() throws Exception {
    chain = chain.toEncrypted("foobar");
    KeyCrypterScrypt scrypter = new KeyCrypterScrypt(2);    // Some bogus params.
    ECKey key1 = new ECKey().encrypt(scrypter, scrypter.deriveKey("other stuff"));
    chain.importKeys(key1);
}
 
Example #13
Source File: ScryptUtil.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static KeyCrypterScrypt getKeyCrypterScrypt() {
    Protos.ScryptParameters scryptParameters = Protos.ScryptParameters.newBuilder()
            .setP(6)
            .setR(8)
            .setN(32768)
            .setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt()))
            .build();
    return new KeyCrypterScrypt(scryptParameters);
}
 
Example #14
Source File: CoreWalletsService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void removeWalletPassword(String password) {
    verifyWalletIsAvailableAndEncrypted();
    KeyCrypterScrypt keyCrypterScrypt = getKeyCrypterScrypt();

    KeyParameter aesKey = keyCrypterScrypt.deriveKey(password);
    if (!walletsManager.checkAESKey(aesKey))
        throw new IllegalStateException("incorrect password");

    walletsManager.decryptWallets(aesKey);
    walletsManager.backupWallets();
}
 
Example #15
Source File: WalletPasswordController.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@FXML void confirmClicked(ActionEvent event) {
    String password = pass1.getText();
    if (password.isEmpty() || password.length() < 4) {
        informationalAlert("Bad password", "The password you entered is empty or too short.");
        return;
    }

    final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) Main.bitcoin.wallet().getKeyCrypter();
    checkNotNull(keyCrypter);   // We should never arrive at this GUI if the wallet isn't actually encrypted.
    KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) {
        @Override
        protected final void onFinish(KeyParameter aesKey, int timeTakenMsec) {
            checkGuiThread();
            if (Main.bitcoin.wallet().checkAESKey(aesKey)) {
                WalletPasswordController.this.aesKey.set(aesKey);
            } else {
                log.warn("User entered incorrect password");
                fadeOut(progressMeter);
                fadeIn(widgetGrid);
                fadeIn(explanationLabel);
                fadeIn(buttonsBox);
                informationalAlert("Wrong password",
                        "Please try entering your password again, carefully checking for typos or spelling errors.");
            }
        }
    };
    progressMeter.progressProperty().bind(tasks.progress);
    tasks.start();

    fadeIn(progressMeter);
    fadeOut(widgetGrid);
    fadeOut(explanationLabel);
    fadeOut(buttonsBox);
}
 
Example #16
Source File: ScryptUtil.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public static KeyCrypterScrypt getKeyCrypterScrypt() {
    Protos.ScryptParameters scryptParameters = Protos.ScryptParameters.newBuilder()
            .setP(6)
            .setR(8)
            .setN(32768)
            .setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt()))
            .build();
    return new KeyCrypterScrypt(scryptParameters);
}
 
Example #17
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    super.encryptWallet(keyCrypterScrypt, key);
    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key));
    });
    addressEntryList.persist();
}
 
Example #18
Source File: WalletsManager.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public void encryptWallets(KeyCrypterScrypt keyCrypterScrypt, KeyParameter aesKey) {
    try {
        btcWalletService.encryptWallet(keyCrypterScrypt, aesKey);
        if (BisqEnvironment.isBaseCurrencySupportingBsq())
            bsqWalletService.encryptWallet(keyCrypterScrypt, aesKey);

        // we save the key for the trade wallet as we don't require passwords here
        tradeWalletService.setAesKey(aesKey);
    } catch (Throwable t) {
        log.error(t.toString());
        throw t;
    }
}
 
Example #19
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    if (this.aesKey != null) {
        log.warn("encryptWallet called but we have a aesKey already set. " +
                "We decryptWallet with the old key before we apply the new key.");
        decryptWallet(this.aesKey);
    }

    wallet.encrypt(keyCrypterScrypt, key);
    aesKey = key;
}
 
Example #20
Source File: ECKeyTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder().setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt()));
    ScryptParameters scryptParameters = scryptParametersBuilder.build();
    keyCrypter = new KeyCrypterScrypt(scryptParameters);

    BriefLogFormatter.init();
}
 
Example #21
Source File: WalletsManager.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public KeyCrypterScrypt getKeyCrypterScrypt() {
    if (areWalletsEncrypted() && btcWalletService.getKeyCrypter() != null)
        return (KeyCrypterScrypt) btcWalletService.getKeyCrypter();
    else
        return ScryptUtil.getKeyCrypterScrypt();
}
 
Example #22
Source File: WalletProtobufSerializer.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Converts the given wallet to the object representation of the protocol buffers. This can be modified, or
 * additional data fields set, before serialization takes place.
 */
public Protos.Wallet walletToProto(Wallet wallet) {
    Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
    walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
    if (wallet.getDescription() != null) {
        walletBuilder.setDescription(wallet.getDescription());
    }

    for (WalletTransaction wtx : wallet.getWalletTransactions()) {
        Protos.Transaction txProto = makeTxProto(wtx);
        walletBuilder.addTransaction(txProto);
    }

    walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobuf());

    for (Script script : wallet.getWatchedScripts()) {
        Protos.Script protoScript =
                Protos.Script.newBuilder()
                        .setProgram(ByteString.copyFrom(script.getProgram()))
                        .setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
                        .build();

        walletBuilder.addWatchedScript(protoScript);
    }

    // Populate the lastSeenBlockHash field.
    Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
    if (lastSeenBlockHash != null) {
        walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
        walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
    }
    if (wallet.getLastBlockSeenTimeSecs() > 0)
        walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());

    // Populate the scrypt parameters.
    KeyCrypter keyCrypter = wallet.getKeyCrypter();
    if (keyCrypter == null) {
        // The wallet is unencrypted.
        walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
    } else {
        // The wallet is encrypted.
        walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
        if (keyCrypter instanceof KeyCrypterScrypt) {
            KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
            walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
        } else {
            // Some other form of encryption has been specified that we do not know how to persist.
            throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
        }
    }

    if (wallet.getKeyRotationTime() != null) {
        long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
        walletBuilder.setKeyRotationTime(timeSecs);
    }

    populateExtensions(wallet, walletBuilder);

    for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
        Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
        walletBuilder.addTags(tag);
    }

    // Populate the wallet version.
    walletBuilder.setVersion(wallet.getVersion());

    return walletBuilder.build();
}
 
Example #23
Source File: CoreWalletsService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private KeyCrypterScrypt getKeyCrypterScrypt() {
    KeyCrypterScrypt keyCrypterScrypt = walletsManager.getKeyCrypterScrypt();
    if (keyCrypterScrypt == null)
        throw new IllegalStateException("wallet encrypter is not available");
    return keyCrypterScrypt;
}
 
Example #24
Source File: PasswordView.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private void onApplyPassword(BusyAnimation busyAnimation, Label deriveStatusLabel) {
    String password = passwordField.getText();
    checkArgument(password.length() < 500, Res.get("password.tooLong"));

    pwButton.setDisable(true);
    deriveStatusLabel.setText(Res.get("password.deriveKey"));
    busyAnimation.play();

    KeyCrypterScrypt keyCrypterScrypt = walletsManager.getKeyCrypterScrypt();
    ScryptUtil.deriveKeyWithScrypt(keyCrypterScrypt, password, aesKey -> {
        deriveStatusLabel.setText("");
        busyAnimation.stop();

        if (walletsManager.areWalletsEncrypted()) {
            if (walletsManager.checkAESKey(aesKey)) {
                walletsManager.decryptWallets(aesKey);
                new Popup()
                        .feedback(Res.get("password.walletDecrypted"))
                        .show();
                backupWalletAndResetFields();
            } else {
                pwButton.setDisable(false);
                new Popup()
                        .warning(Res.get("password.wrongPw"))
                        .show();
            }
        } else {
            try {
                walletsManager.encryptWallets(keyCrypterScrypt, aesKey);
                new Popup()
                        .feedback(Res.get("password.walletEncrypted"))
                        .show();
                backupWalletAndResetFields();
                walletsManager.clearBackup();
            } catch (Throwable t) {
                new Popup()
                        .warning(Res.get("password.walletEncryptionFailed"))
                        .show();
            }
        }
        setText();
        updatePasswordListeners();
    });
}
 
Example #25
Source File: WalletPasswordWindow.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void addButtons() {
    BusyAnimation busyAnimation = new BusyAnimation(false);
    Label deriveStatusLabel = new AutoTooltipLabel();

    unlockButton = new AutoTooltipButton(Res.get("shared.unlock"));
    unlockButton.setDefaultButton(true);
    unlockButton.getStyleClass().add("action-button");
    unlockButton.setDisable(true);
    unlockButton.setOnAction(e -> {
        String password = passwordTextField.getText();
        checkArgument(password.length() < 500, Res.get("password.tooLong"));
        KeyCrypterScrypt keyCrypterScrypt = walletsManager.getKeyCrypterScrypt();
        if (keyCrypterScrypt != null) {
            busyAnimation.play();
            deriveStatusLabel.setText(Res.get("password.deriveKey"));
            ScryptUtil.deriveKeyWithScrypt(keyCrypterScrypt, password, aesKey -> {
                if (walletsManager.checkAESKey(aesKey)) {
                    if (aesKeyHandler != null)
                        aesKeyHandler.onAesKey(aesKey);

                    hide();
                } else {
                    busyAnimation.stop();
                    deriveStatusLabel.setText("");

                    UserThread.runAfter(() -> new Popup()
                            .warning(Res.get("password.wrongPw"))
                            .onClose(this::blurAgain).show(), Transitions.DEFAULT_DURATION, TimeUnit.MILLISECONDS);
                }
            });
        } else {
            log.error("wallet.getKeyCrypter() is null, that must not happen.");
        }
    });

    forgotPasswordButton = new AutoTooltipButton(Res.get("password.forgotPassword"));
    forgotPasswordButton.setOnAction(e -> {
        forgotPasswordButton.setDisable(true);
        unlockButton.setDefaultButton(false);
        showRestoreScreen();
    });

    Button cancelButton = new AutoTooltipButton(Res.get("shared.cancel"));
    cancelButton.setOnAction(event -> {
        hide();
        closeHandlerOptional.ifPresent(Runnable::run);
    });

    HBox hBox = new HBox();
    hBox.setMinWidth(560);
    hBox.setPadding(new Insets(0, 0, 0, 0));
    hBox.setSpacing(10);
    GridPane.setRowIndex(hBox, ++rowIndex);
    hBox.setAlignment(Pos.CENTER_LEFT);
    hBox.getChildren().add(unlockButton);
    if (!hideForgotPasswordButton)
        hBox.getChildren().add(forgotPasswordButton);
    if (!hideCloseButton)
        hBox.getChildren().add(cancelButton);
    hBox.getChildren().addAll(busyAnimation, deriveStatusLabel);
    gridPane.getChildren().add(hBox);


    ColumnConstraints columnConstraints1 = new ColumnConstraints();
    columnConstraints1.setHalignment(HPos.LEFT);
    columnConstraints1.setHgrow(Priority.ALWAYS);
    gridPane.getColumnConstraints().addAll(columnConstraints1);
}
 
Example #26
Source File: KeyDerivationTasks.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call() throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call() throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded() {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}
 
Example #27
Source File: KeyDerivationTasks.java    From devcoretalk with GNU General Public License v2.0 4 votes vote down vote up
public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call() throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call() throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded() {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}
 
Example #28
Source File: WalletProtobufSerializer.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Converts the given wallet to the object representation of the protocol buffers. This can be modified, or
 * additional data fields set, before serialization takes place.
 */
public Protos.Wallet walletToProto(Wallet wallet) {
    Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
    walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
    if (wallet.getDescription() != null) {
        walletBuilder.setDescription(wallet.getDescription());
    }

    for (WalletTransaction wtx : wallet.getWalletTransactions()) {
        Protos.Transaction txProto = makeTxProto(wtx);
        walletBuilder.addTransaction(txProto);
    }

    walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobuf());

    for (Script script : wallet.getWatchedScripts()) {
        Protos.Script protoScript =
                Protos.Script.newBuilder()
                        .setProgram(ByteString.copyFrom(script.getProgram()))
                        .setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
                        .build();

        walletBuilder.addWatchedScript(protoScript);
    }

    // Populate the lastSeenBlockHash field.
    Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
    if (lastSeenBlockHash != null) {
        walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
        walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
    }
    if (wallet.getLastBlockSeenTimeSecs() > 0)
        walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());

    // Populate the scrypt parameters.
    KeyCrypter keyCrypter = wallet.getKeyCrypter();
    if (keyCrypter == null) {
        // The wallet is unencrypted.
        walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
    } else {
        // The wallet is encrypted.
        walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
        if (keyCrypter instanceof KeyCrypterScrypt) {
            KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
            walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
        } else {
            // Some other form of encryption has been specified that we do not know how to persist.
            throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
        }
    }

    if (wallet.getKeyRotationTime() != null) {
        long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
        walletBuilder.setKeyRotationTime(timeSecs);
    }

    populateExtensions(wallet, walletBuilder);

    for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
        Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
        walletBuilder.addTags(tag);
    }

    for (TransactionSigner signer : wallet.getTransactionSigners()) {
        // do not serialize LocalTransactionSigner as it's being added implicitly
        if (signer instanceof LocalTransactionSigner)
            continue;
        Protos.TransactionSigner.Builder protoSigner = Protos.TransactionSigner.newBuilder();
        protoSigner.setClassName(signer.getClass().getName());
        protoSigner.setData(ByteString.copyFrom(signer.serialize()));
        walletBuilder.addTransactionSigners(protoSigner);
    }

    // Populate the wallet version.
    walletBuilder.setVersion(wallet.getVersion());

    return walletBuilder.build();
}
 
Example #29
Source File: KeyDerivationTasks.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call() throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call() throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded() {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}
 
Example #30
Source File: KeyDerivationTasks.java    From thunder with GNU Affero General Public License v3.0 4 votes vote down vote up
public KeyDerivationTasks (KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) {
    keyDerivationTask = new Task<KeyParameter>() {
        @Override
        protected KeyParameter call () throws Exception {
            long start = System.currentTimeMillis();
            try {
                log.info("Started key derivation");
                KeyParameter result = scrypt.deriveKey(password);
                timeTakenMsec = (int) (System.currentTimeMillis() - start);
                log.info("Key derivation done in {}ms", timeTakenMsec);
                return result;
            } catch (Throwable e) {
                log.error("Exception during key derivation", e);
                throw e;
            }
        }
    };

    // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100%
    // a brief moment after the keys were derived successfully.
    progressTask = new Task<Void>() {
        private KeyParameter aesKey;

        @Override
        protected Void call () throws Exception {
            if (targetTime != null) {
                long startTime = System.currentTimeMillis();
                long curTime;
                long targetTimeMillis = targetTime.toMillis();
                while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) {
                    double progress = (curTime - startTime) / (double) targetTimeMillis;
                    updateProgress(progress, 1.0);

                    // 60fps would require 16msec sleep here.
                    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS);
                }
                // Wait for the encryption thread before switching back to main UI.
                updateProgress(1.0, 1.0);
            } else {
                updateProgress(-1, -1);
            }
            aesKey = keyDerivationTask.get();
            return null;
        }

        @Override
        protected void succeeded () {
            checkGuiThread();
            onFinish(aesKey, timeTakenMsec);
        }
    };
    progress = progressTask.progressProperty();
}