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

The following examples show how to use org.bitcoinj.core.ECKey#getPubKey() . 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
public void signAccountAgeWitness(Coin tradeAmount,
                                  AccountAgeWitness accountAgeWitness,
                                  ECKey key,
                                  PublicKey peersPubKey) {
    if (isSignedAccountAgeWitness(accountAgeWitness)) {
        log.warn("Arbitrator trying to sign already signed accountagewitness {}", accountAgeWitness.toString());
        return;
    }

    String accountAgeWitnessHashAsHex = Utilities.encodeToHex(accountAgeWitness.getHash());
    String signatureBase64 = key.signMessage(accountAgeWitnessHashAsHex);
    SignedWitness signedWitness = new SignedWitness(SignedWitness.VerificationMethod.ARBITRATOR,
            accountAgeWitness.getHash(),
            signatureBase64.getBytes(Charsets.UTF_8),
            key.getPubKey(),
            peersPubKey.getEncoded(),
            new Date().getTime(),
            tradeAmount.value);
    publishSignedWitness(signedWitness);
    log.info("Arbitrator signed witness {}", signedWitness.toString());
}
 
Example 2
Source File: EOSWalletTest.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePrvPubKey() {

  byte[] prvWIF = Base58.decode(WIF);
  // have omitted the checksum verification
  prvWIF = Arrays.copyOfRange(prvWIF, 1, prvWIF.length - 4);

  // use the privateKey to calculate the compressed public key directly
  ECKey ecKey = ECKey.fromPrivate(new BigInteger(1, prvWIF));
  byte[] pubKeyData = ecKey.getPubKey();
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(pubKeyData, 0, pubKeyData.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);

  pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
  String eosPK = "EOS" + Base58.encode(pubKeyData);
  Assert.assertEquals(PUBLIC_KEY, eosPK);
}
 
Example 3
Source File: AuthenticationProcessorImpl.java    From thundernetwork with GNU Affero General Public License v3.0 6 votes vote down vote up
public AuthenticationMessage getAuthenticationMessage () {
    try {
        ECKey keyServer = nodeServer.pubKeyServer;
        ECKey keyClient = node.ephemeralKeyClient;

        byte[] data = new byte[keyServer.getPubKey().length + keyClient.getPubKey().length];
        System.arraycopy(keyServer.getPubKey(), 0, data, 0, keyServer.getPubKey().length);
        System.arraycopy(keyClient.getPubKey(), 0, data, keyServer.getPubKey().length, keyClient.getPubKey().length);

        byte[] pubkeyServer = keyServer.getPubKey();
        byte[] signature = CryptoTools.createSignature(keyServer, data);

        return messageFactory.getAuthenticationMessage(pubkeyServer, signature);

    } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: ECDH.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
    try {

        ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
        ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                .getYCoord().toBigInteger()), ecParameters);

        ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
        ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

        JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
        JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

        KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
        aKeyAgree.init(ecPrivKey);
        aKeyAgree.doPhase(ecPubKey, true);

        return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: AuthenticationProcessorImpl.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
public AuthenticationMessage getAuthenticationMessage () {
    try {
        ECKey keyServer = serverObject.pubKeyServer;
        ECKey keyClient = node.ephemeralKeyClient;

        byte[] data = new byte[keyServer.getPubKey().length + keyClient.getPubKey().length];
        System.arraycopy(keyServer.getPubKey(), 0, data, 0, keyServer.getPubKey().length);
        System.arraycopy(keyClient.getPubKey(), 0, data, keyServer.getPubKey().length, keyClient.getPubKey().length);

        byte[] pubkeyServer = keyServer.getPubKey();
        byte[] signature = CryptoTools.createSignature(keyServer, data);

        return messageFactory.getAuthenticationMessage(pubkeyServer, signature);

    } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: SignedWitnessServiceTest.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testIsValidAccountAgeWitnessLongLoop() throws Exception {
    AccountAgeWitness aew = null;
    KeyPair signerKeyPair;
    KeyPair signedKeyPair = Sig.generateKeyPair();
    int iterations = 1002;
    for (int i = 0; i < iterations; i++) {
        byte[] accountDataHash = org.bitcoinj.core.Utils.sha256hash160(String.valueOf(i).getBytes(Charsets.UTF_8));
        long accountCreationTime = getTodayMinusNDays((iterations - i) * (SignedWitnessService.SIGNER_AGE_DAYS + 1));
        aew = new AccountAgeWitness(accountDataHash, accountCreationTime);
        String accountDataHashAsHexString = Utilities.encodeToHex(accountDataHash);
        byte[] signature;
        byte[] signerPubKey;
        if (i == 0) {
            // use arbitrator key
            ECKey arbitratorKey = new ECKey();
            signedKeyPair = Sig.generateKeyPair();
            String signature1String = arbitratorKey.signMessage(accountDataHashAsHexString);
            signature = signature1String.getBytes(Charsets.UTF_8);
            signerPubKey = arbitratorKey.getPubKey();
        } else {
            signerKeyPair = signedKeyPair;
            signedKeyPair = Sig.generateKeyPair();
            signature = Sig.sign(signedKeyPair.getPrivate(), accountDataHashAsHexString.getBytes(Charsets.UTF_8));
            signerPubKey = Sig.getPublicKeyBytes(signerKeyPair.getPublic());
        }
        byte[] witnessOwnerPubKey = Sig.getPublicKeyBytes(signedKeyPair.getPublic());
        long date = getTodayMinusNDays((iterations - i) * (SignedWitnessService.SIGNER_AGE_DAYS + 1));
        SignedWitness sw = new SignedWitness(i == 0 ? ARBITRATOR : TRADE, accountDataHash, signature, signerPubKey, witnessOwnerPubKey, date, tradeAmount1);
        signedWitnessService.addToMap(sw);
    }
    assertFalse(signedWitnessService.isSignerAccountAgeWitness(aew));
}
 
Example 7
Source File: SignedWitnessServiceTest.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    AppendOnlyDataStoreService appendOnlyDataStoreService = mock(AppendOnlyDataStoreService.class);
    ArbitratorManager arbitratorManager = mock(ArbitratorManager.class);
    when(arbitratorManager.isPublicKeyInList(any())).thenReturn(true);
    keyRing = mock(KeyRing.class);
    p2pService = mock(P2PService.class);
    filterManager = mock(FilterManager.class);
    signedWitnessService = new SignedWitnessService(keyRing, p2pService, arbitratorManager, null, appendOnlyDataStoreService, null, filterManager);
    account1DataHash = org.bitcoinj.core.Utils.sha256hash160(new byte[]{1});
    account2DataHash = org.bitcoinj.core.Utils.sha256hash160(new byte[]{2});
    account3DataHash = org.bitcoinj.core.Utils.sha256hash160(new byte[]{3});
    long account1CreationTime = getTodayMinusNDays(SIGN_AGE_1 + 1);
    long account2CreationTime = getTodayMinusNDays(SIGN_AGE_2 + 1);
    long account3CreationTime = getTodayMinusNDays(SIGN_AGE_3 + 1);
    aew1 = new AccountAgeWitness(account1DataHash, account1CreationTime);
    aew2 = new AccountAgeWitness(account2DataHash, account2CreationTime);
    aew3 = new AccountAgeWitness(account3DataHash, account3CreationTime);
    arbitrator1Key = new ECKey();
    peer1KeyPair = Sig.generateKeyPair();
    peer2KeyPair = Sig.generateKeyPair();
    peer3KeyPair = Sig.generateKeyPair();
    signature1 = arbitrator1Key.signMessage(Utilities.encodeToHex(account1DataHash)).getBytes(Charsets.UTF_8);
    signature2 = Sig.sign(peer1KeyPair.getPrivate(), Utilities.encodeToHex(account2DataHash).getBytes(Charsets.UTF_8));
    signature3 = Sig.sign(peer2KeyPair.getPrivate(), Utilities.encodeToHex(account3DataHash).getBytes(Charsets.UTF_8));
    date1 = getTodayMinusNDays(SIGN_AGE_1);
    date2 = getTodayMinusNDays(SIGN_AGE_2);
    date3 = getTodayMinusNDays(SIGN_AGE_3);
    signer1PubKey = arbitrator1Key.getPubKey();
    signer2PubKey = Sig.getPublicKeyBytes(peer1KeyPair.getPublic());
    signer3PubKey = Sig.getPublicKeyBytes(peer2KeyPair.getPublic());
    witnessOwner1PubKey = Sig.getPublicKeyBytes(peer1KeyPair.getPublic());
    witnessOwner2PubKey = Sig.getPublicKeyBytes(peer2KeyPair.getPublic());
    witnessOwner3PubKey = Sig.getPublicKeyBytes(peer3KeyPair.getPublic());
    tradeAmount1 = 1000;
    tradeAmount2 = 1001;
    tradeAmount3 = 1001;
}
 
Example 8
Source File: ECDH.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
        try {

            Security.addProvider(new BouncyCastleProvider());
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "SunEC");
            parameters.init(new ECGenParameterSpec("secp256k1"));
            ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
            ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
            ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                    .getYCoord().toBigInteger()), ecParameters);

            KeyFactory kf = KeyFactory.getInstance("EC");
            ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
            ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

            JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
            JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

            new ECKey().getKeyCrypter();

            KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");

            aKeyAgree.init(ecPrivKey);
            aKeyAgree.doPhase(ecPubKey, true);

            return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//		MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
//
//		return hash.digest();
    }
 
Example 9
Source File: LNPaymentDBHandlerMock.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<Channel> getChannel (ECKey nodeKey) {
    List<Channel> list = new ArrayList<>();
    Channel c = getChannel(1);
    c.nodeKeyClient = nodeKey.getPubKey();
    list.add(c);
    return list;
}
 
Example 10
Source File: LNEstablishAMessage.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
public LNEstablishAMessage (ECKey channelKeyServer, Transaction anchor, RevocationHash revocationHash, long clientAmount, long
        serverAmount, int minConfirmationAnchor, Address address, int feePerByte, long csvDelay) {
    this.channelKeyServer = channelKeyServer.getPubKey();
    this.minConfirmationAnchor = minConfirmationAnchor;
    this.anchorTransaction = anchor.bitcoinSerialize();
    this.revocationHash = revocationHash;
    this.amountClient = clientAmount;
    this.amountServer = serverAmount;
    this.addressBytes = address.getHash160();
    this.feePerByte = feePerByte;
    this.csvDelay = csvDelay;
}
 
Example 11
Source File: Signature.java    From evt4j with MIT License 5 votes vote down vote up
/**
 * Recover public key from signature and original data byte[]. Note: one always
 * need to compare the public key recovered from signature match with whe
 * reference public key
 *
 * @param data      original data signed by the private key
 * @param signature signature from sign method
 * @return {@link PublicKey}
 */
@NotNull
@Contract("_, _ -> new")
public static PublicKey recoverPublicKey(byte[] data, @NotNull Signature signature) {
    Sha256Hash dataHash = Sha256Hash.wrap(data);

    ECKey k = ECKey.recoverFromSignature(signature.getRecId(), signature.get(), dataHash, true);
    if (k == null) {
        throw new PublicKeyRecoverFailureException();
    }

    return new PublicKey(k.getPubKey());
}
 
Example 12
Source File: EOSKey.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public String getPublicKeyAsHex() {
  ECKey ecKey = ECKey.fromPrivate(bytes);
  byte[] pubKeyData = ecKey.getPubKey();
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(pubKeyData, 0, pubKeyData.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);

  pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
  return "EOS" + Base58.encode(pubKeyData);
}
 
Example 13
Source File: Secp256k1Context.java    From sawtooth-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public final PublicKey getPublicKey(final PrivateKey privateKey) {
  ECKey privKey = ECKey.fromPrivate(privateKey.getBytes());
  byte[] publicKey = privKey.getPubKey();
  return new Secp256k1PublicKey(publicKey);
}
 
Example 14
Source File: EthereumAddressCreator.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
private String fromECKey(ECKey key) {
  byte[] pubKeyBytes = key.getPubKey();
  return publicKeyToAddress(Arrays.copyOfRange(pubKeyBytes, 1, pubKeyBytes.length));
}
 
Example 15
Source File: ScriptBuilder.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a scriptSig that can redeem a P2PKH output.
 * If given signature is null, incomplete scriptSig will be created with OP_0 instead of signature
 */
public static Script createInputScript(@Nullable TransactionSignature signature, ECKey pubKey) {
    byte[] pubkeyBytes = pubKey.getPubKey();
    byte[] sigBytes = signature != null ? signature.encodeToBitcoin() : new byte[]{};
    return new ScriptBuilder().data(sigBytes).data(pubkeyBytes).build();
}
 
Example 16
Source File: Secp256k1ContextTest.java    From sawtooth-sdk-java with Apache License 2.0 3 votes vote down vote up
@Test
public void testPublicPrivateKey() {
  Secp256k1Context context = new Secp256k1Context();

  PrivateKey privateKey = Secp256k1PrivateKey.fromHex(Utils.HEX.encode(BigInteger.TEN.toByteArray()));

  ECKey ecKey = ECKey.fromPrivate(privateKey.getBytes(), true);
  PublicKey publicKeyFromECKey = new Secp256k1PublicKey(ecKey.getPubKey());

  PublicKey publicKey = context.getPublicKey(privateKey);

  Assert.assertEquals(publicKey.hex(), publicKeyFromECKey.hex());

}
 
Example 17
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * 
 * @description 通过私钥生成公钥
 * @param privateKey
 *            私钥
 * @return 公钥
 *
 */
public static String getHexPubKeyFromPrivKey(String privateKey) {
	ECKey eckey = ECKey.fromPrivate(HexUtil.fromHexString(privateKey));
	byte[] pubKey = eckey.getPubKey();
	String pubKeyStr = HexUtil.toHexString(pubKey);
	return pubKeyStr;
}