Java Code Examples for org.bouncycastle.crypto.params.ECDomainParameters#getN()

The following examples show how to use org.bouncycastle.crypto.params.ECDomainParameters#getN() . 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: BCECUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
        throws NoSuchProviderException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
            domainParameters.getN(), domainParameters.getH());
    kpg.initialize(parameterSpec, random);
    return kpg.generateKeyPair();
}
 
Example 2
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * 将ECC公钥对象转换为X509标准的字节流
 *
 * @param pubKey
 * @return
 */
public static byte[] convertECPublicKeyToX509(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
            domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
            BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example 3
Source File: Sm2KeyPairImpl.java    From littleca with Apache License 2.0 5 votes vote down vote up
public Sm2KeyPairImpl(boolean selfgen) {
	SecureRandom random = new SecureRandom();
	ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS, random);
	ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
	keyGen.init(keyGenerationParams);
	AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair();
	ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
	ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();
	ECDomainParameters domainParams = priKey.getParameters();
	ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(), domainParams.getN(),
			domainParams.getH());
	BCECPublicKey bcecPublicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec, BouncyCastleProvider.CONFIGURATION);
	publicKey = new Sm2PublicKeyImpl(bcecPublicKey);
	privateKey = new Sm2PrivateKeyImpl(new BCECPrivateKey(ALGO_NAME_EC, priKey, bcecPublicKey, spec, BouncyCastleProvider.CONFIGURATION));
}
 
Example 4
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static byte[] convertEcPubKeyToX509Der(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
        domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
        BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example 5
Source File: Signer.java    From evt4j with MIT License 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).
 */
@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 6
Source File: ECDSASigner.java    From web3sdk with Apache License 2.0 5 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.
 */
@Override
public BigInteger[] generateSignature(byte[] message) {
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);
    BigInteger d = ((ECPrivateKeyParameters) key).getD();

    if (kCalculator.isDeterministic()) {
        kCalculator.init(n, d, message);
    } else {
        kCalculator.init(n, random);
    }

    BigInteger r, s;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.3.2
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            k = kCalculator.nextK();

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

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

        s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
    } while (s.equals(ZERO));

    return new BigInteger[] {r, s};
}
 
Example 7
Source File: ECDSASigner.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * The same generateSignature with the temporary variable ECPoint P generated by the signature
 * process is also returned together
 *
 * @param message the message that will be verified later.
 */
public Object[] generateSignature2(byte[] message) {
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);
    BigInteger d = ((ECPrivateKeyParameters) key).getD();

    if (kCalculator.isDeterministic()) {
        kCalculator.init(n, d, message);
    } else {
        kCalculator.init(n, random);
    }

    BigInteger r, s;

    /** */
    ECPoint p;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    // 5.3.2
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            k = kCalculator.nextK();

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

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

        s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
    } while (s.equals(ZERO));

    return new Object[] {r, s, p};
}
 
Example 8
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
    throws NoSuchProviderException, NoSuchAlgorithmException,
    InvalidAlgorithmParameterException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
        domainParameters.getN(), domainParameters.getH());
    kpg.initialize(parameterSpec, random);
    return kpg.generateKeyPair();
}
 
Example 9
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
/**
 * 将ECC公钥对象转换为X509标准的字节流
 *
 * @param pubKey
 * @return
 */
public static byte[] convertECPublicKeyToX509(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
        domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
        BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example 10
Source File: Signer.java    From evt4j with MIT License 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.
 */
@Override
public BigInteger[] generateSignature(byte[] message) {
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);
    BigInteger d = ((ECPrivateKeyParameters) key).getD();

    if (kCalculator.isDeterministic()) {
        kCalculator.init(n, d, message);
    } else {
        kCalculator.init(n, random);
    }

    BigInteger r, s;

    ECMultiplier basePointMultiplier = createBasePointMultiplier();

    int sLen = 0;
    // 5.3.2
    do // generate s
    {
        BigInteger k;
        int rLen = 0;
        do // generate r
        {
            k = kCalculator.nextK();

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

            // 5.3.3
            r = p.getAffineXCoord().toBigInteger().mod(n);
            rLen = r.toByteArray().length;
        } while (r.equals(ZERO) || rLen != 32); // make sure that length of r is 32 bytes

        s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n);
        sLen = s.toByteArray().length;
    } while (s.equals(ZERO) || sLen != 32);

    return new BigInteger[] { r, s };
}
 
Example 11
Source File: ECDSASigner.java    From web3sdk with Apache License 2.0 4 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).
 */
@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 12
Source File: EthereumUtil.java    From hadoopcryptoledger with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}