Java Code Examples for net.bither.bitherj.crypto.ECKey#clearPrivateKey()

The following examples show how to use net.bither.bitherj.crypto.ECKey#clearPrivateKey() . 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: KeyUtil.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static List<Address> addPrivateKeyByRandomWithPassphras(IUEntropy iuEntropy, CharSequence password, int count) {
    PeerUtil.stopPeer();
    List<Address> addressList = new ArrayList<Address>();
    for (int i = 0; i < count; i++) {
        XRandom xRandom = new XRandom(iuEntropy);
        ECKey ecKey = ECKey.generateECKey(xRandom);
        ecKey = PrivateKeyUtil.encrypt(ecKey, password);
        Address address = new Address(ecKey.toAddress(),
                ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
        ecKey.clearPrivateKey();
        addressList.add(address);
        AddressManager.getInstance().addAddress(address);

    }
    PeerUtil.startPeer();
    if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
        BackupUtil.backupColdKey(false);
    } else {
        BackupUtil.backupHotKey();
    }

    return addressList;

}
 
Example 2
Source File: KeyUtil.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static List<Address> addPrivateKeyByRandomWithPassphras(IUEntropy iuEntropy, CharSequence password, int count) {
    PeerUtil.stopPeer();
    List<Address> addressList = new ArrayList<Address>();
    for (int i = 0; i < count; i++) {
        XRandom xRandom = new XRandom(iuEntropy);
        ECKey ecKey = ECKey.generateECKey(xRandom);
        ecKey = PrivateKeyUtil.encrypt(ecKey, password);
        Address address = new Address(ecKey.toAddress(),
                ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
        ecKey.clearPrivateKey();
        addressList.add(address);
        AddressManager.getInstance().addAddress(address);

    }
    PeerUtil.startPeer();
    if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
        BackupUtil.backupColdKey(false);
    } else {
        BackupUtil.backupHotKey();
    }

    return addressList;

}
 
Example 3
Source File: Address.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws
        PasswordException {
    ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getFullEncryptPrivKey(), passphrase);
    if (key == null) {
        throw new PasswordException("do not decrypt eckey");
    }
    KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase);
    List<byte[]> result = new ArrayList<byte[]>();
    for (byte[] unsignedInHash : unsignedInHashes) {
        TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash,
                assKey), TransactionSignature.SigHash.ALL, false);
        result.add(ScriptBuilder.createInputScript(signature, key).getProgram());
    }
    key.clearPrivateKey();
    return result;
}
 
Example 4
Source File: PrivateKeyUtil.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * will release key
 *
 * @param key
 * @param password
 * @return
 */
public static ECKey encrypt(ECKey key, CharSequence password) {
    KeyCrypter scrypt = new KeyCrypterScrypt();
    KeyParameter derivedKey = scrypt.deriveKey(password);
    ECKey encryptedKey = key.encrypt(scrypt, derivedKey);

    // Check that the encrypted key can be successfully decrypted.
    // This is done as it is a critical failure if the private key cannot be decrypted successfully
    // (all bitcoin controlled by that private key is lost forever).
    // For a correctly constructed keyCrypter the encryption should always be reversible so it is just being as cautious as possible.
    if (!ECKey.encryptionIsReversible(key, encryptedKey, scrypt, derivedKey)) {
        // Abort encryption
        throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption.");
    }
    key.clearPrivateKey();
    return encryptedKey;
}
 
Example 5
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void initHDAccount(DeterministicKey master, EncryptedData encryptedMnemonicSeed,
                           EncryptedData encryptedHDSeed, boolean isSyncedComplete) {
    String firstAddress;
    ECKey k = new ECKey(mnemonicSeed, null);
    String address = k.toAddress();
    k.clearPrivateKey();
    DeterministicKey accountKey = getAccount(master);
    DeterministicKey internalKey = getChainRootKey(accountKey, AbstractHD.PathType.INTERNAL_ROOT_PATH);
    DeterministicKey externalKey = getChainRootKey(accountKey, AbstractHD.PathType.EXTERNAL_ROOT_PATH);
    DeterministicKey key = externalKey.deriveSoftened(0);
    firstAddress = key.toAddress();
    accountKey.wipe();
    master.wipe();

    wipeHDSeed();
    wipeMnemonicSeed();
    hdSeedId = AbstractDb.desktopAddressProvider.addHDKey(encryptedMnemonicSeed.toEncryptedString(),
            encryptedHDSeed.toEncryptedString(), firstAddress, isFromXRandom, address, externalKey.getPubKeyExtended(), internalKey
                    .getPubKeyExtended());
    internalKey.wipe();
    externalKey.wipe();


}
 
Example 6
Source File: HDMBId.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public String setSignatureAndGetAddressOfAddressOfSp(byte[] signed, CharSequence password, String firstHotAddress) throws Exception {
    String addressOfSP = null;
    String message = getBitidString();
    byte[] hash = Utils.getPreSignMessage(message);
    ECKey key = ECKey.signedMessageToKey(hash, signed);
    if (Utils.compareString(address, key.toAddress())) {
        throw new SignatureException();

    }
    String hotAddress = firstHotAddress != null ? firstHotAddress : AddressManager.getInstance().getHdmKeychain().getFirstAddressFromDb();
    UploadHDMBidApi uploadHDMBidApi = new UploadHDMBidApi(address, hotAddress, signed, decryptedPassword);
    uploadHDMBidApi.handleHttpPost();
    boolean result = uploadHDMBidApi.getResult();
    if (result) {
        encryptedBitherPassword = new EncryptedData(decryptedPassword, password);
        ECKey k = new ECKey(decryptedPassword, null);
        addressOfSP = k.toAddress();
        k.clearPrivateKey();
        if (firstHotAddress == null) {
            save(addressOfSP);
        }
    } else {
        throw new HttpException("UploadHDMBidApi error");
    }
    return addressOfSP;
}
 
Example 7
Source File: CheckUtil.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public static Check initCheckForPrivateKey(
        final Address address, final SecureCharSequence password) {
    String title = String.format(LocaliserUtils.getString("check_address_private_key_title"), address
            .getShortAddress());
    Check check = new Check(title, new ICheckAction() {

        @Override
        public boolean check() {
            boolean result = new PasswordSeed(address.getAddress(), address.getFullEncryptPrivKey()).checkPassword(password);
            if (!result) {
                try {
                    ECKey eckeyFromBackup = BackupUtil.getEckeyFromBackup(
                            address.getAddress(), password);
                    if (eckeyFromBackup != null) {
                        String encryptPrivateKey = PrivateKeyUtil.getEncryptedString(eckeyFromBackup);
                        if (!Utils.isEmpty(encryptPrivateKey)) {
                            address.recoverFromBackup(encryptPrivateKey);
                            result = true;
                        }
                        eckeyFromBackup.clearPrivateKey();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    password.wipe();
                }


            }
            return result;
        }
    });
    return check;
}
 
Example 8
Source File: CheckUtil.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public static Check initCheckForPrivateKey(
        final Address address, final SecureCharSequence password) {
    String title = String.format(LocaliserUtils.getString("check_address_private_key_title"), address
            .getShortAddress());
    Check check = new Check(title, new ICheckAction() {

        @Override
        public boolean check() {
            boolean result = new PasswordSeed(address.getAddress(), address.getFullEncryptPrivKey()).checkPassword(password);
            if (!result) {
                try {
                    ECKey eckeyFromBackup = BackupUtil.getEckeyFromBackup(
                            address.getAddress(), password);
                    if (eckeyFromBackup != null) {
                        String encryptPrivateKey = PrivateKeyUtil.getEncryptedString(eckeyFromBackup);
                        if (!Utils.isEmpty(encryptPrivateKey)) {
                            address.recoverFromBackup(encryptPrivateKey);
                            result = true;
                        }
                        eckeyFromBackup.clearPrivateKey();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    password.wipe();
                }


            }
            return result;
        }
    });
    return check;
}
 
Example 9
Source File: HDAccountCold.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public HDAccountCold(byte[] mnemonicSeed, CharSequence password, boolean isFromXRandom)
        throws MnemonicException.MnemonicLengthException {
    this.mnemonicSeed = mnemonicSeed;
    hdSeed = seedFromMnemonic(mnemonicSeed);
    this.isFromXRandom = isFromXRandom;
    DeterministicKey master = HDKeyDerivation.createMasterPrivateKey(hdSeed);
    EncryptedData encryptedHDSeed = new EncryptedData(hdSeed, password, isFromXRandom);
    EncryptedData encryptedMnemonicSeed = new EncryptedData(mnemonicSeed, password,
            isFromXRandom);
    ECKey k = new ECKey(mnemonicSeed, null);
    String address = k.toAddress();
    k.clearPrivateKey();
    DeterministicKey accountKey = getAccount(master);
    DeterministicKey externalKey = getChainRootKey(accountKey, AbstractHD.PathType
            .EXTERNAL_ROOT_PATH);
    DeterministicKey internalKey = getChainRootKey(accountKey, PathType
            .INTERNAL_ROOT_PATH);
    DeterministicKey key = externalKey.deriveSoftened(0);
    String firstAddress = key.toAddress();
    accountKey.wipe();
    master.wipe();
    wipeHDSeed();
    wipeMnemonicSeed();
    hdSeedId = AbstractDb.hdAccountProvider.addHDAccount(encryptedMnemonicSeed
                    .toEncryptedString(), encryptedHDSeed.toEncryptedString(), firstAddress,
            isFromXRandom, address, externalKey.getPubKeyExtended(), internalKey
                    .getPubKeyExtended());
    externalKey.wipe();
}
 
Example 10
Source File: HDMKeychain.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public PasswordSeed createPasswordSeed(CharSequence password) {
    if (isInRecovery()) {
        throw new AssertionError("HDM in recovery can not create passwordSeed");
    }
    String encrypted = AbstractDb.addressProvider.getEncryptMnemonicSeed(hdSeedId);
    byte[] priv = new EncryptedData(encrypted).decrypt(password);
    ECKey k = new ECKey(priv, null);
    String address = k.toAddress();
    Utils.wipeBytes(priv);
    k.clearPrivateKey();
    return new PasswordSeed(address, encrypted);
}
 
Example 11
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public DesktopHDMKeychain(EncryptedData encryptedMnemonicSeed, CharSequence password) throws
        HDMBitherIdNotMatchException, MnemonicException.MnemonicLengthException {
    mnemonicSeed = encryptedMnemonicSeed.decrypt(password);
    hdSeed = seedFromMnemonic(mnemonicSeed);
    isFromXRandom = encryptedMnemonicSeed.isXRandom();
    EncryptedData encryptedHDSeed = new EncryptedData(hdSeed, password, isFromXRandom);
    ArrayList<DesktopHDMAddress> as = new ArrayList<DesktopHDMAddress>();
    ArrayList<HDMAddress.Pubs> uncompPubs = new ArrayList<HDMAddress.Pubs>();

    ECKey k = new ECKey(mnemonicSeed, null);
    String address = k.toAddress();
    k.clearPrivateKey();
    String firstAddress = getFirstAddressFromSeed(password);
    wipeMnemonicSeed();
    wipeHDSeed();

    this.hdSeedId = AbstractDb.desktopAddressProvider.addHDKey(encryptedMnemonicSeed
                    .toEncryptedString(), encryptedHDSeed.toEncryptedString(), firstAddress,
            isFromXRandom, address, null, null);
    if (as.size() > 0) {
        //   EnDesktopAddressProvider.getInstance().completeHDMAddresses(getHdSeedId(), as);

        if (uncompPubs.size() > 0) {
            //  EnDesktopAddressProvider.getInstance().prepareHDMAddresses(getHdSeedId(), uncompPubs);
            for (HDMAddress.Pubs p : uncompPubs) {
                AbstractDb.addressProvider.setHDMPubsRemote(getHdSeedId(), p.index, p.remote);
            }
        }
    }
}
 
Example 12
Source File: ImportPrivateKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Address initPrivateKey() {
    ECKey ecKey = getEckey();
    try {
        if (ecKey == null) {
            if (importPrivateKeyType == ImportPrivateKeyType.BitherQrcode) {
                importError(PASSWORD_WRONG);
            } else {
                importError(IMPORT_FAILED);
            }
            return null;
        } else {
            List<String> addressList = new ArrayList<String>();
            addressList.add(ecKey.toAddress());
            return addECKey(ecKey);
        }
    } catch (Exception e) {
        e.printStackTrace();
        importError(IMPORT_FAILED);
        return null;
    } finally {
        password.wipe();
        if (ecKey != null) {
            ecKey.clearPrivateKey();
        }
    }

}
 
Example 13
Source File: PrivateKeyUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static List<Address> getECKeysFromBackupString(String str, CharSequence password) {
    String[] strs = QRCodeUtil.splitOfPasswordSeed(str);
    if (strs.length % 3 != 0) {
        log.error("Backup: PrivateKeyFromString format error");
        return null;
    }
    ArrayList<Address> list = new ArrayList<Address>();
    for (int i = 0;
         i < strs.length;
         i += 3) {
        if (strs[i].indexOf(QRCodeUtil.HDM_QR_CODE_FLAG) == 0) {
            continue;
        }
        if (strs[i].indexOf(QRCodeUtil.HD_QR_CODE_FLAG) == 0){
            continue;
        }
        String encryptedString = strs[i] + QRCodeUtil.QR_CODE_SPLIT + strs[i + 1]
                + QRCodeUtil.QR_CODE_SPLIT + strs[i + 2];
        ECKey key = getECKeyFromSingleString(encryptedString, password);

        if (key == null) {
            return null;
        } else {
            Address address = new Address(key.toAddress(), key.getPubKey(), encryptedString,
                    false, key.isFromXRandom());
            key.clearPrivateKey();
            list.add(address);
        }
    }
    return list;
}
 
Example 14
Source File: CheckUtil.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public static Check initCheckForPrivateKey(
        final Address address, final SecureCharSequence password) {
    String title = String.format(BitherApplication.mContext.getString(R.string
            .check_address_private_key_title), address.getShortAddress());
    Check check = new Check(title, new ICheckAction() {

        @Override
        public boolean check() {
            PasswordSeed passwordSeed = new PasswordSeed(address.getAddress(), address.getFullEncryptPrivKey());
            boolean result = passwordSeed.checkPassword(password);
            if (!result) {
                try {
                    ECKey eckeyFromBackup = BackupUtil.getEckeyFromBackup(
                            address.getAddress(), password);
                    if (eckeyFromBackup != null) {
                        String encryptPrivateKey = PrivateKeyUtil.getEncryptedString(eckeyFromBackup);
                        eckeyFromBackup.clearPrivateKey();
                        if (!Utils.isEmpty(encryptPrivateKey)) {
                            address.recoverFromBackup(encryptPrivateKey);
                            result = true;
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            password.wipe();
            return result;
        }
    });
    return check;
}
 
Example 15
Source File: KeyUtil.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public static List<Address> addPrivateKeyByRandomWithPassphras(BlockchainService service, IUEntropy iuEntropy, CharSequence password, int count) {
    if (service != null) {
        service.stopAndUnregister();
    }
    List<Address> addressList = new ArrayList<Address>();
    for (int i = 0; i < count; i++) {
        XRandom xRandom = new XRandom(iuEntropy);
        ECKey ecKey = ECKey.generateECKey(xRandom);
        ecKey = PrivateKeyUtil.encrypt(ecKey, password);
        Address address = new Address(ecKey.toAddress(),
                ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), true, ecKey.isFromXRandom());
        ecKey.clearPrivateKey();
        addressList.add(address);
        AddressManager.getInstance().addAddress(address);

    }
    if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
        BackupUtil.backupColdKey(false);
    } else {
        BackupUtil.backupHotKey();
    }
    if (service != null) {
        service.startAndRegister();
    }
    return addressList;

}
 
Example 16
Source File: Bip38.java    From bitherj with Apache License 2.0 4 votes vote down vote up
public static SecureCharSequence decryptNoEcMultiply(Bip38PrivateKey bip38Key, byte[] stretcedKeyMaterial) throws AddressFormatException {
    // Derive Keys
    byte[] derivedHalf1 = new byte[32];
    System.arraycopy(stretcedKeyMaterial, 0, derivedHalf1, 0, 32);
    byte[] derivedHalf2 = new byte[32];
    System.arraycopy(stretcedKeyMaterial, 32, derivedHalf2, 0, 32);

    // Initialize AES key
    Rijndael aes = new Rijndael();
    aes.makeKey(derivedHalf2, 256);

    // Fetch first encrypted half
    byte[] encryptedHalf1 = new byte[16];
    System.arraycopy(bip38Key.data, 0, encryptedHalf1, 0, encryptedHalf1.length);

    // Fetch second encrypted half
    byte[] encryptedHalf2 = new byte[16];
    System.arraycopy(bip38Key.data, 16, encryptedHalf2, 0, encryptedHalf2.length);

    byte[] decryptedHalf1 = new byte[16];
    aes.decrypt(encryptedHalf1, decryptedHalf1);

    byte[] decryptedHalf2 = new byte[16];
    aes.decrypt(encryptedHalf2, decryptedHalf2);

    byte[] complete = new byte[32];
    for (int i = 0; i < 16; i++) {
        complete[i] = (byte) ((((int) decryptedHalf1[i]) & 0xFF) ^ (((int) derivedHalf1[i]) & 0xFF));
        complete[i + 16] = (byte) ((((int) decryptedHalf2[i]) & 0xFF) ^ (((int) derivedHalf1[i + 16]) & 0xFF));
    }

    // Create private key
    ECKey key = new ECKey(new BigInteger(1, complete), null, bip38Key.compressed);

    // Validate result

    byte[] newSalt = calculateScryptSalt(key.toAddress());
    if (!Arrays.equals(bip38Key.salt, newSalt)) {
        // The passphrase is either invalid or we are on the wrong network
        return null;
    }

    // Get SIPA format
    DumpedPrivateKey dumpedPrivateKey = new DumpedPrivateKey(key.getPrivKeyBytes(), key.isCompressed());

    SecureCharSequence secureCharSequence = dumpedPrivateKey.toSecureCharSequence();
    dumpedPrivateKey.clearPrivateKey();
    key.clearPrivateKey();
    return secureCharSequence;
}
 
Example 17
Source File: Address.java    From bitherj with Apache License 2.0 4 votes vote down vote up
public String signMessage(String msg, CharSequence passphrase) {

        ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getFullEncryptPrivKey(), passphrase);
        if (key == null) {
            throw new PasswordException("do not decrypt eckey");
        }
        KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase);

        String result = key.signMessage(msg, assKey);


        key.clearPrivateKey();
        return result;


    }
 
Example 18
Source File: PrivateKeyUEntropyActivity.java    From bither-android with Apache License 2.0 4 votes vote down vote up
@Override
public void runWithService(BlockchainService service) {
    boolean success = false;
    final ArrayList<String> addressStrs = new ArrayList<String>();
    double progress = startProgress;
    double itemProgress = (1.0 - startProgress - saveProgress) / (double) targetCount;

    try {
        entropyCollector.start();
        if (service != null) {
            service.stopAndUnregister();
        }

        XRandom xRandom = new XRandom(entropyCollector);

        List<Address> addressList = new ArrayList<Address>();
        for (int i = 0;
             i < targetCount;
             i++) {
            if (cancelRunnable != null) {
                finishGenerate(service);
                runOnUiThread(cancelRunnable);
                return;
            }

            ECKey ecKey = ECKey.generateECKey(xRandom);
            ecKey.setFromXRandom(true);

            progress += itemProgress * progressKeyRate;
            onProgress(progress);
            if (cancelRunnable != null) {
                finishGenerate(service);
                runOnUiThread(cancelRunnable);
                return;
            }


            // start encrypt
            ecKey = PrivateKeyUtil.encrypt(ecKey, password);
            Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(),
                    PrivateKeyUtil.getEncryptedString(ecKey), true, ecKey.isFromXRandom());
            ecKey.clearPrivateKey();
            addressList.add(address);
            addressStrs.add(address.getAddress());

            progress += itemProgress * progressEntryptRate;
            onProgress(progress);
        }

        entropyCollector.stop();
        password.wipe();
        password = null;

        if (cancelRunnable != null) {
            finishGenerate(service);
            runOnUiThread(cancelRunnable);
            return;
        }

        KeyUtil.addAddressListByDesc(service, addressList);
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    finishGenerate(service);
    if (success) {
        while (System.currentTimeMillis() - startGeneratingTime < MinGeneratingTime) {

        }
        onProgress(1);
        onSuccess(addressStrs);
    } else {
        onFailed();
    }
}
 
Example 19
Source File: PrivateKeyUEntropyDialog.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    startGeneratingTime = System.currentTimeMillis();
    onProgress(startProgress);
    SecureCharSequence password = passwordGetter.getPassword();
    boolean success = false;
    final ArrayList<String> addressStrs = new ArrayList<String>();
    double progress = startProgress;
    double itemProgress = (1.0 - startProgress - saveProgress) / (double) targetCount;

    try {
        entropyCollector.start();
        PeerUtil.stopPeer();

        java.util.List<Address> addressList = new ArrayList<Address>();
        for (int i = 0;
             i < targetCount;
             i++) {
            if (cancelRunnable != null) {
                finishGenerate();
                SwingUtilities.invokeLater(cancelRunnable);
                return;
            }

            XRandom xRandom = new XRandom(entropyCollector);
            ECKey ecKey = ECKey.generateECKey(xRandom);
            ecKey.setFromXRandom(true);
            progress += itemProgress * progressKeyRate;
            onProgress(progress);
            if (cancelRunnable != null) {
                finishGenerate();
                SwingUtilities.invokeLater(cancelRunnable);

                return;
            }
            // start encrypt
            ecKey = PrivateKeyUtil.encrypt(ecKey, password);
            Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(),
                    PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
            ecKey.clearPrivateKey();
            addressList.add(address);
            addressStrs.add(address.getAddress());

            progress += itemProgress * progressEntryptRate;
            onProgress(progress);
        }
        entropyCollector.stop();
        passwordGetter.wipe();

        if (cancelRunnable != null) {
            finishGenerate();
            SwingUtilities.invokeLater(cancelRunnable);
            return;
        }
        KeyUtil.addAddressListByDesc(addressList);
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    finishGenerate();
    if (success) {
        while (System.currentTimeMillis() - startGeneratingTime < MinGeneratingTime) {

        }
        onProgress(1);
        didSuccess(addressStrs);
    } else {
        onFailed();
    }
}
 
Example 20
Source File: PrivateKeyUEntropyDialog.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    startGeneratingTime = System.currentTimeMillis();
    onProgress(startProgress);
    SecureCharSequence password = passwordGetter.getPassword();
    boolean success = false;
    final ArrayList<String> addressStrs = new ArrayList<String>();
    double progress = startProgress;
    double itemProgress = (1.0 - startProgress - saveProgress) / (double) targetCount;

    try {
        entropyCollector.start();
        PeerUtil.stopPeer();

        java.util.List<Address> addressList = new ArrayList<Address>();
        for (int i = 0;
             i < targetCount;
             i++) {
            if (cancelRunnable != null) {
                finishGenerate();
                SwingUtilities.invokeLater(cancelRunnable);
                return;
            }

            XRandom xRandom = new XRandom(entropyCollector);
            ECKey ecKey = ECKey.generateECKey(xRandom);
            ecKey.setFromXRandom(true);
            progress += itemProgress * progressKeyRate;
            onProgress(progress);
            if (cancelRunnable != null) {
                finishGenerate();
                SwingUtilities.invokeLater(cancelRunnable);

                return;
            }
            // start encrypt
            ecKey = PrivateKeyUtil.encrypt(ecKey, password);
            Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(),
                    PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
            ecKey.clearPrivateKey();
            addressList.add(address);
            addressStrs.add(address.getAddress());

            progress += itemProgress * progressEntryptRate;
            onProgress(progress);
        }
        entropyCollector.stop();
        passwordGetter.wipe();

        if (cancelRunnable != null) {
            finishGenerate();
            SwingUtilities.invokeLater(cancelRunnable);
            return;
        }
        KeyUtil.addAddressListByDesc(addressList);
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    finishGenerate();
    if (success) {
        while (System.currentTimeMillis() - startGeneratingTime < MinGeneratingTime) {

        }
        onProgress(1);
        didSuccess(addressStrs);
    } else {
        onFailed();
    }
}