org.spongycastle.crypto.params.ECDomainParameters Java Examples

The following examples show how to use org.spongycastle.crypto.params.ECDomainParameters. 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: BTCUtils.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public static boolean verify(byte[] publicKey, byte[] signature, byte[] msg) {
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters EC_PARAMS = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    synchronized (EC_PARAMS) {
        boolean valid;
        ECDSASigner signerVer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        try {
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(EC_PARAMS.getCurve().decodePoint(publicKey), EC_PARAMS);
            signerVer.init(false, pubKey);
            ASN1InputStream derSigStream = new ASN1InputStream(signature);
            DLSequence seq = (DLSequence) derSigStream.readObject();
            BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
            BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
            derSigStream.close();
            valid = signerVer.verifySignature(msg, r, s);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return valid;
    }
}
 
Example #2
Source File: EOSECDSASigner.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
/**
 * return true if the value r and s represent a DSA signature for
 * the passed in message (for standard DSA the message should be
 * a SHA-1 hash of the real message to be verified).
 */
public boolean verifySignature(
    byte[] message,
    BigInteger r,
    BigInteger s) {
  ECDomainParameters ec = key.getParameters();
  BigInteger n = ec.getN();
  BigInteger e = calculateE(n, message);

  // r in the range [1,n-1]
  if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) {
    return false;
  }

  // s in the range [1,n-1]
  if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) {
    return false;
  }

  BigInteger c = s.modInverse(n);

  BigInteger u1 = e.multiply(c).mod(n);
  BigInteger u2 = r.multiply(c).mod(n);

  ECPoint G = ec.getG();
  ECPoint Q = ((ECPublicKeyParameters) key).getQ();

  ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2).normalize();

  // components must be bogus.
  if (point.isInfinity()) {
    return false;
  }

  BigInteger v = point.getAffineXCoord().toBigInteger().mod(n);

  return v.equals(r);
}
 
Example #3
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * UAF_ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW 0x01
 * An ECDSA signature on the NIST secp256r1 curve which MUST have raw R and S buffers, encoded in big-endian order.
 * I.e. [R (32 bytes), S (32 bytes)]
 * 
 * @param priv - Private key
 * @param input - Data to sign 
 * @return BigInteger[] - [R,S]
 */
public static BigInteger[] signAndFromatToRS(PrivateKey priv, byte[] input) {
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	if (priv == null)
		throw new IllegalStateException(
				"This ECKey does not have the private key necessary for signing.");
	ECDSASigner signer = new ECDSASigner();
	ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
			((ECPrivateKey) priv).getS(), ecParams);
	signer.init(true, privKey);
	BigInteger[] sigs = signer.generateSignature(input);
	return sigs;
}
 
Example #4
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static boolean verify(byte[] pub, byte[] dataForSigning,
		BigInteger[] rs) {
	ECDSASigner signer = new ECDSASigner();
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	ECPublicKeyParameters pubKeyParams = new ECPublicKeyParameters(ecParams
			.getCurve().decodePoint(pub), ecParams);
	signer.init(false, pubKeyParams);

	return signer.verifySignature(dataForSigning, rs[0].abs(), rs[1].abs());
}
 
Example #5
Source File: SignUtils.java    From java-client with Apache License 2.0 5 votes vote down vote up
private static BigInteger ensureCanonical(BigInteger s, BigInteger HALF_CURVE_ORDER, ECDomainParameters CURVE) {
    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.
        s = CURVE.getN().subtract(s);
    }
    return s;
}
 
Example #6
Source File: EOSECDSASigner.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
/**
 * generate a signature for the given message using the key we were
 * initialised with. For conventional DSA the message should be a SHA-1
 * hash of the message of interest.
 *
 * @param message the message that will be verified later.
 */
public BigInteger[] generateSignature(
    byte[] message) {
  ECDomainParameters ec = key.getParameters();
  BigInteger n = ec.getN();
  BigInteger e = calculateE(n, message);
  BigInteger d = ((ECPrivateKeyParameters) key).getD();

  int nonce = 1;
  BigInteger r, s;
  while (true) {

    kCalculator.init(n, d, message);
    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.3.2
    do // generate s
    {
      BigInteger k = BigInteger.ZERO;
      do // generate r
      {
        k = kCalculator.nextK();
        for (int i = 0; i < nonce; i++) {
          k = kCalculator.nextK();
        }

        ECPoint p = basePointMultiplier.multiply(ec.getG(), k).normalize();

        // 5.3.3
        r = p.getAffineXCoord().toBigInteger().mod(n);
      }
      while (r.equals(ZERO));

    // Compute s = (k^-1)*(h + Kx*privkey)
      s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
    }
    while (s.equals(ZERO));

    byte[] der = new ECKey.ECDSASignature(r, s).toCanonicalised().encodeToDER();

    int lenR = der[3];
    int lenS = der[5 + lenR];
    if (lenR == 32 && lenS == 32) {
      break;
    }
    nonce++;
  }

  return new BigInteger[]{r, s};
}
 
Example #7
Source File: SignUtils.java    From java-client with Apache License 2.0 4 votes vote down vote up
private static void sign(IntermediaryTransaction unsignedTransaction, List<String> privateKeys, boolean isHex, boolean addPubKey) {
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters CURVE = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    BigInteger HALF_CURVE_ORDER = params.getN().shiftRight(1);

    for (int i = 0; i < unsignedTransaction.getTosign().size(); i++) {
        String toSign = unsignedTransaction.getTosign().get(i);

        String privateKey = privateKeys.get(i);
        byte[] bytes;
        boolean compressed = false;
        if (isHex) {
            // nothing to do
            bytes = Hex.decode(privateKey);
        } else {
            bytes = getBytesFromBase58Key(privateKey);
        }
        if (bytes.length == 33 && bytes[32] == 1) {
            compressed = true;
            bytes = Arrays.copyOf(bytes, 32);  // Chop off the additional marker byte.
        }
        BigInteger privKeyB = new BigInteger(1, bytes);

        ECPoint point = CURVE.getG().multiply(privKeyB);
        if (compressed) {
            point = new ECPoint.Fp(CURVE.getCurve(), point.getX(), point.getY(), true);
        }

        byte[] publicKey = point.getEncoded();

        ECDSASigner signer = new ECDSASigner();
        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privKeyB, CURVE);
        signer.init(true, privKey);


        if (addPubKey) {
            logger.info("Pushing Pub key for input");
            unsignedTransaction.addPubKeys(bytesToHexString(publicKey));
        }
        BigInteger[] components = signer.generateSignature(Hex.decode(toSign));
        BigInteger r = components[0];
        BigInteger s = components[1];
        // ensure Canonical
        s = ensureCanonical(s, HALF_CURVE_ORDER, CURVE);
        String signedString = bytesToHexString(toDER(r, s));
        unsignedTransaction.addSignature(signedString);
    }
}