org.spongycastle.math.ec.ECPoint Java Examples

The following examples show how to use org.spongycastle.math.ec.ECPoint. 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 6 votes vote down vote up
/**
 * Pair a private key with a public EC point.
 *
 * <p>All private key operations will use the provider.
 */
public ECKeySecp256k1(Provider provider, PrivateKey privKey, ECPoint pub) {
    this.provider = provider;

    if (privKey == null || isECPrivateKey(privKey)) {
        this.privKey = privKey;
    } else {
        throw new IllegalArgumentException(
                "Expected EC private key, given a private key object with class "
                        + privKey.getClass().toString()
                        + " and algorithm "
                        + privKey.getAlgorithm());
    }

    if (pub == null) {
        throw new IllegalArgumentException("Public key may not be null");
    } else {
        this.pub = pub;
    }
}
 
Example #2
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point. <p> All private key operations will use the
 * provider.
 */
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
  this.provider = provider;

  if (privKey == null || isECPrivateKey(privKey)) {
    this.privKey = privKey;
  } else {
    throw new IllegalArgumentException(
        "Expected EC private key, given a private key object with" +
            " class " +
            privKey.getClass().toString() +
            " and algorithm " + privKey.getAlgorithm());
  }

  if (pub == null) {
    throw new IllegalArgumentException("Public key may not be null");
  } else {
    this.pub = pub;
  }
}
 
Example #3
Source File: ECKey.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Pair a private key with a public EC point.
 *
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
  this.provider = provider;

  if (privKey == null || isECPrivateKey(privKey)) {
    this.privKey = privKey;
  } else {
    throw new IllegalArgumentException(
        "Expected EC private key, given a private key object with class "
            + privKey.getClass()
            + " and algorithm "
            + privKey.getAlgorithm());
  }

  if (pub == null) {
    throw new IllegalArgumentException("Public key may not be null");
  } else {
    this.pub = pub;
  }
}
 
Example #4
Source File: ECKeyPair.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public static ECKeyPair createNew(boolean compressed) {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain,
            secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    ECKeyPair k = new ECKeyPair();
    k.priv = privParams.getD();
    k.compressed = compressed;
    ECPoint multiply = CURVE.getG().multiply(k.priv);
    k.pub = multiply.getEncoded(false);
    k.pubComp = multiply.getEncoded(true);
    return k;
}
 
Example #5
Source File: ECKey.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns public key point from the given private key. To convert a byte array into a BigInteger, use <tt>
 * new BigInteger(1, bytes);</tt>
 */
public static ECPoint publicPointFromPrivate(BigInteger privKey) {
    /*
     * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group order,
     * but that could change in future versions.
     */
    if (privKey.bitLength() > CURVE.getN().bitLength()) {
        privKey = privKey.mod(CURVE.getN());
    }
    return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
 
Example #6
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static ECPoint getPointWithCompression(ECPoint point, boolean compressed) {
  if (point.isCompressed() == compressed)
    return point;
  point = point.normalize();
  BigInteger x = point.getAffineXCoord().toBigInteger();
  BigInteger y = point.getAffineYCoord().toBigInteger();
  return CURVE.getCurve().createPoint(x, y, compressed);
}
 
Example #7
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decompress a compressed public key (x co-ord and low-bit of y-coord).
 *
 * @param xBN  -
 * @param yBit -
 * @return -
 */

private static ECPoint decompressKey(BigInteger xBN, boolean yBit) {
    X9IntegerConverter x9 = new X9IntegerConverter();
    byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE
            .getCurve()));
    compEnc[0] = (byte) (yBit ? 0x03 : 0x02);
    return CURVE.getCurve().decodePoint(compEnc);
}
 
Example #8
Source File: ECKey.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns public key point from the given private key. To convert a byte array into a BigInteger, use <tt>
 * new BigInteger(1, bytes);</tt>
 */
public static ECPoint publicPointFromPrivate(BigInteger privKey) {
    /*
     * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group order,
     * but that could change in future versions.
     */
    if (privKey.bitLength() > CURVE.getN().bitLength()) {
        privKey = privKey.mod(CURVE.getN());
    }
    return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
 
Example #9
Source File: DeterministicKey.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public DeterministicKey(ImmutableList<ChildNumber> childNumberPath,
                        byte[] chainCode,
                        ECPoint publicAsPoint,
                        @Nullable BigInteger priv,
                        @Nullable DeterministicKey parent) {
    this(childNumberPath, chainCode, new LazyECPoint(publicAsPoint), priv, parent);
}
 
Example #10
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 #11
Source File: ECKey.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) {
    final java.security.spec.ECPoint publicPointW = ecPublicKey.getW();
    final BigInteger xCoord = publicPointW.getAffineX();
    final BigInteger yCoord = publicPointW.getAffineY();

    return CURVE.getCurve().createPoint(xCoord, yCoord);
}
 
Example #12
Source File: DeterministicKey.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public DeterministicKey(ImmutableList<ChildNumber> childNumberPath,
                        byte[] chainCode,
                        ECPoint publicAsPoint,
                        @Nullable BigInteger priv,
                        @Nullable DeterministicKey parent) {
    this(childNumberPath, chainCode, new LazyECPoint(publicAsPoint), priv, parent);
}
 
Example #13
Source File: CryptProcessor.java    From bitseal with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Encrypts the given data using the supplied public key.<br><br>
 * 
 * See https://bitmessage.org/wiki/Encryption and https://bitmessage.org/forum/index.php?topic=2848.0
 * 
 * @param plain - A byte[] containing the data to be encrypted.
 * @param K - An ECPublicKey object containing the public key 'K' to encrypt the data with.
 * 
 * @return A byte[] containing the encrypted payload.
 */
public byte[] encrypt (byte[] plain, ECPublicKey K)
{
	KeyPair random = generateEncryptionKeyPair();
	ECPublicKey R = (ECPublicKey) random.getPublic();
	BigInteger r = ((ECPrivateKey)random.getPrivate()).getD();
	
	ECPoint P = K.getQ().multiply(r);

	byte[] tmpKey = deriveKey(P);
	byte[] key_e = ArrayCopier.copyOfRange(tmpKey, 0, 32);
	byte[] key_m = ArrayCopier.copyOfRange(tmpKey, 32, 64);

	byte[] iv = new byte[16];
	new SecureRandom().nextBytes(iv);

	byte[] cipherText = doAES(key_e, iv, plain, true);
	
	byte[] x = ByteUtils.getUnsignedBytes(R.getQ().getX().toBigInteger(), 32);
	byte[] y = ByteUtils.getUnsignedBytes(R.getQ().getY().toBigInteger(), 32);

	int xLength = x.length;
	int yLength = y.length;
	
	byte[] encodedR = ByteUtils.concatenateByteArrays(ByteUtils.shortToBytes((short) 714), ByteUtils.shortToBytes((short) xLength), x, ByteUtils.shortToBytes((short) yLength), y);
	
	byte[] dataForMac = ByteUtils.concatenateByteArrays(iv, encodedR, cipherText);
	byte[] mac = SHA256.hmacSHA256(dataForMac, key_m);

	byte[] encryptedPayload = ByteUtils.concatenateByteArrays(iv, encodedR, cipherText, mac);
	
	return encryptedPayload;
}
 
Example #14
Source File: DeterministicKey.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public DeterministicKey(ImmutableList<ChildNumber> childNumberPath,
                        byte[] chainCode,
                        ECPoint publicAsPoint,
                        @Nullable BigInteger priv,
                        @Nullable DeterministicKey parent) {
    this(childNumberPath, chainCode, new LazyECPoint(publicAsPoint), priv, parent);
}
 
Example #15
Source File: ECKeySecp256k1.java    From aion with MIT License 5 votes vote down vote up
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) {
    final java.security.spec.ECPoint publicPointW = ecPublicKey.getW();
    final BigInteger xCoord = publicPointW.getAffineX();
    final BigInteger yCoord = publicPointW.getAffineY();

    return CURVE.getCurve().createPoint(xCoord, yCoord);
}
 
Example #16
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
/** Decompress a compressed public key (x co-ord and low-bit of y-coord). */
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) {
    X9IntegerConverter x9 = new X9IntegerConverter();
    byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve()));
    compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
    return CURVE.getCurve().decodePoint(compEnc);
}
 
Example #17
Source File: ECIESCoder.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
/**
     *  Encryption equivalent to the Crypto++ default ECIES<ECP> settings:
     *
     *  DL_KeyAgreementAlgorithm:        DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> >
     *  DL_KeyDerivationAlgorithm:       DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> >
     *  DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0>
     *  DL_PrivateKey:                   DL_Key<ECPPoint>
     *  DL_PrivateKey_EC<class ECP>
     *
     *  Used for Whisper V3
     */
    public static byte[] encryptSimple(ECPoint pub, byte[] plaintext) throws IOException, InvalidCipherTextException {
        EthereumIESEngine iesEngine = new EthereumIESEngine(
                new ECDHBasicAgreement(),
                new MGF1BytesGeneratorExt(new SHA1Digest(), 1),
                new HMac(new SHA1Digest()),
                new SHA1Digest(),
                null);

        IESParameters p = new IESParameters(null, null, KEY_SIZE);
        ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]);

        iesEngine.setHashMacKey(false);

        ECKeyPairGenerator eGen = new ECKeyPairGenerator();
        SecureRandom random = new SecureRandom();
        KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random);
        eGen.init(gParam);

//        AsymmetricCipherKeyPairGenerator testGen = new AsymmetricCipherKeyPairGenerator() {
//            ECKey priv = ECKey.fromPrivate(Hex.decode("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a"));
//
//            @Override
//            public void init(KeyGenerationParameters keyGenerationParameters) {
//            }
//
//            @Override
//            public AsymmetricCipherKeyPair generateKeyPair() {
//                return new AsymmetricCipherKeyPair(new ECPublicKeyParameters(priv.getPubKeyPoint(), CURVE),
//                        new ECPrivateKeyParameters(priv.getPrivKey(), CURVE));
//            }
//        };

        EphemeralKeyPairGenerator ephemeralKeyPairGenerator =
                new EphemeralKeyPairGenerator(/*testGen*/eGen, new ECIESPublicKeyEncoder());

        iesEngine.init(new ECPublicKeyParameters(pub, CURVE), parametersWithIV, ephemeralKeyPairGenerator);

        return iesEngine.processBlock(plaintext, 0, plaintext.length);
    }
 
Example #18
Source File: ECKey.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 根据私匙和公匙创建
 * @param priv
 * @param pub
 */
private ECKey(BigInteger priv, ECPoint pub) {
    if (priv != null) {
        //私匙不应该是0和1
        Util.checkState(!priv.equals(BigInteger.ZERO));
        Util.checkState(!priv.equals(BigInteger.ONE));
    }
    this.priv = priv;
    this.pub = Util.checkNotNull(pub);
    creationTimeSeconds = System.currentTimeMillis();
}
 
Example #19
Source File: ECKey.java    From ethereumj with MIT License 5 votes vote down vote up
/** Decompress a compressed public key (x co-ord and low-bit of y-coord). */
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) {
    X9IntegerConverter x9 = new X9IntegerConverter();
    byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve()));
    compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
    return CURVE.getCurve().decodePoint(compEnc);
}
 
Example #20
Source File: ECKey.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, use <tt>
 * new BigInteger(1, bytes);</tt>
 */
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
    ECPoint point = CURVE.getG().multiply(privKey);
    if (compressed)
        point = compressPoint(point);
    return point.getEncoded();
}
 
Example #21
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static ECPoint getPointWithCompression(ECPoint point, boolean compressed) {
  if (point.isCompressed() == compressed)
    return point;
  point = point.normalize();
  BigInteger x = point.getAffineXCoord().toBigInteger();
  BigInteger y = point.getAffineYCoord().toBigInteger();
  return CURVE.getCurve().createPoint(x, y, compressed);
}
 
Example #22
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) {
    final java.security.spec.ECPoint publicPointW = ecPublicKey.getW();
    final BigInteger xCoord = publicPointW.getAffineX();
    final BigInteger yCoord = publicPointW.getAffineY();

    return CURVE.getCurve().createPoint(xCoord, yCoord);
}
 
Example #23
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
private ECKey(BigInteger priv, ECPoint pub) {
  this.priv = priv;
  this.pub = new LazyECPoint(pub);
}
 
Example #24
Source File: ECKey.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
private static ECPoint publicPointFromPrivate(BigInteger privKey) {
  if (privKey.bitLength() > CURVE.getN().bitLength()) {
    privKey = privKey.mod(CURVE.getN());
  }
  return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
 
Example #25
Source File: Secp256r1SC.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static ECPoint decode(final byte[] toAdd) {
    return CURVE.getCurve().decodePoint(toAdd);
}
 
Example #26
Source File: LazyECPoint.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public LazyECPoint(ECPoint point) {
  this.point = checkNotNull(point);
  this.curve = null;
  this.bits = null;
}
 
Example #27
Source File: LazyECPoint.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public ECPoint get() {
    if (point == null)
        point = curve.decodePoint(bits);
    return point;
}
 
Example #28
Source File: Secp256r1SC.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static ECPoint gMultiply(BigInteger p) {
    return CURVE.getG()
            .multiply(p);
}
 
Example #29
Source File: LazyECPoint.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public ECPoint get() {
  if (point == null)
    point = curve.decodePoint(bits);
  return point;
}
 
Example #30
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);
}