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

The following examples show how to use org.bitcoinj.core.ECKey#fromPublicOnly() . 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: SignedWitnessService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean verifySignatureWithECKey(SignedWitness signedWitness) {
    try {
        String message = Utilities.encodeToHex(signedWitness.getAccountAgeWitnessHash());
        String signatureBase64 = new String(signedWitness.getSignature(), Charsets.UTF_8);
        ECKey key = ECKey.fromPublicOnly(signedWitness.getSignerPubKey());
        if (arbitratorManager.isPublicKeyInList(Utilities.encodeToHex(key.getPubKey()))) {
            key.verifyMessage(message, signatureBase64);
            return true;
        } else {
            log.warn("Provided EC key is not in list of valid arbitrators.");
            return false;
        }
    } catch (SignatureException e) {
        log.warn("verifySignature signedWitness failed. signedWitness={}", signedWitness);
        log.warn("Caused by ", e);
        return false;
    }
}
 
Example 2
Source File: MeritConsensus.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
private static boolean isSignatureValid(byte[] signatureFromMerit, String pubKeyAsHex, String blindVoteTxId) {
    // We verify if signature of hash of blindVoteTxId is correct. EC key from first input for blind vote tx is
    // used for signature.
    if (pubKeyAsHex == null) {
        log.error("Error at isSignatureValid: pubKeyAsHex is null");
        return false;
    }

    boolean result = false;
    try {
        ECKey pubKey = ECKey.fromPublicOnly(Utilities.decodeFromHex(pubKeyAsHex));
        ECKey.ECDSASignature signature = ECKey.ECDSASignature.decodeFromDER(signatureFromMerit).toCanonicalised();
        Sha256Hash msg = Sha256Hash.wrap(blindVoteTxId);
        result = pubKey.verify(msg, signature);
    } catch (Throwable t) {
        log.error("Signature verification of issuance failed: " + t.toString());
    }
    if (!result) {
        log.error("Signature verification of issuance failed: blindVoteTxId={}, pubKeyAsHex={}",
                blindVoteTxId, pubKeyAsHex);
    }
    return result;
}
 
Example 3
Source File: ConnectionManagerImpl.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
private NodeClient ipObjectToNode (PubkeyIPObject ipObject, ChannelIntent intent) {
    NodeClient node = new NodeClient();
    node.isServer = false;
    node.intent = intent;
    node.pubKeyClient = ECKey.fromPublicOnly(ipObject.pubkey);
    node.host = ipObject.IP;
    node.port = ipObject.port;
    return node;
}
 
Example 4
Source File: KeyChainGroupTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void isWatching() {
    group = new KeyChainGroup(
            MAINNET,
            DeterministicKey
                    .deserializeB58(
                            "xpub69bjfJ91ikC5ghsqsVDHNq2dRGaV2HHVx7Y9LXi27LN9BWWAXPTQr4u8U3wAtap8bLdHdkqPpAcZmhMS5SnrMQC4ccaoBccFhh315P4UYzo",
                            MAINNET));
    final ECKey watchingKey = ECKey.fromPublicOnly(new ECKey().getPubKeyPoint());
    group.importKeys(watchingKey);
    assertTrue(group.isWatching());
}
 
Example 5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public void completeTxPartiallySigned(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
    // Check the wallet will write dummy scriptSigs for inputs that we have only pubkeys for without the privkey.
    ECKey priv = new ECKey();
    ECKey pub = ECKey.fromPublicOnly(priv.getPubKeyPoint());
    wallet.importKey(pub);
    ECKey priv2 = wallet.freshReceiveKey();
    // Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only,
    // and the final one being a key we do have. We expect the first two inputs to be dummy values and the last
    // to be signed correctly.
    Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, LegacyAddress.fromKey(UNITTEST, pub));
    Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub);
    Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2);

    SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
    req.missingSigsMode = missSigMode;
    wallet.completeTx(req);
    byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
    // Selected inputs can be in any order.
    for (int i = 0; i < req.tx.getInputs().size(); i++) {
        TransactionInput input = req.tx.getInput(i);
        if (input.getConnectedOutput().getParentTransaction().equals(t1)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t2)) {
            assertArrayEquals(expectedSig, input.getScriptSig().getChunks().get(0).data);
        } else if (input.getConnectedOutput().getParentTransaction().equals(t3)) {
            input.getScriptSig().correctlySpends(req.tx, i, t3.getOutput(0).getScriptPubKey());
        }
    }
    assertTrue(TransactionSignature.isEncodingCanonical(dummySig));
}
 
Example 6
Source File: DisputeAgentManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
protected boolean verifySignature(PublicKey storageSignaturePubKey, byte[] registrationPubKey, String signature) {
    String keyToSignAsHex = Utils.HEX.encode(storageSignaturePubKey.getEncoded());
    try {
        ECKey key = ECKey.fromPublicOnly(registrationPubKey);
        key.verifyMessage(keyToSignAsHex, signature);
        return true;
    } catch (SignatureException e) {
        log.warn("verifySignature failed");
        return false;
    }
}
 
Example 7
Source File: PublicKey.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
public String getAddress() {
    ECKey pk = ECKey.fromPublicOnly(publicKey.getPubKey());
    if (!pk.isCompressed()) {
        ECPoint point = ECKey.compressPoint(pk.getPubKeyPoint());
        pk = ECKey.fromPublicOnly(point);
    }
    return new address(pk).toString();
}
 
Example 8
Source File: LNOnionHelperImpl.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public OnionObject createOnionObject (List<byte[]> nodeList, byte[] payload) {
    if (nodeList.size() > OnionObject.MAX_HOPS) {
        throw new RuntimeException("Too many nodes in nodeList");
    }

    int byteCount = OnionObject.MAX_HOPS * OnionObject.TOTAL_LENGTH;
    byte[] data = Tools.getRandomByte(byteCount);

    for (int i = 0; i < nodeList.size(); ++i) {
        byte[] temp = new byte[byteCount];
        byte[] dataToSign = new byte[OnionObject.DATA_LENGTH];
        System.arraycopy(data, 0, temp, OnionObject.DATA_LENGTH, data.length - OnionObject.DATA_LENGTH);

        ECKey key = ECKey.fromPublicOnly(nodeList.get(nodeList.size() - 1 - i));
        ECKey keyServer = CryptoTools.getEphemeralKey();
        ECDHKeySet keySet = ECDH.getSharedSecret(keyServer, key);

        if (i > 0) {
            byte[] nextNode = nodeList.get(nodeList.size() - i);
            System.arraycopy(nextNode, 0, dataToSign, 0, nextNode.length);
        }

        System.arraycopy(dataToSign, 0, temp, 0, dataToSign.length);

        byte[] encryptedTemp = CryptoTools.encryptAES_CTR(temp, keySet.encryptionKey, keySet.ivClient, 0);
        byte[] hmac = CryptoTools.getHMAC(dataToSign, keySet.hmacKey);

        data = new byte[OnionObject.MAX_HOPS * OnionObject.TOTAL_LENGTH];

        System.arraycopy(keyServer.getPubKey(), 0, data, 0, OnionObject.KEY_LENGTH);
        System.arraycopy(hmac, 0, data, OnionObject.KEY_LENGTH, hmac.length);
        System.arraycopy(encryptedTemp, 0, data,
                OnionObject.KEY_LENGTH + OnionObject.HMAC_LENGTH, encryptedTemp.length - OnionObject.KEY_LENGTH - OnionObject.HMAC_LENGTH);

    }

    return new OnionObject(data);
}
 
Example 9
Source File: MeritConsensus.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
static boolean isSignatureValid(byte[] signatureFromMerit, String pubKeyAsHex, String blindVoteTxId) {
    // We verify if signature of hash of blindVoteTxId is correct. EC key from first input for blind vote tx is
    // used for signature.
    if (pubKeyAsHex == null) {
        log.error("Error at getMeritStake: pubKeyAsHex is null");
        return false;
    }

    // TODO Check if a sig key was used multiple times for different voters
    // At the moment we don't impl. that to not add too much complexity and as we consider that
    // risk very low.

    boolean result = false;
    try {
        ECKey pubKey = ECKey.fromPublicOnly(Utilities.decodeFromHex(pubKeyAsHex));
        ECKey.ECDSASignature signature = ECKey.ECDSASignature.decodeFromDER(signatureFromMerit).toCanonicalised();
        Sha256Hash msg = Sha256Hash.wrap(blindVoteTxId);
        result = pubKey.verify(msg, signature);
    } catch (Throwable t) {
        log.error("Signature verification of issuance failed: " + t.toString());
    }
    if (!result) {
        log.error("Signature verification of issuance failed: blindVoteTxId={}, pubKeyAsHex={}",
                blindVoteTxId, pubKeyAsHex);
    }
    return result;
}
 
Example 10
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private Script getMultiSigRedeemScript(byte[] buyerPubKey, byte[] sellerPubKey, byte[] arbitratorPubKey) {
    ECKey buyerKey = ECKey.fromPublicOnly(buyerPubKey);
    ECKey sellerKey = ECKey.fromPublicOnly(sellerPubKey);
    ECKey arbitratorKey = ECKey.fromPublicOnly(arbitratorPubKey);
    // Take care of sorting! Need to reverse to the order we use normally (buyer, seller, arbitrator)
    List<ECKey> keys = ImmutableList.of(arbitratorKey, sellerKey, buyerKey);
    return ScriptBuilder.createMultiSigOutputScript(2, keys);
}
 
Example 11
Source File: private_key.java    From bitshares_wallet with MIT License 5 votes vote down vote up
public sha512_object get_shared_secret(public_key publicKey) {
    ECKey ecPublicKey = ECKey.fromPublicOnly(publicKey.getKeyByte());
    ECKey ecPrivateKey = ECKey.fromPrivate(key_data);

    byte[] secret = ecPublicKey.getPubKeyPoint().multiply(ecPrivateKey.getPrivKey())
            .normalize().getXCoord().getEncoded();

    return sha512_object.create_from_byte_array(secret, 0, secret.length);
}
 
Example 12
Source File: PeeledOnion.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
void parseMessage (byte[] data) {
    byte[] pubkeyOfNextHop = new byte[33];
    System.arraycopy(data, 0, pubkeyOfNextHop, 0, 33);

    byte[] emptyData = new byte[OnionObject.KEY_LENGTH];

    if (Arrays.equals(emptyData, pubkeyOfNextHop)) {
        System.out.println("We are the last hop..");
        isLastHop = true;
    } else {
        nextHop = ECKey.fromPublicOnly(pubkeyOfNextHop);
    }
}
 
Example 13
Source File: LNOnionHelperImpl.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
private static ECDHKeySet getKeySet (ECKey keyServer, OnionObject encryptedOnionObject) {
    byte[] key = new byte[OnionObject.KEY_LENGTH];

    System.arraycopy(encryptedOnionObject.data, 0, key, 0, key.length);

    ECKey ephemeralKey = ECKey.fromPublicOnly(key);
    ECDHKeySet keySet = ECDH.getSharedSecret(keyServer, ephemeralKey);
    return keySet;
}
 
Example 14
Source File: EncryptionProcessorImpl.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processEncryptionInitialMessage (Message message) {
    if (!(message instanceof EncryptionInitialMessage)) {
        executor.sendMessageUpwards(messageFactory.getFailureMessage("Expecting EncryptionInitial Message.. " + message));
    } else {
        EncryptionInitialMessage encryptionInitial = (EncryptionInitialMessage) message;

        node.ephemeralKeyClient = ECKey.fromPublicOnly(encryptionInitial.key);
        node.ecdhKeySet = ECDH.getSharedSecret(node.ephemeralKeyServer, node.ephemeralKeyClient);

        sendInitialMessageIfNotSent();
        onKeyExchangeFinished();
    }
}
 
Example 15
Source File: HDKey.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static DeterministicKey createMasterKey(final byte[] chainCode, final byte[] publicKey) {
    final ECKey pub = ECKey.fromPublicOnly(publicKey);
    return new DeterministicKey(new ImmutableList.Builder<ChildNumber>().build(),
                                chainCode, pub.getPubKeyPoint(), null, null);
}
 
Example 16
Source File: TabActivity.java    From smartcoins-wallet with MIT License 4 votes vote down vote up
@Override
public void onSuccess(WitnessResponse response) {
    Log.d(TAG, "recovery.onSuccess. current update account task: " + currentTask);
    AccountProperties account = ((List<AccountProperties>) response.result).get(0);
    for (PublicKey publicKey : account.active.getKeyAuths().keySet()) {
        long weight = account.active.getKeyAuths().get(publicKey);
        Address networkAddress = new Address(publicKey.getKey());
        Log.d(TAG, String.format("Key controlling account: %s, weight: %d", networkAddress.toString(), weight));

        // Recovering task information
        BrainKey brainKey = currentTask.getBrainKey();
        ECKey privateKey = brainKey.getPrivateKey();
        Address cachedKeyAddress = new Address(ECKey.fromPublicOnly(privateKey.getPubKey()));
        Log.d(TAG, String.format("Network address: %s, key derived address: %s", cachedKeyAddress.toString(), networkAddress.toString()));
        if (networkAddress.toString().equals(cachedKeyAddress.toString())) {
            // Only if we get the absolute confirmation that this key we're holding
            // is the actual authority for this account we proceed to update the local
            // information.
            ArrayList<AccountDetails> accountDetails = tinyDB.getListObject(getResources().getString(R.string.pref_wallet_accounts), AccountDetails.class);
            for (AccountDetails accountDetail : accountDetails) {
                if (accountDetail.account_name.equals(currentlyActive.getName())) {
                    try {
                        accountDetail.brain_key = currentTask.getBrainKey().getBrainKey();
                        accountDetail.wif_key = Crypt.getInstance().encrypt_string(currentTask.getBrainKey().getWalletImportFormat());
                    } catch (Exception e) {
                        Log.e(TAG, "Exception while trying to update local key. Msg: " + e.getMessage());
                    }
                    break;
                }
            }
            Log.i(TAG, String.format("Updating account with brain key: %s -> %s", brainKey.getBrainKey(), networkAddress.toString()));
            /* Updating key of currently active account */
            tinyDB.putListObject(getResources().getString(R.string.pref_wallet_accounts), accountDetails);

            /* Updating store of old keys*/
            oldKey = String.format("%s:%s", currentTask.getAccount().getName(), brainKey.getWalletImportFormat());
            ArrayList<String> oldKeys = tinyDB.getListString(Constants.KEY_OLD_KEYS);
            oldKeys.add(oldKey);
            Log.d(TAG, String.format("Updating old keys, adding: %s. List is %d items long now", brainKey.getWalletImportFormat(), oldKeys.size()));
            tinyDB.putListString(Constants.KEY_OLD_KEYS, oldKeys);

            /* Removing this suggestion from the stored list */
            ArrayList<String> suggestions = tinyDB.getListString(Constants.KEY_SUGGESTED_BRAIN_KEY);
            for (int i = 0; i < suggestions.size(); i++) {
                if (suggestions.get(i).equals(brainKey.getBrainKey())) {
                    suggestions.remove(i);
                }
            }
            tinyDB.putListString(Constants.KEY_SUGGESTED_BRAIN_KEY, suggestions);
            break;
        } else {
            Log.d(TAG, "Got old key suggestion stored, but it does not correspond to the current network obtained current key, so we're not updating");
        }
    }
}
 
Example 17
Source File: LNOnionHelperImpl.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public OnionObject createOnionObject (List<byte[]> nodeList, byte[] payload) {
    System.out.println("createOnionObject");
    for (byte[] b : nodeList) {
        System.out.println(Tools.bytesToHex(b));
    }
    if (nodeList.size() > OnionObject.MAX_HOPS) {
        throw new RuntimeException("Too many nodes in nodeList");
    }

    int byteCount = OnionObject.MAX_HOPS * OnionObject.TOTAL_LENGTH;
    byte[] data = Tools.getRandomByte(byteCount);

    for (int i = 0; i < nodeList.size(); ++i) {
        byte[] temp = new byte[byteCount];
        byte[] dataToSign = new byte[OnionObject.DATA_LENGTH];
        System.arraycopy(data, 0, temp, OnionObject.DATA_LENGTH, data.length - OnionObject.DATA_LENGTH);

        ECKey key = ECKey.fromPublicOnly(nodeList.get(nodeList.size() - 1 - i));
        ECKey keyServer = CryptoTools.getEphemeralKey();
        ECDHKeySet keySet = ECDH.getSharedSecret(keyServer, key);

        if (i > 0) {
            byte[] nextNode = nodeList.get(nodeList.size() - i);
            System.arraycopy(nextNode, 0, dataToSign, 0, nextNode.length);
        }

        System.arraycopy(dataToSign, 0, temp, 0, dataToSign.length);

        byte[] encryptedTemp = CryptoTools.encryptAES_CTR(temp, keySet.encryptionKey, keySet.ivClient, 0);
        byte[] hmac = CryptoTools.getHMAC(dataToSign, keySet.hmacKey);

        data = new byte[OnionObject.MAX_HOPS * OnionObject.TOTAL_LENGTH];

        System.arraycopy(keyServer.getPubKey(), 0, data, 0, OnionObject.KEY_LENGTH);
        System.arraycopy(hmac, 0, data, OnionObject.KEY_LENGTH, hmac.length);
        System.arraycopy(encryptedTemp, 0, data,
                OnionObject.KEY_LENGTH + OnionObject.HMAC_LENGTH, encryptedTemp.length - OnionObject.KEY_LENGTH - OnionObject.HMAC_LENGTH);

    }

    return new OnionObject(data);
}
 
Example 18
Source File: Identity.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
public String decryptDataFromIPFS(String encryptedData) {
  int headerLength = 21;

  byte[] payload = NumericUtil.hexToBytes(encryptedData);

  byte version = payload[0];
  if (version != 0x03) {
    throw new TokenException(Messages.UNSUPPORT_ENCRYPTION_DATA_VERSION);
  }
  int srcPos = 1;
  byte[] toSign = new byte[headerLength + 32];
  System.arraycopy(payload, 0, toSign, 0, headerLength);

  byte[] timestamp = new byte[4];
  System.arraycopy(payload, srcPos, timestamp, 0, 4);
  srcPos += 4;

  byte[] encryptionKey = NumericUtil.hexToBytes(this.keystore.getEncKey());
  byte[] iv = new byte[16];
  System.arraycopy(payload, srcPos, iv, 0, 16);
  srcPos += 16;
  VarInt ciphertextLength = new VarInt(payload, srcPos);
  srcPos += ciphertextLength.getSizeInBytes();
  byte[] ciphertext = new byte[(int) ciphertextLength.value];
  System.arraycopy(payload, srcPos, ciphertext, 0, (int) ciphertextLength.value);
  System.arraycopy(Hash.merkleHash(ciphertext), 0, toSign, headerLength, 32);
  srcPos += ciphertextLength.value;
  byte[] encKey = Arrays.copyOf(encryptionKey, 16);
  String content = new String(AES.decryptByCBC(ciphertext, encKey, iv), Charset.forName("UTF-8"));

  byte[] signature = new byte[65];
  System.arraycopy(payload, srcPos, signature, 0, 65);
  try {
    BigInteger pubKey = EthereumSign.ecRecover(NumericUtil.bytesToHex(toSign), NumericUtil.bytesToHex(signature));
    ECKey ecKey = ECKey.fromPublicOnly(ByteUtil.concat(new byte[]{0x04}, NumericUtil.bigIntegerToBytesWithZeroPadded(pubKey, 64)));
    String recoverIpfsID = new Multihash(Multihash.Type.sha2_256, Hash.sha256(ecKey.getPubKey())).toBase58();

    if (!this.keystore.getIpfsId().equals(recoverIpfsID)) {
      throw new TokenException(Messages.INVALID_ENCRYPTION_DATA_SIGNATURE);
    }

  } catch (SignatureException e) {
    throw new TokenException(Messages.INVALID_ENCRYPTION_DATA_SIGNATURE);
  }
  return content;
}
 
Example 19
Source File: PreUtils.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static String ECDH(String pub, String priv) {
    ECKey pubKey = ECKey.fromPublicOnly(HexUtil.fromHexString(pub));
    ECKey privKey = ECKey.fromPrivate(HexUtil.fromHexString(priv));

    return HexUtil.toHexString(pubKey.getPubKeyPoint().multiply(privKey.getPrivKey()).getEncoded());
}
 
Example 20
Source File: PreUtils.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 3 votes vote down vote up
public static EncryptKey GenerateEncryptKey(byte[] pubOwner) {
    ECKey pubOwnerKey = ECKey.fromPublicOnly(pubOwner);

    ECKey priv_r = ECKey.fromPrivate(TransactionUtil.generatorPrivateKey());

    ECKey priv_u = ECKey.fromPrivate(TransactionUtil.generatorPrivateKey());

    BigInteger sum;
    sum = priv_r.getPrivKey().add(priv_u.getPrivKey()).mod(baseN);

    byte[] shareKey = pubOwnerKey.getPubKeyPoint().multiply(sum).getEncoded();

    byte[] enKey = KDF(shareKey, encKeyLength);
    return new EncryptKey(enKey, priv_r.getPublicKeyAsHex(), priv_u.getPublicKeyAsHex());
}