net.bither.bitherj.crypto.ECKey Java Examples

The following examples show how to use net.bither.bitherj.crypto.ECKey. 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: 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 #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: Tx.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new and fully signed input for the given parameters. Note that this method is
 * <b>not</b> thread safe
 * and requires external synchronization. Please refer to general documentation on Bitcoin
 * scripting and contracts
 * to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form
 * of this method
 * that sets them to typical defaults.
 *
 * @throws net.bither.bitherj.exception.ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script.
 */
public In addSignedInput(Out prevOut, Script scriptPubKey, ECKey sigKey,
                         TransactionSignature.SigHash sigHash, boolean anyoneCanPay) throws
        ScriptException {
    In input = new In(this, new byte[]{}, prevOut);
    addInput(input);
    byte[] hash = hashForSignature(ins.size() - 1, scriptPubKey, sigHash, anyoneCanPay);
    ECKey.ECDSASignature ecSig = sigKey.sign(hash);
    TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setInSignature(ScriptBuilder.createInputScript(txSig).getProgram());
    } else if (scriptPubKey.isSentToAddress()) {
        input.setInSignature(ScriptBuilder.createInputScript(txSig, sigKey).getProgram());
    } else {
        throw new ScriptException("Don't know how to sign for this kind of scriptPubKey: " +
                scriptPubKey);
    }
    return input;
}
 
Example #4
Source File: BackupUtil.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
    File file = FileUtil.getBackupFile();
    String str = Utils.readFile(file);
    if (str.contains(address)) {
        String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
        for (String backupStr : backupStrArray) {
            if (backupStr.contains(address)) {
                String[] strArray = QRCodeUtil.splitString(backupStr);
                if (strArray.length > 3) {
                    String keyString = backupStr.substring(strArray[0]
                            .length() + 1);
                    return PrivateKeyUtil.getECKeyFromSingleString(
                            keyString, password);
                }
            }
        }
    }
    return null;
}
 
Example #5
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 #6
Source File: Tx.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private byte[] getSignPubs(byte[] messageHash,
                           ECKey.ECDSASignature sig, List<byte[]> pubs) {

    for (int i = 0; i < 4; i++) {
        ECPoint point = ECKey.recoverECPointFromSignature(i, sig, messageHash);
        ECKey ecKeyCompress = new ECKey(null, point.getEncoded(true));
        ECKey ecKeyUnCompress = new ECKey(null, point.getEncoded(false));
        for (int j = 0; j < pubs.size(); j++) {
            if (Arrays.equals(ecKeyCompress.getPubKey(), pubs.get(j))) {
                return ecKeyCompress.getPubKey();

            }
            if (Arrays.equals(ecKeyUnCompress.getPubKey(), pubs.get(j))) {
                return ecKeyUnCompress.getPubKey();

            }
        }
    }
    return null;
}
 
Example #7
Source File: BackupUtil.java    From bither-android with Apache License 2.0 6 votes vote down vote up
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
    File file = FileUtil.getBackupKeyOfHot();
    String str = Utils.readFile(file);
    if (str.contains(address)) {
        String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
        for (String backupStr : backupStrArray) {
            if (backupStr.contains(address)) {
                String[] strArray = QRCodeUtil.splitString(backupStr);
                if (strArray.length > 3) {
                    String keyString = backupStr.substring(strArray[0]
                            .length() + 1);
                    return PrivateKeyUtil.getECKeyFromSingleString(
                            keyString, password);
                }
            }
        }
    }
    return null;
}
 
Example #8
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 #9
Source File: UpgradeUtil.java    From bither-android with Apache License 2.0 6 votes vote down vote up
private static List<ECKey> initPrivateWallet(
        List<String> sequence) throws Exception {
    List<ECKey> result = new ArrayList<ECKey>();
    File dir = getPrivateCacheDir();
    File[] fs = dir.listFiles();
    if (sequence != null) {
        fs = sortAddressFile(fs, sequence);
    }
    for (File walletFile : fs) {
        String name = walletFile.getName();
        if (sequence.contains(name)) {
            ECKey ecKey = loadECKey(walletFile);
            result.add(ecKey);
        }
    }
    return result;
}
 
Example #10
Source File: DesktopHDMKeychain.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public ArrayList<byte[]> signWithCold(List<byte[]> unsignedHashes,
                                      CharSequence password,
                                      List<PathTypeIndex> pathTypeIndexList) {


    ArrayList<byte[]> sigs = new ArrayList<byte[]>();
    for (int i = 0;
         i < unsignedHashes.size();
         i++) {
        PathTypeIndex pathTypeIndex = pathTypeIndexList.get(i);
        DeterministicKey key;
        if (pathTypeIndex.pathType == PathType.EXTERNAL_ROOT_PATH) {
            key = getExternalKey(pathTypeIndex.index, password);
            System.out.println("pub:" + Base58.encode(key.getPubKey()));
        } else {
            key = getInternalKey(pathTypeIndex.index, password);
        }
        ECKey.ECDSASignature signed = key.sign(unsignedHashes.get(i));
        sigs.add(signed.encodeToDER());
        key.wipe();
    }

    return sigs;
}
 
Example #11
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 #12
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 #13
Source File: UpgradeUtil.java    From bither-android with Apache License 2.0 6 votes vote down vote up
private static List<ECKey> initWatchOnlyWallet(
        List<String> sequence) throws Exception {
    List<ECKey> result = new ArrayList<ECKey>();
    File dir = getWatchOnlyCacheDir();
    File[] fs = dir.listFiles();
    if (sequence != null) {
        fs = sortAddressFile(fs, sequence);
    }
    for (File walletFile : fs) {
        String name = walletFile.getName();
        if (sequence.contains(name)) {
            ECKey ecKey = loadECKey(walletFile);
            result.add(ecKey);
        }
    }
    return result;
}
 
Example #14
Source File: Script.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG.
 */
public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) {
    checkArgument(threshold > 0);
    checkArgument(threshold <= pubkeys.size());
    checkArgument(pubkeys.size() <= 16);  // That's the max we can represent with a single opcode.
    if (pubkeys.size() > 3) {
        log.warn("Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3", pubkeys.size());
    }
    try {
        ByteArrayOutputStream bits = new ByteArrayOutputStream();
        bits.write(encodeToOpN(threshold));
        for (ECKey key : pubkeys) {
            writeBytes(bits, key.getPubKey());
        }
        bits.write(encodeToOpN(pubkeys.size()));
        bits.write(OP_CHECKMULTISIG);
        return bits.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
Example #15
Source File: BackupUtil.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
    File file = FileUtil.getBackupFile();
    String str = Utils.readFile(file);
    if (str.contains(address)) {
        String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
        for (String backupStr : backupStrArray) {
            if (backupStr.contains(address)) {
                String[] strArray = QRCodeUtil.splitString(backupStr);
                if (strArray.length > 3) {
                    String keyString = backupStr.substring(strArray[0]
                            .length() + 1);
                    return PrivateKeyUtil.getECKeyFromSingleString(
                            keyString, password);
                }
            }
        }
    }
    return null;
}
 
Example #16
Source File: ImportPrivateKey.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private ECKey getEckey() {
    ECKey ecKey = null;
    DumpedPrivateKey dumpedPrivateKey = null;
    try {
        switch (this.importPrivateKeyType) {
            case Text:
                dumpedPrivateKey = new DumpedPrivateKey(this.content);
                ecKey = dumpedPrivateKey.getKey();
                break;
            case BitherQrcode:
                ecKey = PrivateKeyUtil.getECKeyFromSingleString(content, password);
                break;
            case Bip38:
                dumpedPrivateKey = new DumpedPrivateKey(this.content);
                ecKey = dumpedPrivateKey.getKey();
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dumpedPrivateKey != null) {
            dumpedPrivateKey.clearPrivateKey();
        }
    }
    return ecKey;
}
 
Example #17
Source File: QRCodeEnodeUtil.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public static List<Address> formatPublicString(String content) {
    String[] strs = QRCodeUtil.splitString(content);
    ArrayList<Address> wallets = new ArrayList<Address>();
    for (String str : strs) {
        boolean isXRandom = false;
        if (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0) {
            isXRandom = true;
            str = str.substring(1);
        }
        byte[] pub = Utils.hexStringToByteArray(str);

        org.spongycastle.math.ec.ECPoint ecPoint = ECKey.checkPoint(pub);
        if (ecPoint != null && ecPoint.isValid()) {
            String addString = Utils.toAddress(Utils.sha256hash160(pub));
            Address address = new Address(addString, pub, null, false, isXRandom);
            wallets.add(address);
        }
    }
    return wallets;

}
 
Example #18
Source File: QRCodeEnodeUtil.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public static boolean checkPubkeysQRCodeContent(String content) {
    String[] strs = QRCodeUtil.splitString(content);
    for (String str : strs) {
        boolean checkCompressed = str.length() == 66 || ((str.length() == 67)
                && (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0));
        boolean checkUnCompressed = str.length() == 130 || ((str.length() == 131)
                && (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0));
        if(str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0){
            str = str.substring(QRCodeUtil.XRANDOM_FLAG.length());
        }
        org.spongycastle.math.ec.ECPoint ecPoint = ECKey.checkPoint(Utils.hexStringToByteArray(str));

        if (ecPoint == null || !ecPoint.isValid()) {
            return false;
        }
        if (!checkCompressed && !checkUnCompressed) {
            return false;
        }
    }
    return true;
}
 
Example #19
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 #20
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 #21
Source File: EnterpriseHDMTxSignaturePool.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public boolean addSignature(List<byte[]> sigs) {
    if (sigs.size() != tx.getIns().size()) {
        return false;
    }
    ArrayList<TransactionSignature> txSigs = new ArrayList<TransactionSignature>();
    int pubIndex = -1;
    for (int i = 0;
         i < tx.getIns().size();
         i++) {
        TransactionSignature txSig = new TransactionSignature(ECKey.ECDSASignature
                .decodeFromDER(sigs.get(i)), TransactionSignature.SigHash.ALL, false);
        if (i == 0) {
            byte[] pub = recoverPub(sigs.get(i), unsignedHashes().get(i));
            if (pub == null) {
                break;
            }
            pubIndex = pubs.indexOf(pub);
            if (pubIndex < 0) {
                break;
            }
        }
        txSigs.add(txSig);
    }
    if (pubIndex < 0) {
        return false;
    }
    signatures.put(Integer.valueOf(pubIndex), txSigs);
    return true;
}
 
Example #22
Source File: DeterministicKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a key from its components, including its private key data and possibly-redundant
 * information about its parent key.  Invoked when deserializing, but otherwise not something that
 * you normally should use.
 */
private DeterministicKey(ImmutableList<ChildNumber> childNumberPath,
                         byte[] chainCode,
                         BigInteger priv,
                         @Nullable DeterministicKey parent,
                         int depth,
                         int parentFingerprint) {
    super(priv.toByteArray(), ECKey.publicKeyFromPrivate(priv, true));
    this.parent = parent;
    this.childNumberPath = childNumberPath;
    this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
    this.parentFingerprint = ascertainParentFingerprint(parent, parentFingerprint);
}
 
Example #23
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 #24
Source File: ImportPrivateKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private Address addECKey(ECKey ecKey) {
    String encryptedPrivateString;
    if (importPrivateKeyType == ImportPrivateKeyType.BitherQrcode) {
        encryptedPrivateString = QRCodeUtil.getNewVersionEncryptPrivKey(content);
    } else {
        ecKey = PrivateKeyUtil.encrypt(ecKey, password);
        encryptedPrivateString = PrivateKeyUtil.getEncryptedString(ecKey);
    }
    Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), encryptedPrivateString
            , false, ecKey.isFromXRandom());
    if (AddressManager.getInstance().getWatchOnlyAddresses().contains(address)) {
        password.wipe();
        importError(CAN_NOT_IMPORT_BITHER_COLD_PRIVATE_KEY);
        return null;
    } else if (AddressManager.getInstance().getPrivKeyAddresses().contains(address)) {
        password.wipe();
        importError(PRIVATE_KEY_ALREADY_EXISTS);
        return null;

    } else {
        if (importPrivateKeyType == ImportPrivateKeyType.BitherQrcode) {
            PasswordSeed passwordSeed = PasswordSeed.getPasswordSeed();
            if (passwordSeed != null && !passwordSeed.checkPassword(password)) {
                password.wipe();
                importError(PASSWORD_IS_DIFFEREND_LOCAL);
                return null;
            }
        } else {
            password.wipe();
        }
        return address;


    }

}
 
Example #25
Source File: BackupUtil.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public static ECKey getEckeyFromBackup(String address, CharSequence password) {
    if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
        return getEckeyFormBackupCold(address, password);
    } else {
        return getEckeyFormBackupHot(address, password);
    }

}
 
Example #26
Source File: PrivateKeyUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static boolean verifyMessage(String address, String messageText, String signatureText) {
    // Strip CRLF from signature text
    try {
        signatureText = signatureText.replaceAll("\n", "").replaceAll("\r", "");

        ECKey key = ECKey.signedMessageToKey(messageText, signatureText);
        String signAddress = key.toAddress();
        return Utils.compareString(address, signAddress);
    } catch (SignatureException e) {
        e.printStackTrace();
        return false;
    }

}
 
Example #27
Source File: SendHDMBitcoinPanel.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public boolean setQrCodeResult(String qr) {

            if (!Utils.isEmpty(qr)) {
                try {
                    String[] stringArray = QRCodeUtil.splitString(qr);
                    sigs = new ArrayList<TransactionSignature>();
                    for (String str : stringArray) {
                        if (!Utils.isEmpty(str)) {
                            TransactionSignature transactionSignature = new
                                    TransactionSignature(ECKey.ECDSASignature.decodeFromDER
                                    (Utils.hexStringToByteArray(str)),
                                    TransactionSignature.SigHash.ALL, false);
                            sigs.add(transactionSignature);
                        }
                    }
                } catch (Exception e) {
                    sigs = null;
                    e.printStackTrace();
                    new MessageDialog(LocaliserUtils.getString("send_failed")).showMsg();
                }
            } else {
                sigs = null;
            }
            try {
                lock.lock();
                fetchedCondition.signal();
            } finally {
                lock.unlock();
            }
            return true;

        }
 
Example #28
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 #29
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 #30
Source File: BackupUtil.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private static ECKey getEckeyFormBackupCold(String address, CharSequence password) {

        try {
            File[] files = FileUtil.getBackupDir().listFiles();
            if (files == null) {
                return null;
            }
            files = FileUtil.orderByDateDesc(files);
            for (int i = files.length - 1;
                 i >= 0;
                 i++) {
                File file = files[i];
                String str = Utils.readFile(file);
                if (str.contains(address)) {
                    String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
                    for (String backupStr : backupStrArray) {
                        if (backupStr.contains(address)) {
                            String[] strArray = QRCodeUtil.splitString(backupStr);
                            if (strArray.length > 3) {
                                String keyString = backupStr
                                        .substring(strArray[0].length() + 1);
                                return PrivateKeyUtil.getECKeyFromSingleString(
                                        keyString, password);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }