Java Code Examples for org.spongycastle.math.ec.ECPoint#Fp

The following examples show how to use org.spongycastle.math.ec.ECPoint#Fp . 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: ECKeySecp256k1.java    From aion with MIT License 4 votes vote down vote up
/**
 * Given the components of a signature and a selector value, recover and return the public key
 * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.
 *
 * <p>The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the
 * correct one. Because the key recovery operation yields multiple potential keys, the correct
 * key must either be stored alongside the signature, or you must be willing to try each recId
 * in turn until you find one that outputs the key you are expecting.
 *
 * <p>If this method returns null it means recovery was not possible and recId should be
 * iterated.
 *
 * <p>Given the above two points, a correct usage of this method is inside a for loop from 0 to
 * 3, and if the output is null OR a key that is not the one you expect, you try again with the
 * next recId.
 *
 * @param recId Which possible key to recover.
 * @param sig the R and S components of the signature, wrapped.
 * @param messageHash Hash of the data that was signed.
 * @return 65-byte encoded public key
 */
public byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) {
    check(recId >= 0, "recId must be positive");
    check(sig.r.signum() >= 0, "r must be positive");
    check(sig.s.signum() >= 0, "s must be positive");
    check(messageHash != null, "messageHash must not be null");
    // 1.0 For j from 0 to h (h == recId here and the loop is outside this
    // function)
    // 1.1 Let x = r + jn
    BigInteger n = CURVE.getN(); // Curve order.
    BigInteger i = BigInteger.valueOf((long) recId / 2);
    BigInteger x = sig.r.add(i.multiply(n));
    // 1.2. Convert the integer x to an octet string X of length mlen using
    // the conversion routine
    // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen =
    // ⌈m/8⌉.
    // 1.3. Convert the octet string (16 set binary digits)||X to an
    // elliptic curve point R using the
    // conversion routine specified in Section 2.3.4. If this conversion
    // routine outputs “invalid”, then
    // do another iteration of Step 1.
    //
    // More concisely, what these points mean is to use X as a compressed
    // public key.
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent
    // about the letter it uses for the
    // prime.
    if (x.compareTo(prime) >= 0) {
        // Cannot have point co-ordinates larger than this as everything
        // takes place modulo Q.
        return null;
    }
    // Compressed keys require you to know an extra bit of data about the
    // y-coord as there are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    // 1.4. If nR != point at infinity, then do another iteration of Step 1
    // (callers responsibility).
    if (!R.multiply(n).isInfinity()) {
        return null;
    }
    // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature
    // verification.
    BigInteger e = new BigInteger(1, messageHash);
    // 1.6. For k from 1 to 2 do the following. (loop is outside this
    // function via iterating recId)
    // 1.6.1. Compute a candidate public key as:
    // Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform this
    // into the following:
    // Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that z
    // + e = 0 (mod n). In the above equation
    // ** is point multiplication and + is point addition (the EC group
    // operator).
    //
    // We can find the additive inverse by subtracting e from zero then
    // taking the mod. For example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 =
    // 8.
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = sig.r.modInverse(n);
    BigInteger srInv = rInv.multiply(sig.s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q =
            (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
    return q.getEncoded(/* compressed */ false);
}
 
Example 2
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * <p>Given the components of a signature and a selector value, recover and return the public key
 * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p>
 *
 * <p> <p>The recId is an index from 0 to 3 which indicates which of the 4 possible allKeys is the
 * correct one. Because the key recovery operation yields multiple potential allKeys, the correct
 * key must either be stored alongside the signature, or you must be willing to try each recId in
 * turn until you find one that outputs the key you are expecting.</p>
 *
 * <p> <p>If this method returns null it means recovery was not possible and recId should be
 * iterated.</p>
 *
 * <p> <p>Given the above two points, a correct usage of this method is inside a for loop from 0
 * to 3, and if the output is null OR a key that is not the one you expect, you try again with the
 * next recId.</p>
 *
 * @param recId       Which possible key to recover.
 * @param sig         the R and S components of the signature, wrapped.
 * @param messageHash Hash of the data that was signed.
 * @return 65-byte encoded public key
 */
@Nullable
public static byte[] recoverPubBytesFromSignature(int recId,
                                                  ECDSASignature sig,
                                                  byte[] messageHash) {
    check(recId >= 0, "recId must be positive");
    check(sig.r.signum() >= 0, "r must be positive");
    check(sig.s.signum() >= 0, "s must be positive");
    check(messageHash != null, "messageHash must not be null");
    // 1.0 For j from 0 to h   (h == recId here and the loop is outside
    // this function)
    //   1.1 Let x = r + jn
    BigInteger n = CURVE.getN();  // Curve order.
    BigInteger i = BigInteger.valueOf((long) recId / 2);
    BigInteger x = sig.r.add(i.multiply(n));
    //   1.2. Convert the integer x to an octet string X of length mlen
    // using the conversion routine
    //        specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or
    // mlen = ⌈m/8⌉.
    //   1.3. Convert the octet string (16 set binary digits)||X to an
    // elliptic curve point R using the
    //        conversion routine specified in Section 2.3.4. If this
    // conversion routine outputs “invalid”, then
    //        do another iteration of Step 1.
    //
    // More concisely, what these points mean is to use X as a compressed
    // public key.
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ();  // Bouncy Castle is not consistent
    // about the letter it uses for the prime.
    if (x.compareTo(prime) >= 0) {
        // Cannot have point co-ordinates larger than this as everything
        // takes place modulo Q.
        return null;
    }
    // Compressed allKeys require you to know an extra bit of data about the
    // y-coord as there are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    //   1.4. If nR != point at infinity, then do another iteration of
    // Step 1 (callers responsibility).
    if (!R.multiply(n).isInfinity()) {
        return null;
    }
    //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature
    // verification.
    BigInteger e = new BigInteger(1, messageHash);
    //   1.6. For k from 1 to 2 do the following.   (loop is outside this
    // function via iterating recId)
    //   1.6.1. Compute a candidate public key as:
    //               Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform
    // this into the following:
    //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that
    // z + e = 0 (mod n). In the above equation
    // ** is point multiplication and + is point addition (the EC group
    // operator).
    //
    // We can find the additive inverse by subtracting e from zero then
    // taking the mod. For example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod
    // 11 = 8.
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = sig.r.modInverse(n);
    BigInteger srInv = rInv.multiply(sig.s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE
            .getG(), eInvrInv, R, srInv);
    return q.getEncoded(/* compressed */ false);
}
 
Example 3
Source File: EthECKeyPair.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[]
        messageHash) {
    check(recId >= 0, "recId must be positive");
    check(sig.r.signum() >= 0, "r must be positive");
    check(sig.s.signum() >= 0, "s must be positive");
    check(messageHash != null, "messageHash must not be null");
    // 1.0 For j from 0 to h   (h == recId here and the loop is outside this function)
    //   1.1 Let x = r + jn
    BigInteger n = CURVE.getN();  // Curve order.
    BigInteger i = BigInteger.valueOf((long) recId / 2);
    BigInteger x = sig.r.add(i.multiply(n));
    //   1.2. Convert the integer x to an octet string X of length mlen using the conversion
    // routine
    //        specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
    //   1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R
    // using the
    //        conversion routine specified in Section 2.3.4. If this conversion routine
    // outputs “invalid”, then
    //        do another iteration of Step 1.
    //
    // More concisely, what these points mean is to use X as a compressed public key.
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ();  // Bouncy Castle is not consistent about the letter it
    // uses for the prime.
    if (x.compareTo(prime) >= 0) {
        // Cannot have point co-ordinates larger than this as everything takes place modulo Q.
        return null;
    }
    // Compressed keys require you to know an extra bit of data about the y-coord as there
    // are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    //   1.4. If nR != point at infinity, then do another iteration of Step 1 (callers
    // responsibility).
    if (!R.multiply(n).isInfinity())
        return null;
    //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
    BigInteger e = new BigInteger(1, messageHash);
    //   1.6. For k from 1 to 2 do the following.   (loop is outside this function via
    // iterating recId)
    //   1.6.1. Compute a candidate public key as:
    //               Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
    //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
    // In the above equation
    // ** is point multiplication and + is point addition (the EC group operator).
    //
    // We can find the additive inverse by subtracting e from zero then taking the mod. For
    // example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = sig.r.modInverse(n);
    BigInteger srInv = rInv.multiply(sig.s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R,
            srInv);
    return q.getEncoded(/* compressed */ false);
}
 
Example 4
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Given the components of a signature and a selector value, recover and return the public key
 * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p> <p> <p>The
 * recId is an index from 0 to 3 which indicates which of the 4 possible allKeys is the correct
 * one. Because the key recovery operation yields multiple potential allKeys, the correct key must
 * either be stored alongside the signature, or you must be willing to try each recId in turn
 * until you find one that outputs the key you are expecting.</p> <p> <p>If this method returns
 * null it means recovery was not possible and recId should be iterated.</p> <p> <p>Given the
 * above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the
 * output is null OR a key that is not the one you expect, you try again with the next recId.</p>
 *
 * @param recId Which possible key to recover.
 * @param sig the R and S components of the signature, wrapped.
 * @param messageHash Hash of the data that was signed.
 * @return 65-byte encoded public key
 */
@Nullable
public static byte[] recoverPubBytesFromSignature(int recId,
    ECDSASignature sig,
    byte[] messageHash) {
  check(recId >= 0, "recId must be positive");
  check(sig.r.signum() >= 0, "r must be positive");
  check(sig.s.signum() >= 0, "s must be positive");
  check(messageHash != null, "messageHash must not be null");
  // 1.0 For j from 0 to h   (h == recId here and the loop is outside
  // this function)
  //   1.1 Let x = r + jn
  BigInteger n = CURVE.getN();  // Curve order.
  BigInteger i = BigInteger.valueOf((long) recId / 2);
  BigInteger x = sig.r.add(i.multiply(n));
  //   1.2. Convert the integer x to an octet string X of length mlen
  // using the conversion routine
  //        specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or
  // mlen = ⌈m/8⌉.
  //   1.3. Convert the octet string (16 set binary digits)||X to an
  // elliptic curve point R using the
  //        conversion routine specified in Section 2.3.4. If this
  // conversion routine outputs “invalid”, then
  //        do another iteration of Step 1.
  //
  // More concisely, what these points mean is to use X as a compressed
  // public key.
  ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
  BigInteger prime = curve.getQ();  // Bouncy Castle is not consistent
  // about the letter it uses for the prime.
  if (x.compareTo(prime) >= 0) {
    // Cannot have point co-ordinates larger than this as everything
    // takes place modulo Q.
    return null;
  }
  // Compressed allKeys require you to know an extra bit of data about the
  // y-coord as there are two possibilities.
  // So it's encoded in the recId.
  ECPoint R = decompressKey(x, (recId & 1) == 1);
  //   1.4. If nR != point at infinity, then do another iteration of
  // Step 1 (callers responsibility).
  if (!R.multiply(n).isInfinity()) {
    return null;
  }
  //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature
  // verification.
  BigInteger e = new BigInteger(1, messageHash);
  //   1.6. For k from 1 to 2 do the following.   (loop is outside this
  // function via iterating recId)
  //   1.6.1. Compute a candidate public key as:
  //               Q = mi(r) * (sR - eG)
  //
  // Where mi(x) is the modular multiplicative inverse. We transform
  // this into the following:
  //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
  // Where -e is the modular additive inverse of e, that is z such that
  // z + e = 0 (mod n). In the above equation
  // ** is point multiplication and + is point addition (the EC group
  // operator).
  //
  // We can find the additive inverse by subtracting e from zero then
  // taking the mod. For example the additive
  // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod
  // 11 = 8.
  BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
  BigInteger rInv = sig.r.modInverse(n);
  BigInteger srInv = rInv.multiply(sig.s).mod(n);
  BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
  ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE
      .getG(), eInvrInv, R, srInv);
  return q.getEncoded(/* compressed */ false);
}
 
Example 5
Source File: ECKey.java    From ethereumj with MIT License 4 votes vote down vote up
/**
 * <p>Given the components of a signature and a selector value, recover and return the public key
 * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p>
 *
 * <p>The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because
 * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the
 * signature, or you must be willing to try each recId in turn until you find one that outputs the key you are
 * expecting.</p>
 *
 * <p>If this method returns null it means recovery was not possible and recId should be iterated.</p>
 *
 * <p>Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the
 * output is null OR a key that is not the one you expect, you try again with the next recId.</p>
 *
 * @param recId Which possible key to recover.
 * @param sig the R and S components of the signature, wrapped.
 * @param messageHash Hash of the data that was signed.
 * @param compressed Whether or not the original pubkey was compressed.
 * @return An ECKey containing only the public part, or null if recovery wasn't possible.
 */
@Nullable
public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed) {
    check(recId >= 0, "recId must be positive");
    check(sig.r.signum() >= 0, "r must be positive");
    check(sig.s.signum() >= 0, "s must be positive");
    check(messageHash != null, "messageHash must not be null");
    // 1.0 For j from 0 to h   (h == recId here and the loop is outside this function)
    //   1.1 Let x = r + jn
    BigInteger n = CURVE.getN();  // Curve order.
    BigInteger i = BigInteger.valueOf((long) recId / 2);
    BigInteger x = sig.r.add(i.multiply(n));
    //   1.2. Convert the integer x to an octet string X of length mlen using the conversion routine
    //        specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
    //   1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R using the
    //        conversion routine specified in Section 2.3.4. If this conversion routine outputs “invalid”, then
    //        do another iteration of Step 1.
    //
    // More concisely, what these points mean is to use X as a compressed public key.
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ();  // Bouncy Castle is not consistent about the letter it uses for the prime.
    if (x.compareTo(prime) >= 0) {
        // Cannot have point co-ordinates larger than this as everything takes place modulo Q.
        return null;
    }
    // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    //   1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).
    if (!R.multiply(n).isInfinity())
        return null;
    //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
    BigInteger e = new BigInteger(1, messageHash);
    //   1.6. For k from 1 to 2 do the following.   (loop is outside this function via iterating recId)
    //   1.6.1. Compute a candidate public key as:
    //               Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
    //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). In the above equation
    // ** is point multiplication and + is point addition (the EC group operator).
    //
    // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = sig.r.modInverse(n);
    BigInteger srInv = rInv.multiply(sig.s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
    return ECKey.fromPublicOnly(q.getEncoded(compressed));
}
 
Example 6
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);
    }
}