org.bouncycastle.math.ec.ECAlgorithms Java Examples
The following examples show how to use
org.bouncycastle.math.ec.ECAlgorithms.
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: ECDSA.java From bushido-java-core with GNU General Public License v3.0 | 6 votes |
private boolean hasError(ECDSASignature signature) { final BigInteger r = signature.r; final BigInteger s = signature.s; if (!(r.compareTo(BigInteger.ZERO) == 1 && r.compareTo(key.params.getN()) == -1) || !(s.compareTo(BigInteger.ZERO) == 1 && s.compareTo(key.params.getN()) == -1)) { //r and s not in range return true; } final BigInteger e = BigIntegerUtil.fromBytes(hashbuf, 16, endian); final BigInteger n = key.params.getN(); final BigInteger sinv = s.modInverse(n); final BigInteger u1 = sinv.multiply(e).mod(n); final BigInteger u2 = sinv.multiply(r).mod(n); final ECPoint g = key.params.getG(); final ECPoint p = ECAlgorithms.sumOfTwoMultiplies(g, u1, key.curve.getCurve().decodePoint(key.getPublic()), u2).normalize(); if (p.isInfinity()) { //p is infinity return true; } if (p.getAffineXCoord().toBigInteger().mod(n).compareTo(r) != 0) { //invalid signature return true; } else { return false; } }
Example #2
Source File: SM2PreprocessSigner.java From gmhelper with Apache License 2.0 | 5 votes |
private boolean verifySignature(byte[] eHash, BigInteger r, BigInteger s) { BigInteger n = ecParams.getN(); // 5.3.1 Draft RFC: SM2 Public Key Algorithms // B1 if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { return false; } // B2 if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { return false; } // B3 eHash // B4 BigInteger e = calculateE(eHash); // B5 BigInteger t = r.add(s).mod(n); if (t.equals(ZERO)) { return false; } // B6 ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); ECPoint x1y1 = ECAlgorithms.sumOfTwoMultiplies(ecParams.getG(), s, q, t).normalize(); if (x1y1.isInfinity()) { return false; } // B7 BigInteger expectedR = e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n); return expectedR.equals(r); }
Example #3
Source File: Signer.java From evt4j with MIT License | 5 votes |
/** * 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). */ @Override 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 #4
Source File: SM2Signer.java From web3sdk with Apache License 2.0 | 5 votes |
private boolean verifySignature(BigInteger r, BigInteger s) { BigInteger n = ecParams.getN(); // 5.3.1 Draft RFC: SM2 Public Key Algorithms // B1 if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { return false; } // B2 if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { return false; } // B3 byte[] eHash = digestDoFinal(); // B4 BigInteger e = calculateE(eHash); // B5 BigInteger t = r.add(s).mod(n); if (t.equals(ZERO)) { return false; } // B6 ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); ECPoint x1y1 = ECAlgorithms.sumOfTwoMultiplies(ecParams.getG(), s, q, t).normalize(); if (x1y1.isInfinity()) { return false; } // B7 BigInteger expectedR = e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n); return expectedR.equals(r); }
Example #5
Source File: SECP256K1.java From incubator-tuweni with Apache License 2.0 | 4 votes |
/** * 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 recovery id 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 recovery id 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 recovery id 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 recovery id. * * @param v Which possible key to recover. * @param r The R component of the signature. * @param s The S component of the signature. * @param messageHash Hash of the data that was signed. * @return A ECKey containing only the public part, or {@code null} if recovery wasn't possible. */ @Nullable private static BigInteger recoverFromSignature(int v, BigInteger r, BigInteger s, Bytes32 messageHash) { assert (v == 0 || v == 1); assert (r.signum() >= 0); assert (s.signum() >= 0); assert (messageHash != 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 recovery id (v). ECPoint R = decompressKey(r, (v & 1) == 1); // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility). if (R == null || !R.multiply(Parameters.CURVE_ORDER).isInfinity()) { return null; } // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. BigInteger e = messageHash.toUnsignedBigInteger(); // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating v) // 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(Parameters.CURVE_ORDER); BigInteger rInv = r.modInverse(Parameters.CURVE_ORDER); BigInteger srInv = rInv.multiply(s).mod(Parameters.CURVE_ORDER); BigInteger eInvrInv = rInv.multiply(eInv).mod(Parameters.CURVE_ORDER); ECPoint q = ECAlgorithms.sumOfTwoMultiplies(Parameters.CURVE.getG(), eInvrInv, R, srInv); if (q.isInfinity()) { return null; } byte[] qBytes = q.getEncoded(false); // We remove the prefix return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length)); }
Example #6
Source File: ECKey.java From javasdk with GNU Lesser General Public License v3.0 | 4 votes |
/** * <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 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> * <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 */ 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 #7
Source File: SECP256K1.java From cava with Apache License 2.0 | 4 votes |
/** * 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 recovery id 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 recovery id 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 recovery id 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 recovery id. * * @param v Which possible key to recover. * @param r The R component of the signature. * @param s The S component of the signature. * @param messageHash Hash of the data that was signed. * @return A ECKey containing only the public part, or {@code null} if recovery wasn't possible. */ @Nullable private static BigInteger recoverFromSignature(int v, BigInteger r, BigInteger s, Bytes32 messageHash) { assert (v == 0 || v == 1); assert (r.signum() >= 0); assert (s.signum() >= 0); assert (messageHash != 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 recovery id (v). ECPoint R = decompressKey(r, (v & 1) == 1); // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility). if (R == null || !R.multiply(Parameters.CURVE_ORDER).isInfinity()) { return null; } // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. BigInteger e = messageHash.toUnsignedBigInteger(); // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating v) // 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(Parameters.CURVE_ORDER); BigInteger rInv = r.modInverse(Parameters.CURVE_ORDER); BigInteger srInv = rInv.multiply(s).mod(Parameters.CURVE_ORDER); BigInteger eInvrInv = rInv.multiply(eInv).mod(Parameters.CURVE_ORDER); ECPoint q = ECAlgorithms.sumOfTwoMultiplies(Parameters.CURVE.getG(), eInvrInv, R, srInv); if (q.isInfinity()) { return null; } byte[] qBytes = q.getEncoded(false); // We remove the prefix return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length)); }
Example #8
Source File: ECDSASigner.java From web3sdk with Apache License 2.0 | 4 votes |
/** * 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). */ @Override 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); // components must be bogus. if (point.isInfinity()) { return false; } /* * If possible, avoid normalizing the point (to save a modular inversion in the curve field). * * There are ~cofactor elements of the curve field that reduce (modulo the group order) to 'r'. * If the cofactor is known and small, we generate those possible field values and project each * of them to the same "denominator" (depending on the particular projective coordinates in use) * as the calculated point.X. If any of the projected values matches point.X, then we have: * (point.X / Denominator mod p) mod n == r * as required, and verification succeeds. * * Based on an original idea by Gregory Maxwell (https://github.com/gmaxwell), as implemented in * the libsecp256k1 project (https://github.com/bitcoin/secp256k1). */ ECCurve curve = point.getCurve(); if (curve != null) { BigInteger cofactor = curve.getCofactor(); if (cofactor != null && cofactor.compareTo(EIGHT) <= 0) { ECFieldElement D = getDenominator(curve.getCoordinateSystem(), point); if (D != null && !D.isZero()) { ECFieldElement X = point.getXCoord(); while (curve.isValidFieldElement(r)) { ECFieldElement R = curve.fromBigInteger(r).multiply(D); if (R.equals(X)) { return true; } r = r.add(n); } return false; } } } BigInteger v = point.normalize().getAffineXCoord().toBigInteger().mod(n); return v.equals(r); }
Example #9
Source File: EthereumUtil.java From hadoopcryptoledger with Apache License 2.0 | 4 votes |
/** * Calculates the sent address of an EthereumTransaction. Note this can be a costly operation to calculate. . This requires that you have Bouncy castle as a dependency in your project * * * @param eTrans transaction * @param chainId chain identifier (e.g. 1 main net) * @return sent address as byte array */ public static byte[] getSendAddress(EthereumTransaction eTrans, int chainId) { // init, maybe we move this out to save time X9ECParameters params = SECNamedCurves.getByName("secp256k1"); ECDomainParameters CURVE=new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH()); // needed for getSentAddress byte[] transactionHash; if ((eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC) || (eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC+1)) { // transaction hash with dummy signature data transactionHash = EthereumUtil.getTransactionHashWithDummySignatureEIP155(eTrans); } else { // transaction hash without signature data transactionHash = EthereumUtil.getTransactionHashWithoutSignature(eTrans); } // signature to address BigInteger bR = new BigInteger(1,eTrans.getSig_r()); BigInteger bS = new BigInteger(1,eTrans.getSig_s()); // calculate v for signature byte v =(byte) (eTrans.getSig_v()[0]); if (!((v == EthereumUtil.LOWER_REAL_V) || (v== (LOWER_REAL_V+1)))) { byte vReal = EthereumUtil.LOWER_REAL_V; if (((int)v%2 == 0)) { v = (byte) (vReal+0x01); } else { v = vReal; } } // the following lines are inspired from ECKey.java of EthereumJ, but adapted to the hadoopcryptoledger context if (v < 27 || v > 34) { LOG.error("Header out of Range: "+v); throw new RuntimeException("Header out of range "+v); } if (v>=31) { v -=4; } int receiverId = v - 27; BigInteger n = CURVE.getN(); BigInteger i = BigInteger.valueOf((long) receiverId / 2); BigInteger x = bR.add(i.multiply(n)); ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve(); BigInteger prime = curve.getQ(); if (x.compareTo(prime) >= 0) { return null; } // decompress Key X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(x, 1 + x9.getByteLength(CURVE.getCurve())); boolean yBit=(receiverId & 1) == 1; compEnc[0] = (byte)(yBit ? 0x03 : 0x02); ECPoint R = CURVE.getCurve().decodePoint(compEnc); if (!R.multiply(n).isInfinity()) { return null; } BigInteger e = new BigInteger(1,transactionHash); BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = bR.modInverse(n); BigInteger srInv = rInv.multiply(bS).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); byte[] pubKey=q.getEncoded(false); // now we need to convert the public key into an ethereum send address which is the last 20 bytes of 32 byte KECCAK-256 Hash of the key. Keccak.Digest256 digest256 = new Keccak.Digest256(); digest256.update(pubKey,1,pubKey.length-1); byte[] kcck = digest256.digest(); return Arrays.copyOfRange(kcck,12,kcck.length); }
Example #10
Source File: Signature.java From etherjar with Apache License 2.0 | 4 votes |
/** * * @return public key derived from current v,R,S and message */ // implementation is based on BitcoinJ ECKey code // see https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/core/ECKey.java public byte[] ecrecover() { int recId = getRecId(); SecP256K1Curve curve = (SecP256K1Curve)ecParams.getCurve(); BigInteger n = ecParams.getN(); // Let x = r + jn BigInteger i = BigInteger.valueOf((long)recId / 2); BigInteger x = r.add(i.multiply(n)); if (x.compareTo(curve.getQ()) >= 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); if (!R.multiply(n).isInfinity()) { // If nR != point at infinity, then recId (i.e. v) is invalid return null; } // // 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 e = new BigInteger(1, message); BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = r.modInverse(n); BigInteger srInv = rInv.multiply(s).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint q = ECAlgorithms.sumOfTwoMultiplies(ecParams.getG(), eInvrInv, R, srInv); // For Ethereum we don't use first byte of the key byte[] full = q.getEncoded(false); byte[] ethereum = new byte[full.length - 1]; System.arraycopy(full, 1, ethereum, 0, ethereum.length); return ethereum; }
Example #11
Source File: ECPointsCompact.java From InflatableDonkey with MIT License | 4 votes |
@Deprecated public static boolean satisfiesCofactor(ECCurve curve, ECPoint point) { // Patched org.bouncycastle.math.ec.ECPoint#satisfiesCofactor protected code. BigInteger h = curve.getCofactor(); return h == null || h.equals(ECConstants.ONE) || !ECAlgorithms.referenceMultiply(point, h).isInfinity(); }