congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
ECKey$ECDSASignature
Code IndexAdd Tabnine to your IDE (free)

How to use
ECKey$ECDSASignature
in
io.yggdrash.common.crypto

Best Java code snippets using io.yggdrash.common.crypto.ECKey$ECDSASignature (Showing top 20 results out of 315)

origin: yggdrash/yggdrash

  signer.init(true, privKeyParams);
  BigInteger[] components = signer.generateSignature(input);
  return new ECDSASignature(components[0], components[1]).toCanonicalised();
} else {
  try {
    ecSig.update(input);
    final byte[] derSignature = ecSig.sign();
    return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
  } catch (SignatureException | InvalidKeyException ex) {
    throw new RuntimeException("ECKey signing error", ex);
origin: yggdrash/yggdrash

/**
 * Given a piece of text and a message signature encoded in base64, returns an ECKey
 * containing the public key that was used to sign it. This can then be compared to the expected public key to
 * determine if the signature was correct.
 *
 * @param messageHash     a piece of human readable text that was signed
 * @param signatureBase64 The Ethereum-format message signature in base64
 * @return -
 * @throws SignatureException If the public key could not be recovered or if there was a signature format error.
 */
public static byte[] signatureToKeyBytes(byte[] messageHash, String signatureBase64) throws SignatureException {
  byte[] signatureEncoded;
  try {
    signatureEncoded = Base64.decode(signatureBase64);
  } catch (RuntimeException e) {
    // This is what you get back from Bouncy Castle if base64 doesn't decode :(
    throw new SignatureException("Could not decode base64", e);
  }
  // Parse the signature bytes into r/s and the selector value.
  if (signatureEncoded.length < 65) {
    throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length);
  }
  return signatureToKeyBytes(
      messageHash,
      ECDSASignature.fromComponents(
          Arrays.copyOfRange(signatureEncoded, 1, 33),
          Arrays.copyOfRange(signatureEncoded, 33, 65),
          (byte) (signatureEncoded[0] & 0xFF)));
}
origin: yggdrash/yggdrash

@Test
@SuppressWarnings("UnstableApiUsage")
public void testSValue() throws Exception {
  // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
  // issue that can allow someone to change a transaction [hash] without invalidating the signature.
  final int ITERATIONS = 10;
  ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
  List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
  final ECKey key = new ECKey();
  for (byte i = 0; i < ITERATIONS; i++) {
    final byte[] hash = HashUtil.sha3(new byte[] {i});
    sigFutures.add(executor.submit(() -> key.doSign(hash)));
  }
  List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
  for (ECKey.ECDSASignature signature : sigs) {
    assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
  }
  final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
  assertEquals(sigs.get(0), duplicate);
  assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
origin: yggdrash/yggdrash

@Test
public void testGetAddressWithSig()
    throws IOException, InvalidCipherTextException, SignatureException {
  Account account = new Account();
  log.debug("Account: " + account.toString());
  log.debug("Account.address: " + Hex.toHexString(account.getAddress()));
  log.debug("Account.pubKey: " + Hex.toHexString(account.getKey().getPubKey()));
  Wallet wallet = new Wallet(account.getKey(), "tmp/path", "nodePri.key", "Aa1234567890!");
  log.debug("Wallet: " + wallet.toString());
  log.debug("Wallet.address: " + Hex.toHexString(wallet.getAddress()));
  log.debug("Wallet.pubKey: " + Hex.toHexString(wallet.getPubicKey()));
  TransactionHusk txHusk1 = createTx(wallet);
  log.debug("Test Transaction1: " + txHusk1.toString());
  log.debug("Test Transaction1 Address: " + txHusk1.getAddress());
  assertThat(txHusk1.verify()).isTrue();
  assertThat(wallet.getAddress()).isEqualTo(account.getAddress());
  assertThat(wallet.getAddress()).isEqualTo(txHusk1.getAddress().getBytes());
  byte[] hashedRawData = txHusk1.getHashForSigning().getBytes();
  log.debug("hashedRawData: " + Hex.toHexString(hashedRawData));
  byte[] signatureBin = txHusk1.getInstance().getSignature().toByteArray();
  log.debug("signatureBin: " + Hex.toHexString(signatureBin));
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(signatureBin);
  ECKey key = ECKey.signatureToKey(hashedRawData, ecdsaSignature);
  byte[] address = key.getAddress();
  byte[] pubKey = key.getPubKey();
  log.debug("address: " + Hex.toHexString(address));
  log.debug("pubKey: " + Hex.toHexString(pubKey));
  assertThat(account.getAddress()).isEqualTo(address);
  assertThat(account.getKey().getPubKey()).isEqualTo(pubKey);
}
origin: yggdrash/yggdrash

/**
 * Verify the signature with public key
 *
 * @param data signed data
 * @param signature  signature
 * @param hashed whether hashed data or not
 * @param pubKey public key for verifying
 * @return verification result
 */
public static boolean verify(byte[] data, byte[] signature, boolean hashed, byte[] pubKey) {
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(signature);
  byte[] hashedData = hashed ? data : HashUtil.sha3(data);
  ECKey ecKeyPub;
  try {
    ecKeyPub = ECKey.signatureToKey(hashedData, ecdsaSignature);
  } catch (SignatureException e) {
    logger.debug("Invalid signature" + e.getMessage());
    return false;
  }
  if (pubKey != null && !Arrays.equals(ecKeyPub.getPubKey(), pubKey)) {
    logger.debug("Invalid signature");
    return false;
  }
  return ecKeyPub.verify(hashedData, ecdsaSignature);
}
origin: yggdrash/yggdrash

/**
 * Given a piece of text and a message signature encoded in binary, returns an ECKey
 * containing the public key that was used to sign it. This can then be compared to the expected public key to
 * determine if the signature was correct.
 *
 * @param messageHash      a piece of human readable text that was signed
 * @param signatureEncoded The signature message in binary
 * @return -
 * @throws SignatureException If the public key could not be recovered or if there was a signature format error.
 */
public static byte[] signatureToKeyBytes(byte[] messageHash, byte[] signatureEncoded) throws SignatureException {
  // Parse the signature bytes into r/s and the selector value.
  if (signatureEncoded.length < 65) {
    throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length);
  }
  return signatureToKeyBytes(
      messageHash,
      ECDSASignature.fromComponents(
          Arrays.copyOfRange(signatureEncoded, 1, 33),
          Arrays.copyOfRange(signatureEncoded, 33, 65),
          (byte) (signatureEncoded[0] & 0xFF)));
}
origin: yggdrash/yggdrash

/**
 * Will automatically adjust the S component to be less than or equal to half the curve order, if necessary.
 * This is required because for every signature (r,s) the signature (r, -s (mod N)) is a valid signature of
 * the same message. However, we dislike the ability to modify the bits of a Ethereum transaction after it's
 * been signed, as that violates various assumed invariants. Thus in future only one of those forms will be
 * considered legal and the other will be banned.
 *
 * @return -
 */
public ECDSASignature toCanonicalised() {
  if (s.compareTo(HALF_CURVE_ORDER) > 0) {
    // The order of the curve is the number of valid points that exist on that curve. If S is in the upper
    // half of the number of valid points, then bring it back to the lower half. Otherwise, imagine that
    //    N = 10
    //    s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions.
    //    10 - 8 == 2, giving us always the latter solution, which is canonical.
    return new ECDSASignature(r, CURVE.getN().subtract(s));
  } else {
    return this;
  }
}
origin: yggdrash/yggdrash

public static ECDSASignature decodeFromDER(byte[] bytes) {
  try (ASN1InputStream decoder = new ASN1InputStream(bytes)) {
    DLSequence seq = (DLSequence) decoder.readObject();
    if (seq == null) {
      throw new RuntimeException("Reached past end of ASN.1 stream.");
    }
    ASN1Integer r, s;
    try {
      r = (ASN1Integer) seq.getObjectAt(0);
      s = (ASN1Integer) seq.getObjectAt(1);
    } catch (ClassCastException e) {
      throw new IllegalArgumentException(e);
    }
    // OpenSSL deviates from the DER spec by interpreting these values as unsigned, though they should not be
    // Thus, we always use the positive versions. See: http://r6.ca/blog/20111119T211504Z.html
    return new ECDSASignature(r.getPositiveValue(), s.getPositiveValue());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  // ignore
}
origin: yggdrash/yggdrash

/**
 * Verify a transaction.(data format & signing)
 *
 * @return true(success), false(fail)
 */
public boolean verify() {
  if (!this.verifyData()) {
    return false;
  }
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(this.signature);
  byte[] hashedHeader = this.header.getHashForSigning();
  ECKey ecKeyPub;
  try {
    ecKeyPub = ECKey.signatureToKey(hashedHeader, ecdsaSignature);
  } catch (SignatureException e) {
    throw new InvalidSignatureException(e);
  }
  return ecKeyPub.verify(hashedHeader, ecdsaSignature);
}
origin: yggdrash/yggdrash

@Test
public void testVerifySignature2() throws SignatureException {
  BigInteger r = new BigInteger("c52c114d4f5a3ba904a9b3036e5e118fe0dbb987fe3955da20f2cd8f6c21ab9c", 16);
  BigInteger s = new BigInteger("6ba4c2874299a55ad947dbc98a25ee895aabf6b625c26c435e84bfd70edf2f69", 16);
  ECDSASignature sig = ECDSASignature.fromComponents(r.toByteArray(), s.toByteArray(), (byte) 0x1b);
  byte[] rawtx = Hex.decode("f82804881bc16d674ec8000094cd2a3d9f938e13cd947ec05abc7fe734df8dd8268609184e72a0006480");
  byte[] rawHash = HashUtil.sha3(rawtx);
  byte[] address = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826");
  ECKey key = ECKey.signatureToKey(rawHash, sig);
  assertEquals(key, ECKey.signatureToKey(rawHash, sig.toBase64()));
  assertEquals(key, ECKey.recoverFromSignature(0, sig, rawHash));
  assertArrayEquals(key.getPubKey(), ECKey.recoverPubBytesFromSignature(0, sig, rawHash));
  assertArrayEquals(address, key.getAddress());
  assertArrayEquals(address, ECKey.signatureToAddress(rawHash, sig));
  assertArrayEquals(address, ECKey.signatureToAddress(rawHash, sig.toBase64()));
  assertArrayEquals(address, ECKey.recoverAddressFromSignature(0, sig, rawHash));
  assertTrue(key.verify(rawHash, sig));
}
origin: yggdrash/yggdrash

public boolean validateComponents() {
  return validateComponents(r, s, v);
}
origin: yggdrash/yggdrash

@Test
public void testVerifySignature_Static() throws SignatureException {
  byte[] messageHash = Hex.decode("92e0d4290bba01aa0abbb4705360c751af13fdb1131b8f6f1e632c4621adac75");
  byte[] signature = Hex.decode("1cca588a8eb84d5bf6741bc6e0ccfbe1fdb05b6c624b5fe72199fa1f2e501f876c5b5f11863323a998b79a0d27714fcc8825cf357903e863396f2e2e281220de31");
  // get public key with messageHash, ECDSASignature
  ECKey.ECDSASignature sig = new ECKey.ECDSASignature(signature);
  ECKey keyFromSig = ECKey.signatureToKey(messageHash, sig);
  log.debug("address=" + Hex.toHexString(keyFromSig.getAddress()));
  byte[] pubKeyFromSig = keyFromSig.getPubKey();
  log.debug("pubKey=" + Hex.toHexString(pubKeyFromSig));
  assertArrayEquals(pubKeyFromSig, Hex.decode("0493fe448d38c77c212cce10c07ed37984c59bedac51219b70847429153063cfae0d2f42ba394ffe9d5d2d11b0c0f400ac04997c584c0ef6f2041cf20f8c2c446b"));
  // verify the sign message
  assertTrue(keyFromSig.verify(messageHash, sig));
}
origin: yggdrash/yggdrash

public boolean verify() {
  if (!this.verifyData()) {
    return false;
  }
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(this.signature);
  byte[] hashedHeader = this.header.getHashForSigning();
  ECKey ecKeyPub;
  try {
    ecKeyPub = ECKey.signatureToKey(hashedHeader, ecdsaSignature);
  } catch (SignatureException e) {
    throw new InvalidSignatureException(e);
  }
  return ecKeyPub.verify(hashedHeader, ecdsaSignature);
}
origin: yggdrash/yggdrash

public String toHex() {
  return Hex.toHexString(toByteArray());
}
origin: yggdrash/yggdrash

public boolean verify() {
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(signature.getBytes());
  try {
    ECKey ecKeyPub = ECKey.signatureToKey(rawForSign.getBytes(), ecdsaSignature);
    if (ecKeyPub.verify(rawForSign.getBytes(), ecdsaSignature)) {
      return new Address(ecKeyPub.getAddress()).equals(owner);
    } else {
      return false;
    }
  } catch (SignatureException e) {
    throw new InvalidSignatureException(e);
  }
}
origin: yggdrash/yggdrash

/**
 * Verify the signature with hashed data.
 *
 * @param hashedData hashed Data
 * @param signature  signature
 * @return verification result
 */
boolean verifyHashedData(byte[] hashedData, byte[] signature) {
  ECKey.ECDSASignature sig = new ECKey.ECDSASignature(signature);
  return key.verify(hashedData, sig);
}
origin: yggdrash/yggdrash

/**
 * @param r -
 * @param s -
 * @param v -
 * @return -
 */
public static ECDSASignature fromComponents(byte[] r, byte[] s, byte v) {
  ECDSASignature signature = fromComponents(r, s);
  signature.v = v;
  return signature;
}
origin: yggdrash/yggdrash

/**
 * Sign the hashed data by sha3().
 *
 * @param hashedData hashed data
 * @return signature as byte[65]
 */
public byte[] signHashedData(byte[] hashedData) {
  return key.sign(hashedData).toBinary();
}
origin: yggdrash/yggdrash

/**
 * Sign the plain data.
 *
 * @param data plain data
 * @return signature as byte[65]
 */
public byte[] sign(byte[] data) {
  return key.sign(HashUtil.sha3(data)).toBinary();
}
origin: yggdrash/yggdrash

public byte[] getPubKey() {
  ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(this.signature);
  ECKey ecKeyPub = null;
  try {
    ecKeyPub = ECKey.signatureToKey(this.header.getHashForSigning(), ecdsaSignature);
  } catch (SignatureException e) {
    log.warn(e.getMessage());
    throw new InvalidSignatureException();
  }
  return ecKeyPub.getPubKey();
}
io.yggdrash.common.cryptoECKey$ECDSASignature

Javadoc

Groups the two components that make up a signature, and provides a way to encode to Base64 form, which is how ECDSA signatures are represented when embedded in other data structures in the Ethereum protocol. The raw components can be useful for doing further EC maths on them.

Most used methods

  • <init>
    Constructs a signature with the binary signature data
  • fromComponents
  • validateComponents
  • decodeFromDER
  • hashCode
  • toBase64
  • toBinary
    Get the signature as byte array [v + r + s].
  • toByteArray
  • toCanonicalised
    Will automatically adjust the S component to be less than or equal to half the curve order, if neces
  • toHex

Popular in Java

  • Start an intent from android
  • startActivity (Activity)
  • requestLocationUpdates (LocationManager)
  • putExtra (Intent)
  • GridBagLayout (java.awt)
    The GridBagLayout class is a flexible layout manager that aligns components vertically and horizonta
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • ArrayList (java.util)
    ArrayList is an implementation of List, backed by an array. All optional operations including adding
  • UUID (java.util)
    UUID is an immutable representation of a 128-bit universally unique identifier (UUID). There are mul
  • Vector (java.util)
    Vector is an implementation of List, backed by an array and synchronized. All optional operations in
  • Project (org.apache.tools.ant)
    Central representation of an Ant project. This class defines an Ant project with all of its targets,
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now